commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
99947acb784d975319bd99240abed066a4f0a51f
|
pytablewriter/_converter.py
|
pytablewriter/_converter.py
|
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def str_datetime_converter(value):
return value.strftime("%Y-%m-%dT%H:%M:%S%z")
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
Add a converter which convert datetime to string
|
Add a converter which convert datetime to string
|
Python
|
mit
|
thombashi/pytablewriter
|
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
+ def str_datetime_converter(value):
+ return value.strftime("%Y-%m-%dT%H:%M:%S%z")
+
+
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
Add a converter which convert datetime to string
|
## Code Before:
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
## Instruction:
Add a converter which convert datetime to string
## Code After:
from __future__ import absolute_import
import re
def lower_bool_converter(bool_value):
return str(bool_value).lower()
def str_datetime_converter(value):
return value.strftime("%Y-%m-%dT%H:%M:%S%z")
def strip_quote(text, value):
re_replace = re.compile(
'["\']%s["\']' % (value), re.MULTILINE)
return re_replace.sub(value, text)
|
# ... existing code ...
def str_datetime_converter(value):
return value.strftime("%Y-%m-%dT%H:%M:%S%z")
def strip_quote(text, value):
# ... rest of the code ...
|
eb1daa3edfaa72cad2cb39507b2db0bf95204561
|
markitup/renderers.py
|
markitup/renderers.py
|
from __future__ import unicode_literals
try:
from docutils.core import publish_parts
def render_rest(markup, **docutils_settings):
parts = publish_parts(source=markup, writer_name="html4css1", settings_overrides=docutils_settings)
return parts["html_body"]
except ImportError:
pass
|
from __future__ import unicode_literals
try:
from docutils.core import publish_parts
def render_rest(markup, **docutils_settings):
docutils_settings.update({
'raw_enabled': False,
'file_insertion_enabled': False,
})
parts = publish_parts(
source=markup,
writer_name="html4css1",
settings_overrides=docutils_settings,
)
return parts["html_body"]
except ImportError:
pass
|
Enforce better security in sample ReST renderer.
|
Enforce better security in sample ReST renderer.
|
Python
|
bsd-3-clause
|
WimpyAnalytics/django-markitup,carljm/django-markitup,WimpyAnalytics/django-markitup,zsiciarz/django-markitup,zsiciarz/django-markitup,carljm/django-markitup,WimpyAnalytics/django-markitup,carljm/django-markitup,zsiciarz/django-markitup
|
from __future__ import unicode_literals
try:
from docutils.core import publish_parts
+
def render_rest(markup, **docutils_settings):
- parts = publish_parts(source=markup, writer_name="html4css1", settings_overrides=docutils_settings)
+ docutils_settings.update({
+ 'raw_enabled': False,
+ 'file_insertion_enabled': False,
+ })
+
+ parts = publish_parts(
+ source=markup,
+ writer_name="html4css1",
+ settings_overrides=docutils_settings,
+ )
return parts["html_body"]
except ImportError:
pass
|
Enforce better security in sample ReST renderer.
|
## Code Before:
from __future__ import unicode_literals
try:
from docutils.core import publish_parts
def render_rest(markup, **docutils_settings):
parts = publish_parts(source=markup, writer_name="html4css1", settings_overrides=docutils_settings)
return parts["html_body"]
except ImportError:
pass
## Instruction:
Enforce better security in sample ReST renderer.
## Code After:
from __future__ import unicode_literals
try:
from docutils.core import publish_parts
def render_rest(markup, **docutils_settings):
docutils_settings.update({
'raw_enabled': False,
'file_insertion_enabled': False,
})
parts = publish_parts(
source=markup,
writer_name="html4css1",
settings_overrides=docutils_settings,
)
return parts["html_body"]
except ImportError:
pass
|
// ... existing code ...
from docutils.core import publish_parts
def render_rest(markup, **docutils_settings):
docutils_settings.update({
'raw_enabled': False,
'file_insertion_enabled': False,
})
parts = publish_parts(
source=markup,
writer_name="html4css1",
settings_overrides=docutils_settings,
)
return parts["html_body"]
// ... rest of the code ...
|
180062c4d1159185ab113e98f41bb219d52086e8
|
test.py
|
test.py
|
from pyserializable import serialize, deserialize, autoserialized
from pyserializable.util import repr_func
@autoserialized
class Color:
serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8'
serial_attr_converters = {'r': [int, str]}
__repr__ = repr_func('r', 'g', 'b', 'a')
@autoserialized
class Tile:
serial_format = 'enabled=uint:1, color=Color, elite=uint:1'
serial_fmt_converters = {'uint:1': [int, bool]}
__repr__ = repr_func('enabled', 'color', 'elite')
t = Tile()
t.enabled = False
t.elite = True
t.color = Color()
t.color.r = '201'
t.color.g = 202
t.color.b = 203
t.color.a = 204
data = serialize(t)
# Deserialize based on class
t2 = deserialize(Tile, data)
#Deserialize into existing instance
t3 = Tile()
deserialize(t3, data)
print(t)
print(t2)
print(t3)
|
from pyserializable import serialize, deserialize, autoserialized
from pyserializable.util import repr_func
@autoserialized
class Color(object):
serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8'
serial_attr_converters = {'r': [int, str]}
__repr__ = repr_func('r', 'g', 'b', 'a')
@autoserialized
class Tile(object):
serial_format = 'enabled=uint:1, color=Color, elite=uint:1'
serial_fmt_converters = {'uint:1': [int, bool]}
__repr__ = repr_func('enabled', 'color', 'elite')
t = Tile()
t.enabled = False
t.elite = True
t.color = Color()
t.color.r = '201'
t.color.g = 202
t.color.b = 203
t.color.a = 204
data = serialize(t)
# Deserialize based on class
t2 = deserialize(Tile, data)
#Deserialize into existing instance
t3 = Tile()
deserialize(t3, data)
print(t)
print(t2)
print(t3)
|
Fix base class for python 2.x
|
Fix base class for python 2.x
|
Python
|
mit
|
numberoverzero/origami
|
from pyserializable import serialize, deserialize, autoserialized
from pyserializable.util import repr_func
@autoserialized
- class Color:
+ class Color(object):
serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8'
serial_attr_converters = {'r': [int, str]}
__repr__ = repr_func('r', 'g', 'b', 'a')
@autoserialized
- class Tile:
+ class Tile(object):
serial_format = 'enabled=uint:1, color=Color, elite=uint:1'
serial_fmt_converters = {'uint:1': [int, bool]}
__repr__ = repr_func('enabled', 'color', 'elite')
t = Tile()
t.enabled = False
t.elite = True
t.color = Color()
t.color.r = '201'
t.color.g = 202
t.color.b = 203
t.color.a = 204
data = serialize(t)
# Deserialize based on class
t2 = deserialize(Tile, data)
#Deserialize into existing instance
t3 = Tile()
deserialize(t3, data)
print(t)
print(t2)
print(t3)
|
Fix base class for python 2.x
|
## Code Before:
from pyserializable import serialize, deserialize, autoserialized
from pyserializable.util import repr_func
@autoserialized
class Color:
serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8'
serial_attr_converters = {'r': [int, str]}
__repr__ = repr_func('r', 'g', 'b', 'a')
@autoserialized
class Tile:
serial_format = 'enabled=uint:1, color=Color, elite=uint:1'
serial_fmt_converters = {'uint:1': [int, bool]}
__repr__ = repr_func('enabled', 'color', 'elite')
t = Tile()
t.enabled = False
t.elite = True
t.color = Color()
t.color.r = '201'
t.color.g = 202
t.color.b = 203
t.color.a = 204
data = serialize(t)
# Deserialize based on class
t2 = deserialize(Tile, data)
#Deserialize into existing instance
t3 = Tile()
deserialize(t3, data)
print(t)
print(t2)
print(t3)
## Instruction:
Fix base class for python 2.x
## Code After:
from pyserializable import serialize, deserialize, autoserialized
from pyserializable.util import repr_func
@autoserialized
class Color(object):
serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8'
serial_attr_converters = {'r': [int, str]}
__repr__ = repr_func('r', 'g', 'b', 'a')
@autoserialized
class Tile(object):
serial_format = 'enabled=uint:1, color=Color, elite=uint:1'
serial_fmt_converters = {'uint:1': [int, bool]}
__repr__ = repr_func('enabled', 'color', 'elite')
t = Tile()
t.enabled = False
t.elite = True
t.color = Color()
t.color.r = '201'
t.color.g = 202
t.color.b = 203
t.color.a = 204
data = serialize(t)
# Deserialize based on class
t2 = deserialize(Tile, data)
#Deserialize into existing instance
t3 = Tile()
deserialize(t3, data)
print(t)
print(t2)
print(t3)
|
# ... existing code ...
@autoserialized
class Color(object):
serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8'
# ... modified code ...
@autoserialized
class Tile(object):
serial_format = 'enabled=uint:1, color=Color, elite=uint:1'
# ... rest of the code ...
|
01ca6c2c71b8558e119ae4448e02c2c84a5ef6f9
|
mailviews/tests/urls.py
|
mailviews/tests/urls.py
|
from mailviews.utils import is_django_version_greater
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
|
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
|
Remove unused import on test url's
|
Remove unused import on test url's
|
Python
|
apache-2.0
|
disqus/django-mailviews,disqus/django-mailviews
|
- from mailviews.utils import is_django_version_greater
-
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
|
Remove unused import on test url's
|
## Code Before:
from mailviews.utils import is_django_version_greater
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
## Instruction:
Remove unused import on test url's
## Code After:
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
|
# ... existing code ...
from django.conf.urls import include, url
# ... rest of the code ...
|
af2b561cd1a25fc4abd7c7948e5ff8ceb507a497
|
tests/cli/test_rasa_shell.py
|
tests/cli/test_rasa_shell.py
|
from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN]
[--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
[--ssl-certificate SSL_CERTIFICATE]
[--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE]
[--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS]
[--connector CONNECTOR] [--jwt-secret JWT_SECRET]
[--jwt-method JWT_METHOD]
{nlu} ... [model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
def test_shell_nlu_help(run: Callable[..., RunResult]):
output = run("shell", "nlu", "--help")
help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL]
[model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
|
from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
[--conversation-id CONVERSATION_ID] [-m MODEL]
[--log-file LOG_FILE] [--endpoints ENDPOINTS] [-p PORT]
[-t AUTH_TOKEN] [--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
[--ssl-certificate SSL_CERTIFICATE]
[--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE]
[--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS]
[--connector CONNECTOR] [--jwt-secret JWT_SECRET]
[--jwt-method JWT_METHOD]
{nlu} ... [model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
def test_shell_nlu_help(run: Callable[..., RunResult]):
output = run("shell", "nlu", "--help")
help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL]
[model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
|
Adjust rasa shell help test to changes.
|
Adjust rasa shell help test to changes.
|
Python
|
apache-2.0
|
RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu
|
from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
- help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
+ help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
- [--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN]
+ [--conversation-id CONVERSATION_ID] [-m MODEL]
+ [--log-file LOG_FILE] [--endpoints ENDPOINTS] [-p PORT]
- [--cors [CORS [CORS ...]]] [--enable-api]
+ [-t AUTH_TOKEN] [--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
[--ssl-certificate SSL_CERTIFICATE]
[--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE]
[--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS]
[--connector CONNECTOR] [--jwt-secret JWT_SECRET]
[--jwt-method JWT_METHOD]
{nlu} ... [model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
def test_shell_nlu_help(run: Callable[..., RunResult]):
output = run("shell", "nlu", "--help")
help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL]
[model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
|
Adjust rasa shell help test to changes.
|
## Code Before:
from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN]
[--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
[--ssl-certificate SSL_CERTIFICATE]
[--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE]
[--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS]
[--connector CONNECTOR] [--jwt-secret JWT_SECRET]
[--jwt-method JWT_METHOD]
{nlu} ... [model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
def test_shell_nlu_help(run: Callable[..., RunResult]):
output = run("shell", "nlu", "--help")
help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL]
[model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
## Instruction:
Adjust rasa shell help test to changes.
## Code After:
from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
[--conversation-id CONVERSATION_ID] [-m MODEL]
[--log-file LOG_FILE] [--endpoints ENDPOINTS] [-p PORT]
[-t AUTH_TOKEN] [--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
[--ssl-certificate SSL_CERTIFICATE]
[--ssl-keyfile SSL_KEYFILE] [--ssl-ca-file SSL_CA_FILE]
[--ssl-password SSL_PASSWORD] [--credentials CREDENTIALS]
[--connector CONNECTOR] [--jwt-secret JWT_SECRET]
[--jwt-method JWT_METHOD]
{nlu} ... [model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
def test_shell_nlu_help(run: Callable[..., RunResult]):
output = run("shell", "nlu", "--help")
help_text = """usage: rasa shell nlu [-h] [-v] [-vv] [--quiet] [-m MODEL]
[model-as-positional-argument]"""
lines = help_text.split("\n")
for i, line in enumerate(lines):
assert output.outlines[i] == line
|
// ... existing code ...
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
[--conversation-id CONVERSATION_ID] [-m MODEL]
[--log-file LOG_FILE] [--endpoints ENDPOINTS] [-p PORT]
[-t AUTH_TOKEN] [--cors [CORS [CORS ...]]] [--enable-api]
[--remote-storage REMOTE_STORAGE]
// ... rest of the code ...
|
2a6399a74110b6a9e0d48349c68775986c13a579
|
pyservice/context.py
|
pyservice/context.py
|
import collections
class Container(collections.defaultdict):
DEFAULT_FACTORY = lambda: None
def __init__(self):
super().__init__(self, Container.DEFAULT_FACTORY)
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
self[name] = value
class Context(object):
def __init__(self, service, operation):
self.service = service
self.operation = operation
def execute(self):
self.service.continue_execution(self)
|
import ujson
import collections
class Container(collections.defaultdict):
DEFAULT_FACTORY = lambda: None
def __init__(self):
super().__init__(self, Container.DEFAULT_FACTORY)
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
self[name] = value
class Context(object):
def __init__(self, service, operation, processor):
self.service = service
self.operation = operation
self.processor = processor
def process_request(self):
self.processor.continue_execution()
class Processor(object):
def __init__(self, service, operation, request_body):
self.service = service
self.operation = operation
self.context = Context(service, operation, self)
self.request = Container()
self.request_body = request_body
self.response = Container()
self.response_body = None
self.plugins = service.get_plugins(operation)
self.index = -1
self.state = "request" # request -> operation -> function
def execute(self):
self.context.process_request()
def continue_execution(self):
self.index += 1
plugins = self.plugins[self.state]
n = len(plugins)
if self.index > n:
# Terminal point so that service.invoke
# can safely call context.process_request()
return
elif self.index == n:
if self.state == "request":
self.index = -1
self.state = "operation"
self._deserialize_request()
self.continue_execution()
self._serialize_response()
elif self.state == "operation":
self.service.invoke(self.operation, self.request,
self.response, self.context)
# index < n
else:
if self.state == "request":
plugins[self.index](self.context)
elif self.state == "operation":
plugins[self.index](self.request, self.response, self.context)
def _deserialize_request(self):
self.request.update(ujson.loads(self.request_body))
def _serialize_response(self):
self.response_body = ujson.dumps(self.response)
|
Create class for request process recursion
|
Create class for request process recursion
|
Python
|
mit
|
numberoverzero/pyservice
|
+ import ujson
import collections
class Container(collections.defaultdict):
DEFAULT_FACTORY = lambda: None
def __init__(self):
super().__init__(self, Container.DEFAULT_FACTORY)
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
self[name] = value
class Context(object):
- def __init__(self, service, operation):
+ def __init__(self, service, operation, processor):
+ self.service = service
+ self.operation = operation
+ self.processor = processor
+
+ def process_request(self):
+ self.processor.continue_execution()
+
+
+ class Processor(object):
+ def __init__(self, service, operation, request_body):
self.service = service
self.operation = operation
+ self.context = Context(service, operation, self)
+ self.request = Container()
+ self.request_body = request_body
+ self.response = Container()
+ self.response_body = None
+
+ self.plugins = service.get_plugins(operation)
+
+ self.index = -1
+ self.state = "request" # request -> operation -> function
+
def execute(self):
- self.service.continue_execution(self)
+ self.context.process_request()
+ def continue_execution(self):
+ self.index += 1
+ plugins = self.plugins[self.state]
+ n = len(plugins)
+
+ if self.index > n:
+ # Terminal point so that service.invoke
+ # can safely call context.process_request()
+ return
+ elif self.index == n:
+ if self.state == "request":
+ self.index = -1
+ self.state = "operation"
+
+ self._deserialize_request()
+ self.continue_execution()
+ self._serialize_response()
+ elif self.state == "operation":
+ self.service.invoke(self.operation, self.request,
+ self.response, self.context)
+ # index < n
+ else:
+ if self.state == "request":
+ plugins[self.index](self.context)
+ elif self.state == "operation":
+ plugins[self.index](self.request, self.response, self.context)
+
+ def _deserialize_request(self):
+ self.request.update(ujson.loads(self.request_body))
+
+ def _serialize_response(self):
+ self.response_body = ujson.dumps(self.response)
+
|
Create class for request process recursion
|
## Code Before:
import collections
class Container(collections.defaultdict):
DEFAULT_FACTORY = lambda: None
def __init__(self):
super().__init__(self, Container.DEFAULT_FACTORY)
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
self[name] = value
class Context(object):
def __init__(self, service, operation):
self.service = service
self.operation = operation
def execute(self):
self.service.continue_execution(self)
## Instruction:
Create class for request process recursion
## Code After:
import ujson
import collections
class Container(collections.defaultdict):
DEFAULT_FACTORY = lambda: None
def __init__(self):
super().__init__(self, Container.DEFAULT_FACTORY)
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
self[name] = value
class Context(object):
def __init__(self, service, operation, processor):
self.service = service
self.operation = operation
self.processor = processor
def process_request(self):
self.processor.continue_execution()
class Processor(object):
def __init__(self, service, operation, request_body):
self.service = service
self.operation = operation
self.context = Context(service, operation, self)
self.request = Container()
self.request_body = request_body
self.response = Container()
self.response_body = None
self.plugins = service.get_plugins(operation)
self.index = -1
self.state = "request" # request -> operation -> function
def execute(self):
self.context.process_request()
def continue_execution(self):
self.index += 1
plugins = self.plugins[self.state]
n = len(plugins)
if self.index > n:
# Terminal point so that service.invoke
# can safely call context.process_request()
return
elif self.index == n:
if self.state == "request":
self.index = -1
self.state = "operation"
self._deserialize_request()
self.continue_execution()
self._serialize_response()
elif self.state == "operation":
self.service.invoke(self.operation, self.request,
self.response, self.context)
# index < n
else:
if self.state == "request":
plugins[self.index](self.context)
elif self.state == "operation":
plugins[self.index](self.request, self.response, self.context)
def _deserialize_request(self):
self.request.update(ujson.loads(self.request_body))
def _serialize_response(self):
self.response_body = ujson.dumps(self.response)
|
# ... existing code ...
import ujson
import collections
# ... modified code ...
class Context(object):
def __init__(self, service, operation, processor):
self.service = service
self.operation = operation
self.processor = processor
def process_request(self):
self.processor.continue_execution()
class Processor(object):
def __init__(self, service, operation, request_body):
self.service = service
...
self.context = Context(service, operation, self)
self.request = Container()
self.request_body = request_body
self.response = Container()
self.response_body = None
self.plugins = service.get_plugins(operation)
self.index = -1
self.state = "request" # request -> operation -> function
def execute(self):
self.context.process_request()
def continue_execution(self):
self.index += 1
plugins = self.plugins[self.state]
n = len(plugins)
if self.index > n:
# Terminal point so that service.invoke
# can safely call context.process_request()
return
elif self.index == n:
if self.state == "request":
self.index = -1
self.state = "operation"
self._deserialize_request()
self.continue_execution()
self._serialize_response()
elif self.state == "operation":
self.service.invoke(self.operation, self.request,
self.response, self.context)
# index < n
else:
if self.state == "request":
plugins[self.index](self.context)
elif self.state == "operation":
plugins[self.index](self.request, self.response, self.context)
def _deserialize_request(self):
self.request.update(ujson.loads(self.request_body))
def _serialize_response(self):
self.response_body = ujson.dumps(self.response)
# ... rest of the code ...
|
25325ee55852eb65e58c13c46660701b1cdd803f
|
music/migrations/0020_auto_20151028_0925.py
|
music/migrations/0020_auto_20151028_0925.py
|
from __future__ import unicode_literals
from django.db import models, migrations
def set_total_duration_as_duration(apps, schema_editor):
Music = apps.get_model("music", "Music")
for music in Music.objects.all():
music.total_duration = music.duration
music.save()
class Migration(migrations.Migration):
dependencies = [
('music', '0019_auto_20151006_1416'),
]
operations = [
migrations.AddField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False, null=True),
preserve_default=False,
),
migrations.RunPython(set_total_duration_as_duration),
migrations.AlterField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name='music',
name='duration',
field=models.PositiveIntegerField(null=True),
preserve_default=True,
),
]
|
from __future__ import unicode_literals
from django.db import models, migrations
def set_total_duration_as_duration(apps, schema_editor):
Music = apps.get_model("music", "Music")
for music in Music.objects.all():
music.total_duration = music.duration
music.save()
class Migration(migrations.Migration):
dependencies = [
('music', '0019_auto_20151006_1416'),
]
operations = [
migrations.AddField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False, null=True),
preserve_default=False,
),
migrations.RunPython(set_total_duration_as_duration),
migrations.AlterField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name='music',
name='duration',
field=models.PositiveIntegerField(null=True),
preserve_default=True,
),
migrations.RemoveField(
model_name='music',
name='timer_end',
),
]
|
Delete timer_end in same migration as total_duration
|
Delete timer_end in same migration as total_duration
|
Python
|
mit
|
Amoki/Amoki-Music,Amoki/Amoki-Music,Amoki/Amoki-Music
|
from __future__ import unicode_literals
from django.db import models, migrations
def set_total_duration_as_duration(apps, schema_editor):
Music = apps.get_model("music", "Music")
for music in Music.objects.all():
music.total_duration = music.duration
music.save()
class Migration(migrations.Migration):
dependencies = [
('music', '0019_auto_20151006_1416'),
]
operations = [
migrations.AddField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False, null=True),
preserve_default=False,
),
migrations.RunPython(set_total_duration_as_duration),
migrations.AlterField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name='music',
name='duration',
field=models.PositiveIntegerField(null=True),
preserve_default=True,
),
+ migrations.RemoveField(
+ model_name='music',
+ name='timer_end',
+ ),
]
|
Delete timer_end in same migration as total_duration
|
## Code Before:
from __future__ import unicode_literals
from django.db import models, migrations
def set_total_duration_as_duration(apps, schema_editor):
Music = apps.get_model("music", "Music")
for music in Music.objects.all():
music.total_duration = music.duration
music.save()
class Migration(migrations.Migration):
dependencies = [
('music', '0019_auto_20151006_1416'),
]
operations = [
migrations.AddField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False, null=True),
preserve_default=False,
),
migrations.RunPython(set_total_duration_as_duration),
migrations.AlterField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name='music',
name='duration',
field=models.PositiveIntegerField(null=True),
preserve_default=True,
),
]
## Instruction:
Delete timer_end in same migration as total_duration
## Code After:
from __future__ import unicode_literals
from django.db import models, migrations
def set_total_duration_as_duration(apps, schema_editor):
Music = apps.get_model("music", "Music")
for music in Music.objects.all():
music.total_duration = music.duration
music.save()
class Migration(migrations.Migration):
dependencies = [
('music', '0019_auto_20151006_1416'),
]
operations = [
migrations.AddField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False, null=True),
preserve_default=False,
),
migrations.RunPython(set_total_duration_as_duration),
migrations.AlterField(
model_name='music',
name='total_duration',
field=models.PositiveIntegerField(editable=False),
),
migrations.AlterField(
model_name='music',
name='duration',
field=models.PositiveIntegerField(null=True),
preserve_default=True,
),
migrations.RemoveField(
model_name='music',
name='timer_end',
),
]
|
// ... existing code ...
),
migrations.RemoveField(
model_name='music',
name='timer_end',
),
]
// ... rest of the code ...
|
9ad98b4bbed0c67f25576187996e7e1d534f6a90
|
mammoth/__init__.py
|
mammoth/__init__.py
|
from .results import Result
from . import docx, conversion, style_reader
def convert_to_html(fileobj):
return docx.read(fileobj).bind(lambda document:
conversion.convert_document_element_to_html(document, styles=_create_default_styles())
)
def _create_default_styles():
lines = filter(None, map(lambda line: line.strip(), _default_styles.split("\n")))
return map(style_reader.read_style, lines)
_default_styles = """
p:unordered-list(1) => ul > li:fresh
"""
|
from .results import Result
from . import docx, conversion, style_reader
def convert_to_html(fileobj):
return docx.read(fileobj).bind(lambda document:
conversion.convert_document_element_to_html(document, styles=_create_default_styles())
)
def _create_default_styles():
lines = filter(None, map(lambda line: line.strip(), _default_styles.split("\n")))
return map(style_reader.read_style, lines)
_default_styles = """
p.Heading1 => h1:fresh
p.Heading2 => h2:fresh
p.Heading3 => h3:fresh
p.Heading4 => h4:fresh
p:unordered-list(1) => ul > li:fresh
p:unordered-list(2) => ul|ol > li > ul > li:fresh
p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh
p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh
p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh
p:ordered-list(1) => ol > li:fresh
p:ordered-list(2) => ul|ol > li > ol > li:fresh
p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh
p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh
p:ordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh
"""
|
Add full list of default styles
|
Add full list of default styles
|
Python
|
bsd-2-clause
|
mwilliamson/python-mammoth,JoshBarr/python-mammoth
|
from .results import Result
from . import docx, conversion, style_reader
def convert_to_html(fileobj):
return docx.read(fileobj).bind(lambda document:
conversion.convert_document_element_to_html(document, styles=_create_default_styles())
)
def _create_default_styles():
lines = filter(None, map(lambda line: line.strip(), _default_styles.split("\n")))
return map(style_reader.read_style, lines)
_default_styles = """
+ p.Heading1 => h1:fresh
+ p.Heading2 => h2:fresh
+ p.Heading3 => h3:fresh
+ p.Heading4 => h4:fresh
p:unordered-list(1) => ul > li:fresh
+ p:unordered-list(2) => ul|ol > li > ul > li:fresh
+ p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh
+ p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh
+ p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh
+ p:ordered-list(1) => ol > li:fresh
+ p:ordered-list(2) => ul|ol > li > ol > li:fresh
+ p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh
+ p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh
+ p:ordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh
"""
|
Add full list of default styles
|
## Code Before:
from .results import Result
from . import docx, conversion, style_reader
def convert_to_html(fileobj):
return docx.read(fileobj).bind(lambda document:
conversion.convert_document_element_to_html(document, styles=_create_default_styles())
)
def _create_default_styles():
lines = filter(None, map(lambda line: line.strip(), _default_styles.split("\n")))
return map(style_reader.read_style, lines)
_default_styles = """
p:unordered-list(1) => ul > li:fresh
"""
## Instruction:
Add full list of default styles
## Code After:
from .results import Result
from . import docx, conversion, style_reader
def convert_to_html(fileobj):
return docx.read(fileobj).bind(lambda document:
conversion.convert_document_element_to_html(document, styles=_create_default_styles())
)
def _create_default_styles():
lines = filter(None, map(lambda line: line.strip(), _default_styles.split("\n")))
return map(style_reader.read_style, lines)
_default_styles = """
p.Heading1 => h1:fresh
p.Heading2 => h2:fresh
p.Heading3 => h3:fresh
p.Heading4 => h4:fresh
p:unordered-list(1) => ul > li:fresh
p:unordered-list(2) => ul|ol > li > ul > li:fresh
p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh
p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh
p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh
p:ordered-list(1) => ol > li:fresh
p:ordered-list(2) => ul|ol > li > ol > li:fresh
p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh
p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh
p:ordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh
"""
|
# ... existing code ...
_default_styles = """
p.Heading1 => h1:fresh
p.Heading2 => h2:fresh
p.Heading3 => h3:fresh
p.Heading4 => h4:fresh
p:unordered-list(1) => ul > li:fresh
p:unordered-list(2) => ul|ol > li > ul > li:fresh
p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh
p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh
p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh
p:ordered-list(1) => ol > li:fresh
p:ordered-list(2) => ul|ol > li > ol > li:fresh
p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh
p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh
p:ordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh
"""
# ... rest of the code ...
|
ebf52caf6ee09ef1f15cb88815a1fb8008899c79
|
tests/test_reactjs.py
|
tests/test_reactjs.py
|
import dukpy
class TestReactJS(object):
def test_hello_world(self):
jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;')
jsi = dukpy.JSInterpreter()
result = jsi.evaljs([
'''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
''',
jsx,
'ReactDOM.renderToStaticMarkup(react_hello, null);'
])
assert result == '<h1>Hello, world!</h1>'
|
import dukpy
class TestReactJS(object):
def test_hello_world(self):
jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;')
jsi = dukpy.JSInterpreter()
result = jsi.evaljs([
'''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
''',
jsx,
'ReactDOM.renderToStaticMarkup(react_hello, null);'
])
assert result == '<h1>Hello, world!</h1>', res
def test_jsx_mixed(self):
code = '''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
ReactDOM.renderToStaticMarkup(<h1>Hello, world!</h1>, null);
'''
jsx = dukpy.jsx_compile(code)
res = dukpy.evaljs(jsx)
assert res == '<h1>Hello, world!</h1>', res
def test_react_binding(self):
code = '''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
var HelloWorld = React.createClass({
render: function() {
return (
<div className="helloworld">
Hello {this.props.data.name}
</div>
);
}
});
ReactDOM.renderToStaticMarkup(<HelloWorld data={dukpy.data}/>, null);
'''
jsx = dukpy.jsx_compile(code)
res = dukpy.evaljs(jsx, data={'id': 1, 'name': "Alessandro"})
assert res == '<div class="helloworld">Hello Alessandro</div>', res
|
Add tests for a React Component
|
Add tests for a React Component
|
Python
|
mit
|
amol-/dukpy,amol-/dukpy,amol-/dukpy
|
import dukpy
class TestReactJS(object):
def test_hello_world(self):
jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;')
jsi = dukpy.JSInterpreter()
result = jsi.evaljs([
'''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
''',
jsx,
'ReactDOM.renderToStaticMarkup(react_hello, null);'
])
- assert result == '<h1>Hello, world!</h1>'
+ assert result == '<h1>Hello, world!</h1>', res
+ def test_jsx_mixed(self):
+ code = '''
+ var React = require('react/react'),
+ ReactDOM = require('react/react-dom-server');
+ ReactDOM.renderToStaticMarkup(<h1>Hello, world!</h1>, null);
+ '''
+ jsx = dukpy.jsx_compile(code)
+ res = dukpy.evaljs(jsx)
+ assert res == '<h1>Hello, world!</h1>', res
+
+ def test_react_binding(self):
+ code = '''
+ var React = require('react/react'),
+ ReactDOM = require('react/react-dom-server');
+
+ var HelloWorld = React.createClass({
+ render: function() {
+ return (
+ <div className="helloworld">
+ Hello {this.props.data.name}
+ </div>
+ );
+ }
+ });
+
+ ReactDOM.renderToStaticMarkup(<HelloWorld data={dukpy.data}/>, null);
+ '''
+ jsx = dukpy.jsx_compile(code)
+ res = dukpy.evaljs(jsx, data={'id': 1, 'name': "Alessandro"})
+ assert res == '<div class="helloworld">Hello Alessandro</div>', res
|
Add tests for a React Component
|
## Code Before:
import dukpy
class TestReactJS(object):
def test_hello_world(self):
jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;')
jsi = dukpy.JSInterpreter()
result = jsi.evaljs([
'''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
''',
jsx,
'ReactDOM.renderToStaticMarkup(react_hello, null);'
])
assert result == '<h1>Hello, world!</h1>'
## Instruction:
Add tests for a React Component
## Code After:
import dukpy
class TestReactJS(object):
def test_hello_world(self):
jsx = dukpy.jsx_compile('var react_hello = <h1>Hello, world!</h1>;')
jsi = dukpy.JSInterpreter()
result = jsi.evaljs([
'''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
''',
jsx,
'ReactDOM.renderToStaticMarkup(react_hello, null);'
])
assert result == '<h1>Hello, world!</h1>', res
def test_jsx_mixed(self):
code = '''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
ReactDOM.renderToStaticMarkup(<h1>Hello, world!</h1>, null);
'''
jsx = dukpy.jsx_compile(code)
res = dukpy.evaljs(jsx)
assert res == '<h1>Hello, world!</h1>', res
def test_react_binding(self):
code = '''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
var HelloWorld = React.createClass({
render: function() {
return (
<div className="helloworld">
Hello {this.props.data.name}
</div>
);
}
});
ReactDOM.renderToStaticMarkup(<HelloWorld data={dukpy.data}/>, null);
'''
jsx = dukpy.jsx_compile(code)
res = dukpy.evaljs(jsx, data={'id': 1, 'name': "Alessandro"})
assert res == '<div class="helloworld">Hello Alessandro</div>', res
|
...
])
assert result == '<h1>Hello, world!</h1>', res
def test_jsx_mixed(self):
code = '''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
ReactDOM.renderToStaticMarkup(<h1>Hello, world!</h1>, null);
'''
jsx = dukpy.jsx_compile(code)
res = dukpy.evaljs(jsx)
assert res == '<h1>Hello, world!</h1>', res
def test_react_binding(self):
code = '''
var React = require('react/react'),
ReactDOM = require('react/react-dom-server');
var HelloWorld = React.createClass({
render: function() {
return (
<div className="helloworld">
Hello {this.props.data.name}
</div>
);
}
});
ReactDOM.renderToStaticMarkup(<HelloWorld data={dukpy.data}/>, null);
'''
jsx = dukpy.jsx_compile(code)
res = dukpy.evaljs(jsx, data={'id': 1, 'name': "Alessandro"})
assert res == '<div class="helloworld">Hello Alessandro</div>', res
...
|
14b9ef43fd244d4709d14478ec0714325ca37cdb
|
tests/builtins/test_sum.py
|
tests/builtins/test_sum.py
|
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_bytearray',
'test_frozenzet',
]
|
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_frozenzet',
]
|
Fix unexpected success on sum(bytearray())
|
Fix unexpected success on sum(bytearray())
|
Python
|
bsd-3-clause
|
cflee/voc,cflee/voc,freakboy3742/voc,freakboy3742/voc
|
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
- 'test_bytearray',
'test_frozenzet',
]
|
Fix unexpected success on sum(bytearray())
|
## Code Before:
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_bytearray',
'test_frozenzet',
]
## Instruction:
Fix unexpected success on sum(bytearray())
## Code After:
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class SumTests(TranspileTestCase):
def test_sum_list(self):
self.assertCodeExecution("""
print(sum([1, 2, 3, 4, 5, 6, 7]))
""")
def test_sum_tuple(self):
self.assertCodeExecution("""
print(sum((1, 2, 3, 4, 5, 6, 7)))
""")
def test_sum_iterator(self):
self.assertCodeExecution("""
i = iter([1, 2])
print(sum(i))
print(sum(i))
""")
def test_sum_mix_floats_and_ints(self):
self.assertCodeExecution("""
print(sum([1, 1.414, 2, 3.14159]))
""")
class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["sum"]
not_implemented = [
'test_frozenzet',
]
|
# ... existing code ...
not_implemented = [
'test_frozenzet',
# ... rest of the code ...
|
2833a895e8a7d0ba879598222c83bc5a4cd88853
|
desc/geometry/__init__.py
|
desc/geometry/__init__.py
|
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve
from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection
__all__ = [
"FourierRZCurve",
"FourierXYZCurve",
"FourierPlanarCurve",
"FourierRZToroidalSurface",
"ZernikeRZToroidalSection",
]
|
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve
from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection
from .core import Surface, Curve
__all__ = [
"FourierRZCurve",
"FourierXYZCurve",
"FourierPlanarCurve",
"FourierRZToroidalSurface",
"ZernikeRZToroidalSection",
]
|
Add geometry ABCs to init
|
Add geometry ABCs to init
|
Python
|
mit
|
PlasmaControl/DESC,PlasmaControl/DESC
|
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve
from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection
+ from .core import Surface, Curve
__all__ = [
"FourierRZCurve",
"FourierXYZCurve",
"FourierPlanarCurve",
"FourierRZToroidalSurface",
"ZernikeRZToroidalSection",
]
|
Add geometry ABCs to init
|
## Code Before:
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve
from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection
__all__ = [
"FourierRZCurve",
"FourierXYZCurve",
"FourierPlanarCurve",
"FourierRZToroidalSurface",
"ZernikeRZToroidalSection",
]
## Instruction:
Add geometry ABCs to init
## Code After:
from .curve import FourierRZCurve, FourierXYZCurve, FourierPlanarCurve
from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection
from .core import Surface, Curve
__all__ = [
"FourierRZCurve",
"FourierXYZCurve",
"FourierPlanarCurve",
"FourierRZToroidalSurface",
"ZernikeRZToroidalSection",
]
|
// ... existing code ...
from .surface import FourierRZToroidalSurface, ZernikeRZToroidalSection
from .core import Surface, Curve
// ... rest of the code ...
|
a05372ad910900ec2ef89bb10d4a0759c9bcd437
|
app.py
|
app.py
|
import os
from flask import Flask, request, redirect, session
import twilio.twiml
from twilio.rest import TwilioRestClient
from charity import Charity
SECRET_KEY = os.environ['DONATION_SECRET_KEY']
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.values.get('From', None)
client = TwilioRestClient()
charity = Charity()
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
message = from_number + ", thanks for the message!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
import os
from flask import Flask, request
import twilio.twiml
from twilio.rest import TwilioRestClient
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.args.get('From')
text_content = request.args.get('Body').lower()
client = TwilioRestClient(os.environ['TWILIO_ACCOUNT_SID'],
os.environ['TWILIO_AUTH_TOKEN'])
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
message = from_number + ", thanks for the donation!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
Test sending a fresh message
|
Test sending a fresh message
|
Python
|
mit
|
DanielleSucher/Text-Donation
|
import os
- from flask import Flask, request, redirect, session
+ from flask import Flask, request
import twilio.twiml
from twilio.rest import TwilioRestClient
- from charity import Charity
- SECRET_KEY = os.environ['DONATION_SECRET_KEY']
+
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
- from_number = request.values.get('From', None)
+ from_number = request.args.get('From')
- client = TwilioRestClient()
- charity = Charity()
+ text_content = request.args.get('Body').lower()
+
+ client = TwilioRestClient(os.environ['TWILIO_ACCOUNT_SID'],
+ os.environ['TWILIO_AUTH_TOKEN'])
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
- message = from_number + ", thanks for the message!"
+ message = from_number + ", thanks for the donation!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
Test sending a fresh message
|
## Code Before:
import os
from flask import Flask, request, redirect, session
import twilio.twiml
from twilio.rest import TwilioRestClient
from charity import Charity
SECRET_KEY = os.environ['DONATION_SECRET_KEY']
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.values.get('From', None)
client = TwilioRestClient()
charity = Charity()
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
message = from_number + ", thanks for the message!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
## Instruction:
Test sending a fresh message
## Code After:
import os
from flask import Flask, request
import twilio.twiml
from twilio.rest import TwilioRestClient
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
from_number = request.args.get('From')
text_content = request.args.get('Body').lower()
client = TwilioRestClient(os.environ['TWILIO_ACCOUNT_SID'],
os.environ['TWILIO_AUTH_TOKEN'])
client.sms.messages.create(to="+17187535039",
from_=from_number,
body="fresh message!")
message = from_number + ", thanks for the donation!"
resp = twilio.twiml.Response()
resp.sms(message)
return str(resp)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
# ... existing code ...
import os
from flask import Flask, request
import twilio.twiml
# ... modified code ...
from twilio.rest import TwilioRestClient
app = Flask(__name__)
...
def hello():
from_number = request.args.get('From')
text_content = request.args.get('Body').lower()
client = TwilioRestClient(os.environ['TWILIO_ACCOUNT_SID'],
os.environ['TWILIO_AUTH_TOKEN'])
client.sms.messages.create(to="+17187535039",
...
message = from_number + ", thanks for the donation!"
resp = twilio.twiml.Response()
# ... rest of the code ...
|
9a988056944700d6188f6e7164e68dcd35c342d8
|
databench/analysis.py
|
databench/analysis.py
|
"""Analysis module for Databench."""
from flask import Blueprint, render_template
import databench.signals
LIST_ALL = []
class Analysis(object):
"""Databench's analysis class.
An optional :class:`databench.Signals` instance and :class:`flask.Blueprint`
can be dependency-injected, however that should not be necessary for
standard use cases.
Args:
name (str): Name of this analysis. If ``signals`` is not specified, this
also becomes the namespace for the Socket.IO connection and has
to match the frontend's :js:class:`Databench` ``name``.
import_name (str): Usually the file name ``__name__`` where this
analysis is instantiated.
signals (optional): Inject an instance of :class:`databench.Signals`.
blueprint (optional): Inject an instance of a :class:`flask.Blueprint`.
"""
def __init__(
self,
name,
import_name,
signals=None,
blueprint=None
):
LIST_ALL.append(self)
self.name = name
self.import_name = import_name
if not signals:
self.signals = databench.signals.Signals(name)
else:
self.signals = signals
if not blueprint:
self.blueprint = Blueprint(
name,
import_name,
template_folder='templates',
static_folder='static',
)
else:
self.blueprint = blueprint
self.show_in_index = True
@self.blueprint.route('/')
def render_index():
"""Renders the main analysis frontend template."""
return render_template(self.name+'.html')
|
"""Analysis module for Databench."""
from flask import Blueprint, render_template
import databench.signals
LIST_ALL = []
class Analysis(object):
"""Databench's analysis class.
An optional :class:`databench.Signals` instance and :class:`flask.Blueprint`
can be dependency-injected, however that should not be necessary for
standard use cases.
Args:
name (str): Name of this analysis. If ``signals`` is not specified, this
also becomes the namespace for the Socket.IO connection and has
to match the frontend's :js:class:`Databench` ``name``.
import_name (str): Usually the file name ``__name__`` where this
analysis is instantiated.
signals (optional): Inject an instance of :class:`databench.Signals`.
blueprint (optional): Inject an instance of a :class:`flask.Blueprint`.
"""
def __init__(
self,
name,
import_name,
signals=None,
blueprint=None
):
LIST_ALL.append(self)
self.show_in_index = True
self.name = name
self.import_name = import_name
if not signals:
self.signals = databench.signals.Signals(name)
else:
self.signals = signals
if not blueprint:
self.blueprint = Blueprint(
name,
import_name,
template_folder='templates',
static_folder='static',
)
else:
self.blueprint = blueprint
self.blueprint.add_url_rule('/', 'render_index', self.render_index)
def render_index(self):
"""Renders the main analysis frontend template."""
return render_template(self.name+'.html')
|
Move the render_index() function out of the constructor and use add_url_rule() instead of the route() decorator to connect it to Flask.
|
Move the render_index() function out of the constructor and use add_url_rule() instead of the route() decorator to connect it to Flask.
|
Python
|
mit
|
svenkreiss/databench,svenkreiss/databench,svenkreiss/databench,svenkreiss/databench
|
"""Analysis module for Databench."""
from flask import Blueprint, render_template
import databench.signals
LIST_ALL = []
class Analysis(object):
"""Databench's analysis class.
An optional :class:`databench.Signals` instance and :class:`flask.Blueprint`
can be dependency-injected, however that should not be necessary for
standard use cases.
Args:
name (str): Name of this analysis. If ``signals`` is not specified, this
also becomes the namespace for the Socket.IO connection and has
to match the frontend's :js:class:`Databench` ``name``.
import_name (str): Usually the file name ``__name__`` where this
analysis is instantiated.
signals (optional): Inject an instance of :class:`databench.Signals`.
blueprint (optional): Inject an instance of a :class:`flask.Blueprint`.
"""
def __init__(
self,
name,
import_name,
signals=None,
blueprint=None
):
LIST_ALL.append(self)
+ self.show_in_index = True
+
self.name = name
self.import_name = import_name
if not signals:
self.signals = databench.signals.Signals(name)
else:
self.signals = signals
if not blueprint:
self.blueprint = Blueprint(
name,
import_name,
template_folder='templates',
static_folder='static',
)
else:
self.blueprint = blueprint
- self.show_in_index = True
+ self.blueprint.add_url_rule('/', 'render_index', self.render_index)
- @self.blueprint.route('/')
- def render_index():
+ def render_index(self):
- """Renders the main analysis frontend template."""
+ """Renders the main analysis frontend template."""
- return render_template(self.name+'.html')
+ return render_template(self.name+'.html')
|
Move the render_index() function out of the constructor and use add_url_rule() instead of the route() decorator to connect it to Flask.
|
## Code Before:
"""Analysis module for Databench."""
from flask import Blueprint, render_template
import databench.signals
LIST_ALL = []
class Analysis(object):
"""Databench's analysis class.
An optional :class:`databench.Signals` instance and :class:`flask.Blueprint`
can be dependency-injected, however that should not be necessary for
standard use cases.
Args:
name (str): Name of this analysis. If ``signals`` is not specified, this
also becomes the namespace for the Socket.IO connection and has
to match the frontend's :js:class:`Databench` ``name``.
import_name (str): Usually the file name ``__name__`` where this
analysis is instantiated.
signals (optional): Inject an instance of :class:`databench.Signals`.
blueprint (optional): Inject an instance of a :class:`flask.Blueprint`.
"""
def __init__(
self,
name,
import_name,
signals=None,
blueprint=None
):
LIST_ALL.append(self)
self.name = name
self.import_name = import_name
if not signals:
self.signals = databench.signals.Signals(name)
else:
self.signals = signals
if not blueprint:
self.blueprint = Blueprint(
name,
import_name,
template_folder='templates',
static_folder='static',
)
else:
self.blueprint = blueprint
self.show_in_index = True
@self.blueprint.route('/')
def render_index():
"""Renders the main analysis frontend template."""
return render_template(self.name+'.html')
## Instruction:
Move the render_index() function out of the constructor and use add_url_rule() instead of the route() decorator to connect it to Flask.
## Code After:
"""Analysis module for Databench."""
from flask import Blueprint, render_template
import databench.signals
LIST_ALL = []
class Analysis(object):
"""Databench's analysis class.
An optional :class:`databench.Signals` instance and :class:`flask.Blueprint`
can be dependency-injected, however that should not be necessary for
standard use cases.
Args:
name (str): Name of this analysis. If ``signals`` is not specified, this
also becomes the namespace for the Socket.IO connection and has
to match the frontend's :js:class:`Databench` ``name``.
import_name (str): Usually the file name ``__name__`` where this
analysis is instantiated.
signals (optional): Inject an instance of :class:`databench.Signals`.
blueprint (optional): Inject an instance of a :class:`flask.Blueprint`.
"""
def __init__(
self,
name,
import_name,
signals=None,
blueprint=None
):
LIST_ALL.append(self)
self.show_in_index = True
self.name = name
self.import_name = import_name
if not signals:
self.signals = databench.signals.Signals(name)
else:
self.signals = signals
if not blueprint:
self.blueprint = Blueprint(
name,
import_name,
template_folder='templates',
static_folder='static',
)
else:
self.blueprint = blueprint
self.blueprint.add_url_rule('/', 'render_index', self.render_index)
def render_index(self):
"""Renders the main analysis frontend template."""
return render_template(self.name+'.html')
|
# ... existing code ...
LIST_ALL.append(self)
self.show_in_index = True
self.name = name
# ... modified code ...
self.blueprint.add_url_rule('/', 'render_index', self.render_index)
def render_index(self):
"""Renders the main analysis frontend template."""
return render_template(self.name+'.html')
# ... rest of the code ...
|
04c8a36c5713e4279f8bf52fa45cdb03de721dbb
|
example/deploy.py
|
example/deploy.py
|
from pyinfra import inventory, state
from pyinfra_docker import deploy_docker
from pyinfra_etcd import deploy_etcd
from pyinfra_kubernetes import deploy_kubernetes_master, deploy_kubernetes_node
SUDO = True
FAIL_PERCENT = 0
def get_etcd_nodes():
return [
'http://{0}:2379'.format(
etcd_node.fact.network_devices[etcd_node.data.etcd_interface]
['ipv4']['address'],
)
for etcd_node in inventory.get_group('etcd_nodes')
]
# Install/configure etcd cluster
with state.limit('etcd_nodes'):
deploy_etcd()
# Install/configure the masters (apiserver, controller, scheduler)
with state.limit('kubernetes_masters'):
deploy_kubernetes_master(etcd_nodes=get_etcd_nodes())
# Install/configure the nodes
with state.limit('kubernetes_nodes'):
# Install Docker
deploy_docker()
# Install Kubernetes node components (kubelet, kube-proxy)
first_master = inventory.get_group('kubernetes_masters')[0]
deploy_kubernetes_node(
master_address='http://{0}'.format((
first_master
.fact.network_devices[first_master.data.network_interface]
['ipv4']['address']
)),
)
# deploy_docker(config={
# # Make Docker use the Vagrant provided interface which has it's own /24
# 'bip': '{{ host.fact.network_devices[host.data.network_interface].ipv4.address }}',
# })
|
from pyinfra import inventory, state
from pyinfra_docker import deploy_docker
from pyinfra_etcd import deploy_etcd
from pyinfra_kubernetes import deploy_kubernetes_master, deploy_kubernetes_node
SUDO = True
FAIL_PERCENT = 0
def get_etcd_nodes():
return [
'http://{0}:2379'.format(
etcd_node.fact.network_devices[etcd_node.data.etcd_interface]
['ipv4']['address'],
)
for etcd_node in inventory.get_group('etcd_nodes')
]
# Install/configure etcd cluster
with state.limit('etcd_nodes'):
deploy_etcd()
# Install/configure the masters (apiserver, controller, scheduler)
with state.limit('kubernetes_masters'):
deploy_kubernetes_master(etcd_nodes=get_etcd_nodes())
# Install/configure the nodes
with state.limit('kubernetes_nodes'):
# Install Docker
deploy_docker(config={
# Make Docker use the Vagrant provided interface which has it's own /24
'bip': '{{ host.fact.network_devices[host.data.network_interface].ipv4.address }}',
})
# Install Kubernetes node components (kubelet, kube-proxy)
first_master = inventory.get_group('kubernetes_masters')[0]
deploy_kubernetes_node(
master_address='http://{0}'.format((
first_master
.fact.network_devices[first_master.data.network_interface]
['ipv4']['address']
)),
)
|
Use Docker config pointing at the correct interface/subnect for networking.
|
Use Docker config pointing at the correct interface/subnect for networking.
|
Python
|
mit
|
EDITD/pyinfra-kubernetes,EDITD/pyinfra-kubernetes
|
from pyinfra import inventory, state
from pyinfra_docker import deploy_docker
from pyinfra_etcd import deploy_etcd
from pyinfra_kubernetes import deploy_kubernetes_master, deploy_kubernetes_node
SUDO = True
FAIL_PERCENT = 0
def get_etcd_nodes():
return [
'http://{0}:2379'.format(
etcd_node.fact.network_devices[etcd_node.data.etcd_interface]
['ipv4']['address'],
)
for etcd_node in inventory.get_group('etcd_nodes')
]
# Install/configure etcd cluster
with state.limit('etcd_nodes'):
deploy_etcd()
# Install/configure the masters (apiserver, controller, scheduler)
with state.limit('kubernetes_masters'):
deploy_kubernetes_master(etcd_nodes=get_etcd_nodes())
# Install/configure the nodes
with state.limit('kubernetes_nodes'):
# Install Docker
- deploy_docker()
+ deploy_docker(config={
+ # Make Docker use the Vagrant provided interface which has it's own /24
+ 'bip': '{{ host.fact.network_devices[host.data.network_interface].ipv4.address }}',
+ })
# Install Kubernetes node components (kubelet, kube-proxy)
first_master = inventory.get_group('kubernetes_masters')[0]
deploy_kubernetes_node(
master_address='http://{0}'.format((
first_master
.fact.network_devices[first_master.data.network_interface]
['ipv4']['address']
)),
)
- # deploy_docker(config={
- # # Make Docker use the Vagrant provided interface which has it's own /24
- # 'bip': '{{ host.fact.network_devices[host.data.network_interface].ipv4.address }}',
- # })
-
|
Use Docker config pointing at the correct interface/subnect for networking.
|
## Code Before:
from pyinfra import inventory, state
from pyinfra_docker import deploy_docker
from pyinfra_etcd import deploy_etcd
from pyinfra_kubernetes import deploy_kubernetes_master, deploy_kubernetes_node
SUDO = True
FAIL_PERCENT = 0
def get_etcd_nodes():
return [
'http://{0}:2379'.format(
etcd_node.fact.network_devices[etcd_node.data.etcd_interface]
['ipv4']['address'],
)
for etcd_node in inventory.get_group('etcd_nodes')
]
# Install/configure etcd cluster
with state.limit('etcd_nodes'):
deploy_etcd()
# Install/configure the masters (apiserver, controller, scheduler)
with state.limit('kubernetes_masters'):
deploy_kubernetes_master(etcd_nodes=get_etcd_nodes())
# Install/configure the nodes
with state.limit('kubernetes_nodes'):
# Install Docker
deploy_docker()
# Install Kubernetes node components (kubelet, kube-proxy)
first_master = inventory.get_group('kubernetes_masters')[0]
deploy_kubernetes_node(
master_address='http://{0}'.format((
first_master
.fact.network_devices[first_master.data.network_interface]
['ipv4']['address']
)),
)
# deploy_docker(config={
# # Make Docker use the Vagrant provided interface which has it's own /24
# 'bip': '{{ host.fact.network_devices[host.data.network_interface].ipv4.address }}',
# })
## Instruction:
Use Docker config pointing at the correct interface/subnect for networking.
## Code After:
from pyinfra import inventory, state
from pyinfra_docker import deploy_docker
from pyinfra_etcd import deploy_etcd
from pyinfra_kubernetes import deploy_kubernetes_master, deploy_kubernetes_node
SUDO = True
FAIL_PERCENT = 0
def get_etcd_nodes():
return [
'http://{0}:2379'.format(
etcd_node.fact.network_devices[etcd_node.data.etcd_interface]
['ipv4']['address'],
)
for etcd_node in inventory.get_group('etcd_nodes')
]
# Install/configure etcd cluster
with state.limit('etcd_nodes'):
deploy_etcd()
# Install/configure the masters (apiserver, controller, scheduler)
with state.limit('kubernetes_masters'):
deploy_kubernetes_master(etcd_nodes=get_etcd_nodes())
# Install/configure the nodes
with state.limit('kubernetes_nodes'):
# Install Docker
deploy_docker(config={
# Make Docker use the Vagrant provided interface which has it's own /24
'bip': '{{ host.fact.network_devices[host.data.network_interface].ipv4.address }}',
})
# Install Kubernetes node components (kubelet, kube-proxy)
first_master = inventory.get_group('kubernetes_masters')[0]
deploy_kubernetes_node(
master_address='http://{0}'.format((
first_master
.fact.network_devices[first_master.data.network_interface]
['ipv4']['address']
)),
)
|
# ... existing code ...
# Install Docker
deploy_docker(config={
# Make Docker use the Vagrant provided interface which has it's own /24
'bip': '{{ host.fact.network_devices[host.data.network_interface].ipv4.address }}',
})
# ... modified code ...
)
# ... rest of the code ...
|
cde9dd479b2974f26f2e50b3611bfd0756f86c2b
|
game_of_thrones/__init__.py
|
game_of_thrones/__init__.py
|
class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
return [pair for pair in zip(text[0::1], text[1::1])]
|
class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
"""
Takes an string and returns a list of tuples. For example:
>>> pair_symbols('Arya')
[('A', 'r'), ('r', 'y'), ('y', 'a')]
"""
return [pair for pair in zip(text[0::1], text[1::1])]
|
Add docstring to the `pair_symbols` method
|
Add docstring to the `pair_symbols` method
|
Python
|
mit
|
Matt-Deacalion/Name-of-Thrones
|
class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
+ """
+ Takes an string and returns a list of tuples. For example:
+
+ >>> pair_symbols('Arya')
+ [('A', 'r'), ('r', 'y'), ('y', 'a')]
+ """
return [pair for pair in zip(text[0::1], text[1::1])]
|
Add docstring to the `pair_symbols` method
|
## Code Before:
class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
return [pair for pair in zip(text[0::1], text[1::1])]
## Instruction:
Add docstring to the `pair_symbols` method
## Code After:
class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
"""
Takes an string and returns a list of tuples. For example:
>>> pair_symbols('Arya')
[('A', 'r'), ('r', 'y'), ('y', 'a')]
"""
return [pair for pair in zip(text[0::1], text[1::1])]
|
# ... existing code ...
def pair_symbols(self, text):
"""
Takes an string and returns a list of tuples. For example:
>>> pair_symbols('Arya')
[('A', 'r'), ('r', 'y'), ('y', 'a')]
"""
return [pair for pair in zip(text[0::1], text[1::1])]
# ... rest of the code ...
|
ad5cb91fa011e067a96835e59e05581af3ea3a53
|
acctwatch/configcheck.py
|
acctwatch/configcheck.py
|
import httplib2
import os
import sys
import time
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
from config import Configuration
try:
import geoip2.database as geoipdb
except ImportError:
geoipdb = None
def main():
config = Configuration()
if config.WITH_GEOIP and not geoipdb:
print ("GeoIP is enabled, but unable to import module, please check installation. Disabling.")
config.WITH_GEOIP = False
credentials = config.get_credentials()
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
# Construct the service object for the interacting with the Admin Reports API.
service = discovery.build('admin', 'reports_v1', http=http)
activities = service.activities()
try:
login_list = activities.list(userKey='all', applicationName='login', maxResults=1000).execute()
print("Success!")
except client.AccessTokenRefreshError:
print("Failure. Access token is invalid.")
if __name__ == '__main__':
main()
|
import httplib2
import os
import sys
import time
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
from config import Configuration
try:
import geoip2.database as geoipdb
except ImportError:
print ("GeoIP is missing, please install dependency")
def main():
config = Configuration()
credentials = config.get_credentials()
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
# Construct the service object for the interacting with the Admin Reports API.
service = discovery.build('admin', 'reports_v1', http=http)
activities = service.activities()
try:
login_list = activities.list(userKey='all', applicationName='login', maxResults=1000).execute()
print("Success!")
except client.AccessTokenRefreshError:
print("Failure. Access token is invalid. Please re-run the tool to get a new access token.")
if __name__ == '__main__':
main()
|
Clean up configuration check utility
|
Clean up configuration check utility
|
Python
|
isc
|
GuardedRisk/Google-Apps-Auditing
|
import httplib2
import os
import sys
import time
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
from config import Configuration
try:
import geoip2.database as geoipdb
except ImportError:
- geoipdb = None
+ print ("GeoIP is missing, please install dependency")
def main():
config = Configuration()
- if config.WITH_GEOIP and not geoipdb:
- print ("GeoIP is enabled, but unable to import module, please check installation. Disabling.")
- config.WITH_GEOIP = False
-
credentials = config.get_credentials()
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
# Construct the service object for the interacting with the Admin Reports API.
service = discovery.build('admin', 'reports_v1', http=http)
activities = service.activities()
try:
login_list = activities.list(userKey='all', applicationName='login', maxResults=1000).execute()
print("Success!")
except client.AccessTokenRefreshError:
- print("Failure. Access token is invalid.")
+ print("Failure. Access token is invalid. Please re-run the tool to get a new access token.")
if __name__ == '__main__':
main()
|
Clean up configuration check utility
|
## Code Before:
import httplib2
import os
import sys
import time
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
from config import Configuration
try:
import geoip2.database as geoipdb
except ImportError:
geoipdb = None
def main():
config = Configuration()
if config.WITH_GEOIP and not geoipdb:
print ("GeoIP is enabled, but unable to import module, please check installation. Disabling.")
config.WITH_GEOIP = False
credentials = config.get_credentials()
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
# Construct the service object for the interacting with the Admin Reports API.
service = discovery.build('admin', 'reports_v1', http=http)
activities = service.activities()
try:
login_list = activities.list(userKey='all', applicationName='login', maxResults=1000).execute()
print("Success!")
except client.AccessTokenRefreshError:
print("Failure. Access token is invalid.")
if __name__ == '__main__':
main()
## Instruction:
Clean up configuration check utility
## Code After:
import httplib2
import os
import sys
import time
from apiclient import discovery
from oauth2client import file
from oauth2client import client
from oauth2client import tools
from config import Configuration
try:
import geoip2.database as geoipdb
except ImportError:
print ("GeoIP is missing, please install dependency")
def main():
config = Configuration()
credentials = config.get_credentials()
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
# Construct the service object for the interacting with the Admin Reports API.
service = discovery.build('admin', 'reports_v1', http=http)
activities = service.activities()
try:
login_list = activities.list(userKey='all', applicationName='login', maxResults=1000).execute()
print("Success!")
except client.AccessTokenRefreshError:
print("Failure. Access token is invalid. Please re-run the tool to get a new access token.")
if __name__ == '__main__':
main()
|
# ... existing code ...
except ImportError:
print ("GeoIP is missing, please install dependency")
# ... modified code ...
config = Configuration()
credentials = config.get_credentials()
...
except client.AccessTokenRefreshError:
print("Failure. Access token is invalid. Please re-run the tool to get a new access token.")
# ... rest of the code ...
|
6f75300037254f51f1512a271bf7850a4bc0a8f8
|
djangospam/cookie/urls.py
|
djangospam/cookie/urls.py
|
from django.conf.urls.defaults import patterns
urlpatterns = patterns('',
(r'^post$', 'djangospam.cookie.views.spammer_view'),)
|
try:
from django.conf.urls import patterns
except ImportError:
from django.conf.urls.defaults import patterns
urlpatterns = patterns('',
(r'^post$', 'djangospam.cookie.views.spammer_view'),)
|
Add support for Django 1.4 and up
|
Add support for Django 1.4 and up
* Module django.conf.urls.defaults has been moved to django.conf.urls in
version 1.4.
Commit references issue #3.
|
Python
|
bsd-2-clause
|
leandroarndt/djangospam,leandroarndt/djangospam
|
+ try:
+ from django.conf.urls import patterns
+ except ImportError:
- from django.conf.urls.defaults import patterns
+ from django.conf.urls.defaults import patterns
urlpatterns = patterns('',
(r'^post$', 'djangospam.cookie.views.spammer_view'),)
|
Add support for Django 1.4 and up
|
## Code Before:
from django.conf.urls.defaults import patterns
urlpatterns = patterns('',
(r'^post$', 'djangospam.cookie.views.spammer_view'),)
## Instruction:
Add support for Django 1.4 and up
## Code After:
try:
from django.conf.urls import patterns
except ImportError:
from django.conf.urls.defaults import patterns
urlpatterns = patterns('',
(r'^post$', 'djangospam.cookie.views.spammer_view'),)
|
...
try:
from django.conf.urls import patterns
except ImportError:
from django.conf.urls.defaults import patterns
...
|
5d4572f08c6e65a062fd2f00590f6eeb5e12ce38
|
src/zeit/content/article/edit/browser/tests/test_template.py
|
src/zeit/content/article/edit/browser/tests/test_template.py
|
import zeit.content.article.edit.browser.testing
class ArticleTemplateTest(
zeit.content.article.edit.browser.testing.EditorTestCase):
def setUp(self):
super(ArticleTemplateTest, self).setUp()
self.add_article()
self.selenium.waitForElementPresent('id=options-template.template')
def test_changing_template_should_update_header_layout_list(self):
s = self.selenium
s.click('css=#edit-form-misc .edit-bar .fold-link')
s.assertSelectedLabel(
'id=options-template.template', '(nothing selected)')
s.assertNotVisible('css=.fieldname-header_layout')
s.select('id=options-template.template', 'Kolumne')
s.pause(100)
kolumne_layouts = [
u'(nothing selected)',
u'Heiter bis glücklich',
u'Ich habe einen Traum',
u'Martenstein',
u'Standard',
u'Von A nach B',
]
s.assertVisible('css=.fieldname-header_layout')
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
s.type('id=options-template.header_layout', '\t')
s.pause(500)
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
|
import zeit.content.article.edit.browser.testing
class ArticleTemplateTest(
zeit.content.article.edit.browser.testing.EditorTestCase):
def setUp(self):
super(ArticleTemplateTest, self).setUp()
self.add_article()
self.selenium.waitForElementPresent('id=options-template.template')
def test_changing_template_should_update_header_layout_list(self):
s = self.selenium
s.click('css=#edit-form-misc .edit-bar .fold-link')
s.assertSelectedLabel(
'id=options-template.template', 'Artikel')
s.select('id=options-template.template', 'Kolumne')
s.pause(100)
kolumne_layouts = [
u'(nothing selected)',
u'Heiter bis glücklich',
u'Ich habe einen Traum',
u'Martenstein',
u'Standard',
u'Von A nach B',
]
s.assertVisible('css=.fieldname-header_layout')
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
s.type('id=options-template.header_layout', '\t')
s.pause(500)
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
|
Update test, the article now starts with a default value for `template` (belongs to commit:95a001d)
|
ZON-3178: Update test, the article now starts with a default value for `template` (belongs to commit:95a001d)
|
Python
|
bsd-3-clause
|
ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article,ZeitOnline/zeit.content.article
|
import zeit.content.article.edit.browser.testing
class ArticleTemplateTest(
zeit.content.article.edit.browser.testing.EditorTestCase):
def setUp(self):
super(ArticleTemplateTest, self).setUp()
self.add_article()
self.selenium.waitForElementPresent('id=options-template.template')
def test_changing_template_should_update_header_layout_list(self):
s = self.selenium
s.click('css=#edit-form-misc .edit-bar .fold-link')
s.assertSelectedLabel(
- 'id=options-template.template', '(nothing selected)')
+ 'id=options-template.template', 'Artikel')
- s.assertNotVisible('css=.fieldname-header_layout')
s.select('id=options-template.template', 'Kolumne')
s.pause(100)
kolumne_layouts = [
u'(nothing selected)',
u'Heiter bis glücklich',
u'Ich habe einen Traum',
u'Martenstein',
u'Standard',
u'Von A nach B',
]
s.assertVisible('css=.fieldname-header_layout')
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
s.type('id=options-template.header_layout', '\t')
s.pause(500)
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
|
Update test, the article now starts with a default value for `template` (belongs to commit:95a001d)
|
## Code Before:
import zeit.content.article.edit.browser.testing
class ArticleTemplateTest(
zeit.content.article.edit.browser.testing.EditorTestCase):
def setUp(self):
super(ArticleTemplateTest, self).setUp()
self.add_article()
self.selenium.waitForElementPresent('id=options-template.template')
def test_changing_template_should_update_header_layout_list(self):
s = self.selenium
s.click('css=#edit-form-misc .edit-bar .fold-link')
s.assertSelectedLabel(
'id=options-template.template', '(nothing selected)')
s.assertNotVisible('css=.fieldname-header_layout')
s.select('id=options-template.template', 'Kolumne')
s.pause(100)
kolumne_layouts = [
u'(nothing selected)',
u'Heiter bis glücklich',
u'Ich habe einen Traum',
u'Martenstein',
u'Standard',
u'Von A nach B',
]
s.assertVisible('css=.fieldname-header_layout')
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
s.type('id=options-template.header_layout', '\t')
s.pause(500)
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
## Instruction:
Update test, the article now starts with a default value for `template` (belongs to commit:95a001d)
## Code After:
import zeit.content.article.edit.browser.testing
class ArticleTemplateTest(
zeit.content.article.edit.browser.testing.EditorTestCase):
def setUp(self):
super(ArticleTemplateTest, self).setUp()
self.add_article()
self.selenium.waitForElementPresent('id=options-template.template')
def test_changing_template_should_update_header_layout_list(self):
s = self.selenium
s.click('css=#edit-form-misc .edit-bar .fold-link')
s.assertSelectedLabel(
'id=options-template.template', 'Artikel')
s.select('id=options-template.template', 'Kolumne')
s.pause(100)
kolumne_layouts = [
u'(nothing selected)',
u'Heiter bis glücklich',
u'Ich habe einen Traum',
u'Martenstein',
u'Standard',
u'Von A nach B',
]
s.assertVisible('css=.fieldname-header_layout')
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
s.type('id=options-template.header_layout', '\t')
s.pause(500)
self.assertEqual(
kolumne_layouts,
s.getSelectOptions('id=options-template.header_layout'))
|
// ... existing code ...
s.assertSelectedLabel(
'id=options-template.template', 'Artikel')
s.select('id=options-template.template', 'Kolumne')
// ... rest of the code ...
|
d01adfce91927c57258f1e13ed34e4e600e40048
|
pipenv/pew/__main__.py
|
pipenv/pew/__main__.py
|
from pipenv.patched import pew
if __name__ == '__main__':
pew.pew.pew()
|
from pipenv.patched import pew
import os
import sys
pipenv_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pipenv_vendor = os.sep.join([pipenv_root, 'vendor'])
pipenv_patched = os.sep.join([pipenv_root, 'patched'])
if __name__ == '__main__':
sys.path.insert(0, pipenv_vendor)
sys.path.insert(0, pipenv_patched)
pew.pew.pew()
|
Add vendor and patch directories to pew path
|
Add vendor and patch directories to pew path
- Fixes #1661
|
Python
|
mit
|
kennethreitz/pipenv
|
from pipenv.patched import pew
+ import os
+ import sys
+
+ pipenv_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ pipenv_vendor = os.sep.join([pipenv_root, 'vendor'])
+ pipenv_patched = os.sep.join([pipenv_root, 'patched'])
+
if __name__ == '__main__':
+ sys.path.insert(0, pipenv_vendor)
+ sys.path.insert(0, pipenv_patched)
pew.pew.pew()
|
Add vendor and patch directories to pew path
|
## Code Before:
from pipenv.patched import pew
if __name__ == '__main__':
pew.pew.pew()
## Instruction:
Add vendor and patch directories to pew path
## Code After:
from pipenv.patched import pew
import os
import sys
pipenv_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pipenv_vendor = os.sep.join([pipenv_root, 'vendor'])
pipenv_patched = os.sep.join([pipenv_root, 'patched'])
if __name__ == '__main__':
sys.path.insert(0, pipenv_vendor)
sys.path.insert(0, pipenv_patched)
pew.pew.pew()
|
# ... existing code ...
from pipenv.patched import pew
import os
import sys
pipenv_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pipenv_vendor = os.sep.join([pipenv_root, 'vendor'])
pipenv_patched = os.sep.join([pipenv_root, 'patched'])
# ... modified code ...
if __name__ == '__main__':
sys.path.insert(0, pipenv_vendor)
sys.path.insert(0, pipenv_patched)
pew.pew.pew()
# ... rest of the code ...
|
c5fc667a6d50677936d8ae457734562d207a034b
|
bluesky/tests/test_vertical_integration.py
|
bluesky/tests/test_vertical_integration.py
|
from metadatastore.utils.testing import mds_setup, mds_teardown
from dataportal import DataBroker as db
from bluesky.examples import *
from bluesky.standard_config import RE
def setup():
mds_setup()
def teardown():
mds_teardown()
def test_scan_and_get_data():
uid = RE(stepscan(det, motor), group='foo', beamline_id='testing',
config={})
hdr = db[uid]
ev = db.fetch_events(hdr)
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
|
from metadatastore.utils.testing import mds_setup, mds_teardown
from dataportal import DataBroker as db
from bluesky.examples import stepscan, det, motor
from bluesky.standard_config import gs
def setup():
mds_setup()
def teardown():
mds_teardown()
def test_scan_and_get_data():
uid = gs.RE(stepscan(det, motor), group='foo', beamline_id='testing',
config={})
hdr = db[uid]
db.fetch_events(hdr)
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
|
Update test after RE -> gs.RE change.
|
TST: Update test after RE -> gs.RE change.
|
Python
|
bsd-3-clause
|
sameera2004/bluesky,ericdill/bluesky,klauer/bluesky,klauer/bluesky,ericdill/bluesky,dchabot/bluesky,sameera2004/bluesky,dchabot/bluesky
|
from metadatastore.utils.testing import mds_setup, mds_teardown
from dataportal import DataBroker as db
- from bluesky.examples import *
+ from bluesky.examples import stepscan, det, motor
- from bluesky.standard_config import RE
+ from bluesky.standard_config import gs
def setup():
mds_setup()
def teardown():
mds_teardown()
def test_scan_and_get_data():
- uid = RE(stepscan(det, motor), group='foo', beamline_id='testing',
+ uid = gs.RE(stepscan(det, motor), group='foo', beamline_id='testing',
config={})
hdr = db[uid]
- ev = db.fetch_events(hdr)
+ db.fetch_events(hdr)
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
|
Update test after RE -> gs.RE change.
|
## Code Before:
from metadatastore.utils.testing import mds_setup, mds_teardown
from dataportal import DataBroker as db
from bluesky.examples import *
from bluesky.standard_config import RE
def setup():
mds_setup()
def teardown():
mds_teardown()
def test_scan_and_get_data():
uid = RE(stepscan(det, motor), group='foo', beamline_id='testing',
config={})
hdr = db[uid]
ev = db.fetch_events(hdr)
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
## Instruction:
Update test after RE -> gs.RE change.
## Code After:
from metadatastore.utils.testing import mds_setup, mds_teardown
from dataportal import DataBroker as db
from bluesky.examples import stepscan, det, motor
from bluesky.standard_config import gs
def setup():
mds_setup()
def teardown():
mds_teardown()
def test_scan_and_get_data():
uid = gs.RE(stepscan(det, motor), group='foo', beamline_id='testing',
config={})
hdr = db[uid]
db.fetch_events(hdr)
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
|
# ... existing code ...
from dataportal import DataBroker as db
from bluesky.examples import stepscan, det, motor
from bluesky.standard_config import gs
# ... modified code ...
def test_scan_and_get_data():
uid = gs.RE(stepscan(det, motor), group='foo', beamline_id='testing',
config={})
...
hdr = db[uid]
db.fetch_events(hdr)
# ... rest of the code ...
|
0e1bdcb4e6d2404bb832ab86ec7bf526c1c90bbb
|
teami18n/teami18n/models.py
|
teami18n/teami18n/models.py
|
from django.db import models
from django_countries import countries
class Country(models.Model):
code = models.CharField(max_length=2, choices=tuple(countries),
unique=True)
class Podcast(models.Model):
story_id = models.CharField(max_length=16, unique=True)
link = models.URLField()
title = models.TextField()
teaser = models.TextField()
program_name = models.TextField(blank=True)
show_date = models.DateTimeField(null=True, blank=True)
image_link = models.URLField(null=True, blank=True)
countries = models.ManyToManyField(Country, related_name="podcasts")
|
from django.db import models
from django_countries import countries
class Country(models.Model):
code = models.CharField(max_length=2, choices=tuple(countries),
unique=True)
def __unicode__(self):
return self.code
class Podcast(models.Model):
story_id = models.CharField(max_length=16, unique=True)
link = models.URLField()
title = models.TextField()
teaser = models.TextField()
program_name = models.TextField(blank=True)
show_date = models.DateTimeField(null=True, blank=True)
image_link = models.URLField(null=True, blank=True)
countries = models.ManyToManyField(Country, related_name="podcasts")
def __unicode__(self):
return self.title
|
Add nice name for working in the shell
|
Add nice name for working in the shell
|
Python
|
mit
|
team-i18n/hackaway,team-i18n/hackaway,team-i18n/hackaway
|
from django.db import models
from django_countries import countries
class Country(models.Model):
code = models.CharField(max_length=2, choices=tuple(countries),
unique=True)
+
+ def __unicode__(self):
+ return self.code
class Podcast(models.Model):
story_id = models.CharField(max_length=16, unique=True)
link = models.URLField()
title = models.TextField()
teaser = models.TextField()
program_name = models.TextField(blank=True)
show_date = models.DateTimeField(null=True, blank=True)
image_link = models.URLField(null=True, blank=True)
countries = models.ManyToManyField(Country, related_name="podcasts")
+ def __unicode__(self):
+ return self.title
+
|
Add nice name for working in the shell
|
## Code Before:
from django.db import models
from django_countries import countries
class Country(models.Model):
code = models.CharField(max_length=2, choices=tuple(countries),
unique=True)
class Podcast(models.Model):
story_id = models.CharField(max_length=16, unique=True)
link = models.URLField()
title = models.TextField()
teaser = models.TextField()
program_name = models.TextField(blank=True)
show_date = models.DateTimeField(null=True, blank=True)
image_link = models.URLField(null=True, blank=True)
countries = models.ManyToManyField(Country, related_name="podcasts")
## Instruction:
Add nice name for working in the shell
## Code After:
from django.db import models
from django_countries import countries
class Country(models.Model):
code = models.CharField(max_length=2, choices=tuple(countries),
unique=True)
def __unicode__(self):
return self.code
class Podcast(models.Model):
story_id = models.CharField(max_length=16, unique=True)
link = models.URLField()
title = models.TextField()
teaser = models.TextField()
program_name = models.TextField(blank=True)
show_date = models.DateTimeField(null=True, blank=True)
image_link = models.URLField(null=True, blank=True)
countries = models.ManyToManyField(Country, related_name="podcasts")
def __unicode__(self):
return self.title
|
// ... existing code ...
unique=True)
def __unicode__(self):
return self.code
// ... modified code ...
countries = models.ManyToManyField(Country, related_name="podcasts")
def __unicode__(self):
return self.title
// ... rest of the code ...
|
32e066988a902f19d171225891f0a52a13945526
|
frappe/patches/v12_0/move_form_attachments_to_attachments_folder.py
|
frappe/patches/v12_0/move_form_attachments_to_attachments_folder.py
|
import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
''')
|
import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
AND folder = 'Home'
''')
|
Move files only from Home folder
|
fix(patch): Move files only from Home folder
|
Python
|
mit
|
mhbu50/frappe,frappe/frappe,vjFaLk/frappe,adityahase/frappe,adityahase/frappe,mhbu50/frappe,mhbu50/frappe,vjFaLk/frappe,vjFaLk/frappe,StrellaGroup/frappe,yashodhank/frappe,yashodhank/frappe,frappe/frappe,almeidapaulopt/frappe,yashodhank/frappe,StrellaGroup/frappe,yashodhank/frappe,vjFaLk/frappe,saurabh6790/frappe,mhbu50/frappe,adityahase/frappe,saurabh6790/frappe,almeidapaulopt/frappe,adityahase/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,saurabh6790/frappe,frappe/frappe,StrellaGroup/frappe,saurabh6790/frappe
|
import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
+ AND folder = 'Home'
''')
|
Move files only from Home folder
|
## Code Before:
import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
''')
## Instruction:
Move files only from Home folder
## Code After:
import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
AND folder = 'Home'
''')
|
...
WHERE ifnull(attached_to_doctype, '') != ''
AND folder = 'Home'
''')
...
|
fb027f075c3745c5b14a5c611063d161a47f60e4
|
oidc_apis/id_token.py
|
oidc_apis/id_token.py
|
import inspect
from .scopes import get_userinfo_by_scopes
def process_id_token(payload, user, scope=None):
if scope is None:
# HACK: Steal the scope argument from the locals dictionary of
# the caller, since it was not passed to us
scope = inspect.stack()[1][0].f_locals.get('scope', [])
payload.update(get_userinfo_by_scopes(user, scope))
payload['preferred_username'] = user.username
return payload
|
import inspect
from .scopes import get_userinfo_by_scopes
def process_id_token(payload, user, scope=None):
if scope is None:
# HACK: Steal the scope argument from the locals dictionary of
# the caller, since it was not passed to us
scope = inspect.stack()[1][0].f_locals.get('scope', [])
payload.update(get_userinfo_by_scopes(user, scope))
return payload
|
Revert "Add username to ID Token"
|
Revert "Add username to ID Token"
This reverts commit 6e1126fe9a8269ff4489ee338000afc852bce922.
|
Python
|
mit
|
mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo
|
import inspect
from .scopes import get_userinfo_by_scopes
def process_id_token(payload, user, scope=None):
if scope is None:
# HACK: Steal the scope argument from the locals dictionary of
# the caller, since it was not passed to us
scope = inspect.stack()[1][0].f_locals.get('scope', [])
payload.update(get_userinfo_by_scopes(user, scope))
- payload['preferred_username'] = user.username
return payload
|
Revert "Add username to ID Token"
|
## Code Before:
import inspect
from .scopes import get_userinfo_by_scopes
def process_id_token(payload, user, scope=None):
if scope is None:
# HACK: Steal the scope argument from the locals dictionary of
# the caller, since it was not passed to us
scope = inspect.stack()[1][0].f_locals.get('scope', [])
payload.update(get_userinfo_by_scopes(user, scope))
payload['preferred_username'] = user.username
return payload
## Instruction:
Revert "Add username to ID Token"
## Code After:
import inspect
from .scopes import get_userinfo_by_scopes
def process_id_token(payload, user, scope=None):
if scope is None:
# HACK: Steal the scope argument from the locals dictionary of
# the caller, since it was not passed to us
scope = inspect.stack()[1][0].f_locals.get('scope', [])
payload.update(get_userinfo_by_scopes(user, scope))
return payload
|
...
payload.update(get_userinfo_by_scopes(user, scope))
return payload
...
|
193831b6ee8b49674e32413e71819f2451bfc844
|
situational/apps/quick_history/forms.py
|
situational/apps/quick_history/forms.py
|
from django import forms
from . import widgets
class HistoryDetailsForm(forms.Form):
CIRCUMSTANCE_CHOICES = [
("full_time", "Full time"),
("part_time", "Part time"),
("work_programme", "Work programme"),
("unemployed", "Unemployed"),
("sick", "Off sick"),
("training", "In full time training"),
("caring", "Caring full time for others"),
("none", "None of these"),
]
circumstances = forms.ChoiceField(
widget=forms.RadioSelect(),
choices=CIRCUMSTANCE_CHOICES
)
date = forms.DateField(
widget=widgets.MonthYearWidget(years=range(2000, 2016))
)
description = forms.CharField(required=False)
def clean(self):
cleaned_data = super(HistoryDetailsForm, self).clean()
return cleaned_data
|
from django import forms
from . import widgets
class HistoryDetailsForm(forms.Form):
CIRCUMSTANCE_CHOICES = [
("full_time", "Full time"),
("part_time", "Part time"),
("unemployed", "Unemployed"),
("sick", "Off sick"),
("training", "In full time training"),
("caring", "Caring full time for others"),
("none", "None of these"),
]
circumstances = forms.ChoiceField(
widget=forms.RadioSelect(),
choices=CIRCUMSTANCE_CHOICES
)
date = forms.DateField(
widget=widgets.MonthYearWidget(years=range(2000, 2016))
)
description = forms.CharField(required=False)
def clean(self):
cleaned_data = super(HistoryDetailsForm, self).clean()
return cleaned_data
|
Remove "work programme" option from quick history
|
Remove "work programme" option from quick history
|
Python
|
bsd-3-clause
|
lm-tools/situational,lm-tools/sectors,lm-tools/situational,lm-tools/situational,lm-tools/situational,lm-tools/sectors,lm-tools/situational,lm-tools/sectors,lm-tools/sectors
|
from django import forms
from . import widgets
class HistoryDetailsForm(forms.Form):
CIRCUMSTANCE_CHOICES = [
("full_time", "Full time"),
("part_time", "Part time"),
- ("work_programme", "Work programme"),
("unemployed", "Unemployed"),
("sick", "Off sick"),
("training", "In full time training"),
("caring", "Caring full time for others"),
("none", "None of these"),
]
circumstances = forms.ChoiceField(
widget=forms.RadioSelect(),
choices=CIRCUMSTANCE_CHOICES
)
date = forms.DateField(
widget=widgets.MonthYearWidget(years=range(2000, 2016))
)
description = forms.CharField(required=False)
def clean(self):
cleaned_data = super(HistoryDetailsForm, self).clean()
return cleaned_data
|
Remove "work programme" option from quick history
|
## Code Before:
from django import forms
from . import widgets
class HistoryDetailsForm(forms.Form):
CIRCUMSTANCE_CHOICES = [
("full_time", "Full time"),
("part_time", "Part time"),
("work_programme", "Work programme"),
("unemployed", "Unemployed"),
("sick", "Off sick"),
("training", "In full time training"),
("caring", "Caring full time for others"),
("none", "None of these"),
]
circumstances = forms.ChoiceField(
widget=forms.RadioSelect(),
choices=CIRCUMSTANCE_CHOICES
)
date = forms.DateField(
widget=widgets.MonthYearWidget(years=range(2000, 2016))
)
description = forms.CharField(required=False)
def clean(self):
cleaned_data = super(HistoryDetailsForm, self).clean()
return cleaned_data
## Instruction:
Remove "work programme" option from quick history
## Code After:
from django import forms
from . import widgets
class HistoryDetailsForm(forms.Form):
CIRCUMSTANCE_CHOICES = [
("full_time", "Full time"),
("part_time", "Part time"),
("unemployed", "Unemployed"),
("sick", "Off sick"),
("training", "In full time training"),
("caring", "Caring full time for others"),
("none", "None of these"),
]
circumstances = forms.ChoiceField(
widget=forms.RadioSelect(),
choices=CIRCUMSTANCE_CHOICES
)
date = forms.DateField(
widget=widgets.MonthYearWidget(years=range(2000, 2016))
)
description = forms.CharField(required=False)
def clean(self):
cleaned_data = super(HistoryDetailsForm, self).clean()
return cleaned_data
|
// ... existing code ...
("part_time", "Part time"),
("unemployed", "Unemployed"),
// ... rest of the code ...
|
43238d0de9e4d6d4909b4d67c17449a9599e5dac
|
mygpo/web/templatetags/time.py
|
mygpo/web/templatetags/time.py
|
from datetime import time
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django import template
register = template.Library()
@register.filter
def sec_to_time(sec):
""" Converts seconds to a time object
>>> t = sec_to_time(1000)
>>> (t.hour, t.minute, t.second)
(0, 16, 40)
"""
s = int(sec)
hour = int(s / 60 / 60)
minute = int((s / 60) % 60)
sec = int(s % 60 )
return time(hour, minute, sec)
@register.filter
@mark_safe
def format_duration(sec):
""" Converts seconds into a duration string
>>> format_duration(1000)
'0h 16m 40s'
"""
hours = int(sec / 60 / 60)
minutes = int((sec / 60) % 60)
seconds = int(sec % 60)
return _('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds)
|
from datetime import time
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django import template
register = template.Library()
@register.filter
def sec_to_time(sec):
""" Converts seconds to a time object
>>> t = sec_to_time(1000)
>>> (t.hour, t.minute, t.second)
(0, 16, 40)
"""
s = int(sec)
hour = int(s / 60 / 60)
minute = int((s / 60) % 60)
sec = int(s % 60 )
return time(hour, minute, sec)
@register.filter
@mark_safe
def format_duration(sec):
""" Converts seconds into a duration string
>>> format_duration(1000)
'16m 40s'
>>> format_duration(10009)
'2h 46m 49s'
"""
hours = int(sec / 60 / 60)
minutes = int((sec / 60) % 60)
seconds = int(sec % 60)
if hours:
return _('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds)
else:
return _('{m}m {s}s').format(m=minutes, s=seconds)
|
Format short durations without "0 hours"
|
Format short durations without "0 hours"
|
Python
|
agpl-3.0
|
gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo
|
from datetime import time
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django import template
register = template.Library()
@register.filter
def sec_to_time(sec):
""" Converts seconds to a time object
>>> t = sec_to_time(1000)
>>> (t.hour, t.minute, t.second)
(0, 16, 40)
"""
s = int(sec)
hour = int(s / 60 / 60)
minute = int((s / 60) % 60)
sec = int(s % 60 )
return time(hour, minute, sec)
@register.filter
@mark_safe
def format_duration(sec):
""" Converts seconds into a duration string
>>> format_duration(1000)
- '0h 16m 40s'
+ '16m 40s'
+ >>> format_duration(10009)
+ '2h 46m 49s'
"""
hours = int(sec / 60 / 60)
minutes = int((sec / 60) % 60)
seconds = int(sec % 60)
- return _('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds)
+ if hours:
+ return _('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds)
+ else:
+ return _('{m}m {s}s').format(m=minutes, s=seconds)
+
|
Format short durations without "0 hours"
|
## Code Before:
from datetime import time
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django import template
register = template.Library()
@register.filter
def sec_to_time(sec):
""" Converts seconds to a time object
>>> t = sec_to_time(1000)
>>> (t.hour, t.minute, t.second)
(0, 16, 40)
"""
s = int(sec)
hour = int(s / 60 / 60)
minute = int((s / 60) % 60)
sec = int(s % 60 )
return time(hour, minute, sec)
@register.filter
@mark_safe
def format_duration(sec):
""" Converts seconds into a duration string
>>> format_duration(1000)
'0h 16m 40s'
"""
hours = int(sec / 60 / 60)
minutes = int((sec / 60) % 60)
seconds = int(sec % 60)
return _('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds)
## Instruction:
Format short durations without "0 hours"
## Code After:
from datetime import time
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django import template
register = template.Library()
@register.filter
def sec_to_time(sec):
""" Converts seconds to a time object
>>> t = sec_to_time(1000)
>>> (t.hour, t.minute, t.second)
(0, 16, 40)
"""
s = int(sec)
hour = int(s / 60 / 60)
minute = int((s / 60) % 60)
sec = int(s % 60 )
return time(hour, minute, sec)
@register.filter
@mark_safe
def format_duration(sec):
""" Converts seconds into a duration string
>>> format_duration(1000)
'16m 40s'
>>> format_duration(10009)
'2h 46m 49s'
"""
hours = int(sec / 60 / 60)
minutes = int((sec / 60) % 60)
seconds = int(sec % 60)
if hours:
return _('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds)
else:
return _('{m}m {s}s').format(m=minutes, s=seconds)
|
// ... existing code ...
>>> format_duration(1000)
'16m 40s'
>>> format_duration(10009)
'2h 46m 49s'
"""
// ... modified code ...
seconds = int(sec % 60)
if hours:
return _('{h}h {m}m {s}s').format(h=hours, m=minutes, s=seconds)
else:
return _('{m}m {s}s').format(m=minutes, s=seconds)
// ... rest of the code ...
|
ecc3a9c90d20699c6f0bf18600cf9bd755b56d65
|
rollbar/contrib/fastapi/utils.py
|
rollbar/contrib/fastapi/utils.py
|
import logging
log = logging.getLogger(__name__)
class FastAPIVersionError(Exception):
def __init__(self, version, reason=''):
err_msg = f'FastAPI {version}+ is required'
if reason:
err_msg += f' {reason}'
log.error(err_msg)
return super().__init__(err_msg)
|
import functools
import logging
import fastapi
log = logging.getLogger(__name__)
class FastAPIVersionError(Exception):
def __init__(self, version, reason=''):
err_msg = f'FastAPI {version}+ is required'
if reason:
err_msg += f' {reason}'
log.error(err_msg)
return super().__init__(err_msg)
class fastapi_min_version:
def __init__(self, min_version):
self.min_version = min_version
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if fastapi.__version__ < self.min_version:
raise FastAPIVersionError(
'0.41.0', reason=f'to use {func.__name__}() function'
)
return func(*args, **kwargs)
return wrapper
|
Add decorator to check minimum required FastAPI version
|
Add decorator to check minimum required FastAPI version
|
Python
|
mit
|
rollbar/pyrollbar
|
+ import functools
import logging
+
+ import fastapi
log = logging.getLogger(__name__)
class FastAPIVersionError(Exception):
def __init__(self, version, reason=''):
err_msg = f'FastAPI {version}+ is required'
if reason:
err_msg += f' {reason}'
log.error(err_msg)
return super().__init__(err_msg)
+
+ class fastapi_min_version:
+ def __init__(self, min_version):
+ self.min_version = min_version
+
+ def __call__(self, func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ if fastapi.__version__ < self.min_version:
+ raise FastAPIVersionError(
+ '0.41.0', reason=f'to use {func.__name__}() function'
+ )
+
+ return func(*args, **kwargs)
+
+ return wrapper
+
|
Add decorator to check minimum required FastAPI version
|
## Code Before:
import logging
log = logging.getLogger(__name__)
class FastAPIVersionError(Exception):
def __init__(self, version, reason=''):
err_msg = f'FastAPI {version}+ is required'
if reason:
err_msg += f' {reason}'
log.error(err_msg)
return super().__init__(err_msg)
## Instruction:
Add decorator to check minimum required FastAPI version
## Code After:
import functools
import logging
import fastapi
log = logging.getLogger(__name__)
class FastAPIVersionError(Exception):
def __init__(self, version, reason=''):
err_msg = f'FastAPI {version}+ is required'
if reason:
err_msg += f' {reason}'
log.error(err_msg)
return super().__init__(err_msg)
class fastapi_min_version:
def __init__(self, min_version):
self.min_version = min_version
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if fastapi.__version__ < self.min_version:
raise FastAPIVersionError(
'0.41.0', reason=f'to use {func.__name__}() function'
)
return func(*args, **kwargs)
return wrapper
|
...
import functools
import logging
import fastapi
...
return super().__init__(err_msg)
class fastapi_min_version:
def __init__(self, min_version):
self.min_version = min_version
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if fastapi.__version__ < self.min_version:
raise FastAPIVersionError(
'0.41.0', reason=f'to use {func.__name__}() function'
)
return func(*args, **kwargs)
return wrapper
...
|
f3fb5bd0dbb3e19e58558af015aaee5ec120af71
|
portal/template_helpers.py
|
portal/template_helpers.py
|
""" Module for helper functions used inside jinja2 templates """
# NB, each blueprint must individually load any functions defined below
# for them to appear in the namespace when invoked from respective blueprint
# See @<blueprint>.context_processor decorator for more info.
def split_string(s, delimiter=','):
return s.split(delimiter)
|
""" Module for helper functions used inside jinja2 templates """
# NB, each blueprint must individually load any functions defined below
# for them to appear in the namespace when invoked from respective blueprint
# See @<blueprint>.context_processor decorator for more info.
def split_string(s, delimiter=','):
"""Given string (or tuple) return the delimited values"""
# If given a tuple, split already happened
if isinstance(s, (list, tuple)):
return s
return s.split(delimiter)
|
Allow for list/tuples in config files when looking for comma delimited strings.
|
Allow for list/tuples in config files when looking for comma delimited
strings.
|
Python
|
bsd-3-clause
|
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
|
""" Module for helper functions used inside jinja2 templates """
# NB, each blueprint must individually load any functions defined below
# for them to appear in the namespace when invoked from respective blueprint
# See @<blueprint>.context_processor decorator for more info.
def split_string(s, delimiter=','):
+ """Given string (or tuple) return the delimited values"""
+ # If given a tuple, split already happened
+ if isinstance(s, (list, tuple)):
+ return s
return s.split(delimiter)
|
Allow for list/tuples in config files when looking for comma delimited strings.
|
## Code Before:
""" Module for helper functions used inside jinja2 templates """
# NB, each blueprint must individually load any functions defined below
# for them to appear in the namespace when invoked from respective blueprint
# See @<blueprint>.context_processor decorator for more info.
def split_string(s, delimiter=','):
return s.split(delimiter)
## Instruction:
Allow for list/tuples in config files when looking for comma delimited strings.
## Code After:
""" Module for helper functions used inside jinja2 templates """
# NB, each blueprint must individually load any functions defined below
# for them to appear in the namespace when invoked from respective blueprint
# See @<blueprint>.context_processor decorator for more info.
def split_string(s, delimiter=','):
"""Given string (or tuple) return the delimited values"""
# If given a tuple, split already happened
if isinstance(s, (list, tuple)):
return s
return s.split(delimiter)
|
# ... existing code ...
def split_string(s, delimiter=','):
"""Given string (or tuple) return the delimited values"""
# If given a tuple, split already happened
if isinstance(s, (list, tuple)):
return s
return s.split(delimiter)
# ... rest of the code ...
|
7dcd2c2aa1e2fd8f17e0b564f9b77375675ccd9a
|
metakernel/pexpect.py
|
metakernel/pexpect.py
|
from __future__ import absolute_import
from pexpect import spawn, which, EOF, TIMEOUT
|
from __future__ import absolute_import
from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
import os
try:
from pexpect import spawn
import pty
except ImportError:
pty = None
def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if 'PATH' not in os.environ or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if pty:
if is_executable_file(ff):
return ff
else:
pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
pathext = pathext.split(os.pathsep) + ['']
for ext in pathext:
if os.access(ff + ext, os.X_OK):
return ff + ext
return None
|
Add handling of which on Windows
|
Add handling of which on Windows
|
Python
|
bsd-3-clause
|
Calysto/metakernel
|
from __future__ import absolute_import
- from pexpect import spawn, which, EOF, TIMEOUT
+ from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
+ import os
+ try:
+ from pexpect import spawn
+ import pty
+ except ImportError:
+ pty = None
+
+
+ def which(filename):
+ '''This takes a given filename; tries to find it in the environment path;
+ then checks if it is executable. This returns the full path to the filename
+ if found and executable. Otherwise this returns None.'''
+
+ # Special case where filename contains an explicit path.
+ if os.path.dirname(filename) != '' and is_executable_file(filename):
+ return filename
+ if 'PATH' not in os.environ or os.environ['PATH'] == '':
+ p = os.defpath
+ else:
+ p = os.environ['PATH']
+ pathlist = p.split(os.pathsep)
+ for path in pathlist:
+ ff = os.path.join(path, filename)
+ if pty:
+ if is_executable_file(ff):
+ return ff
+ else:
+ pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
+ pathext = pathext.split(os.pathsep) + ['']
+ for ext in pathext:
+ if os.access(ff + ext, os.X_OK):
+ return ff + ext
+ return None
+
|
Add handling of which on Windows
|
## Code Before:
from __future__ import absolute_import
from pexpect import spawn, which, EOF, TIMEOUT
## Instruction:
Add handling of which on Windows
## Code After:
from __future__ import absolute_import
from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
import os
try:
from pexpect import spawn
import pty
except ImportError:
pty = None
def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if 'PATH' not in os.environ or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if pty:
if is_executable_file(ff):
return ff
else:
pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
pathext = pathext.split(os.pathsep) + ['']
for ext in pathext:
if os.access(ff + ext, os.X_OK):
return ff + ext
return None
|
# ... existing code ...
from __future__ import absolute_import
from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
import os
try:
from pexpect import spawn
import pty
except ImportError:
pty = None
def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if 'PATH' not in os.environ or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if pty:
if is_executable_file(ff):
return ff
else:
pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
pathext = pathext.split(os.pathsep) + ['']
for ext in pathext:
if os.access(ff + ext, os.X_OK):
return ff + ext
return None
# ... rest of the code ...
|
2eac437b9d907fb60d53522633dd278aa277ea08
|
test/user_tests/test_models.py
|
test/user_tests/test_models.py
|
import unittest
from test.factories import UserFactory
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from users.models import create_user_profile, Users
class UserTest(unittest.TestCase):
'''User-specific tests'''
def setUp(self):
self.user = UserFactory.build()
def tearDown(self):
self.user = None
def test_user(self):
self.assertNotEqual(None, self.user)
self.assertEqual('Boy', self.user.first_name)
self.assertEqual('Factory', self.user.last_name)
self.assertEqual('[email protected]', self.user.email)
def test_user_generator(self):
pass
class UserProfileTest(unittest.TestCase):
'''User profile test'''
def test_post_save_signal(self):
# Disconnect post_save signal from user model (for test purposing only)
post_save.disconnect(create_user_profile, sender=User)
sender = User
user = UserFactory.create()
create_user_profile(sender, user, True)
cnt = Users.objects.all().count()
self.assertEqual(1, cnt)
|
import unittest
from test.factories import UserFactory
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from users.models import create_new_user, Users
class UserTest(unittest.TestCase):
'''User-specific tests'''
def setUp(self):
self.user = UserFactory.build()
def tearDown(self):
self.user = None
def test_user(self):
self.assertNotEqual(None, self.user)
self.assertEqual('Boy', self.user.first_name)
self.assertEqual('Factory', self.user.last_name)
self.assertEqual('[email protected]', self.user.email)
def test_user_generator(self):
pass
def test_create_new_user(self):
self.assertEqual(0, User.objects.all().count())
create_new_user(
first_name = self.user.first_name,
last_name = self.user.last_name,
email = self.user.email,
password='123'
)
self.assertEqual(1, User.objects.all().count())
u = User.objects.get(email=self.user.email)
self.assertEqual(u.first_name, self.user.first_name)
self.assertEqual(u.last_name, self.user.last_name)
self.assertTrue(u.check_password('123'))
self.assertFalse(u.is_staff)
self.assertFalse(u.is_active)
|
Test for create user in model. Remove test profile creation
|
Test for create user in model. Remove test profile creation
|
Python
|
mit
|
sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa
|
import unittest
from test.factories import UserFactory
from django.contrib.auth.models import User
from django.db.models.signals import post_save
- from users.models import create_user_profile, Users
+ from users.models import create_new_user, Users
class UserTest(unittest.TestCase):
'''User-specific tests'''
def setUp(self):
self.user = UserFactory.build()
def tearDown(self):
self.user = None
def test_user(self):
self.assertNotEqual(None, self.user)
self.assertEqual('Boy', self.user.first_name)
self.assertEqual('Factory', self.user.last_name)
self.assertEqual('[email protected]', self.user.email)
def test_user_generator(self):
pass
+ def test_create_new_user(self):
+ self.assertEqual(0, User.objects.all().count())
+ create_new_user(
+ first_name = self.user.first_name,
+ last_name = self.user.last_name,
+ email = self.user.email,
+ password='123'
+ )
+ self.assertEqual(1, User.objects.all().count())
+ u = User.objects.get(email=self.user.email)
+ self.assertEqual(u.first_name, self.user.first_name)
+ self.assertEqual(u.last_name, self.user.last_name)
+ self.assertTrue(u.check_password('123'))
+ self.assertFalse(u.is_staff)
+ self.assertFalse(u.is_active)
- class UserProfileTest(unittest.TestCase):
- '''User profile test'''
- def test_post_save_signal(self):
- # Disconnect post_save signal from user model (for test purposing only)
- post_save.disconnect(create_user_profile, sender=User)
- sender = User
- user = UserFactory.create()
- create_user_profile(sender, user, True)
- cnt = Users.objects.all().count()
- self.assertEqual(1, cnt)
|
Test for create user in model. Remove test profile creation
|
## Code Before:
import unittest
from test.factories import UserFactory
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from users.models import create_user_profile, Users
class UserTest(unittest.TestCase):
'''User-specific tests'''
def setUp(self):
self.user = UserFactory.build()
def tearDown(self):
self.user = None
def test_user(self):
self.assertNotEqual(None, self.user)
self.assertEqual('Boy', self.user.first_name)
self.assertEqual('Factory', self.user.last_name)
self.assertEqual('[email protected]', self.user.email)
def test_user_generator(self):
pass
class UserProfileTest(unittest.TestCase):
'''User profile test'''
def test_post_save_signal(self):
# Disconnect post_save signal from user model (for test purposing only)
post_save.disconnect(create_user_profile, sender=User)
sender = User
user = UserFactory.create()
create_user_profile(sender, user, True)
cnt = Users.objects.all().count()
self.assertEqual(1, cnt)
## Instruction:
Test for create user in model. Remove test profile creation
## Code After:
import unittest
from test.factories import UserFactory
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from users.models import create_new_user, Users
class UserTest(unittest.TestCase):
'''User-specific tests'''
def setUp(self):
self.user = UserFactory.build()
def tearDown(self):
self.user = None
def test_user(self):
self.assertNotEqual(None, self.user)
self.assertEqual('Boy', self.user.first_name)
self.assertEqual('Factory', self.user.last_name)
self.assertEqual('[email protected]', self.user.email)
def test_user_generator(self):
pass
def test_create_new_user(self):
self.assertEqual(0, User.objects.all().count())
create_new_user(
first_name = self.user.first_name,
last_name = self.user.last_name,
email = self.user.email,
password='123'
)
self.assertEqual(1, User.objects.all().count())
u = User.objects.get(email=self.user.email)
self.assertEqual(u.first_name, self.user.first_name)
self.assertEqual(u.last_name, self.user.last_name)
self.assertTrue(u.check_password('123'))
self.assertFalse(u.is_staff)
self.assertFalse(u.is_active)
|
# ... existing code ...
from users.models import create_new_user, Users
# ... modified code ...
def test_create_new_user(self):
self.assertEqual(0, User.objects.all().count())
create_new_user(
first_name = self.user.first_name,
last_name = self.user.last_name,
email = self.user.email,
password='123'
)
self.assertEqual(1, User.objects.all().count())
u = User.objects.get(email=self.user.email)
self.assertEqual(u.first_name, self.user.first_name)
self.assertEqual(u.last_name, self.user.last_name)
self.assertTrue(u.check_password('123'))
self.assertFalse(u.is_staff)
self.assertFalse(u.is_active)
# ... rest of the code ...
|
65c5474936dca27023e45c1644fa2a9492e9a420
|
tests/convergence_tests/run_convergence_tests_lspr.py
|
tests/convergence_tests/run_convergence_tests_lspr.py
|
import os
import time
import subprocess
import datetime
from check_for_meshes import check_mesh
# tests to run
tests = ['sphere_lspr.py', 'sphere_multiple_lspr.py']
# specify CUDA device to use
CUDA_DEVICE = '0'
ENV = os.environ.copy()
ENV['CUDA_DEVICE'] = CUDA_DEVICE
mesh_file = ''
folder_name = 'lspr_convergence_test_meshes'
rename_folder = 'geometry_lspr'
size = '~3MB'
check_mesh(mesh_file, folder_name, rename_folder, size)
tic = time.time()
for test in tests:
subprocess.call(['python', '{}'.format(test)])
toc = time.time()
print("Total runtime for convergence tests: ")
print(str(datetime.timedelta(seconds=(toc - tic))))
|
import os
import time
import subprocess
import datetime
from check_for_meshes import check_mesh
# tests to run
tests = ['sphere_lspr.py', 'sphere_multiple_lspr.py']
# specify CUDA device to use
CUDA_DEVICE = '0'
ENV = os.environ.copy()
ENV['CUDA_DEVICE'] = CUDA_DEVICE
mesh_file = 'https://zenodo.org/record/580786/files/pygbe-lspr_convergence_test_meshes.zip'
folder_name = 'lspr_convergence_test_meshes'
rename_folder = 'geometry_lspr'
size = '~3MB'
check_mesh(mesh_file, folder_name, rename_folder, size)
tic = time.time()
for test in tests:
subprocess.call(['python', '{}'.format(test)])
toc = time.time()
print("Total runtime for convergence tests: ")
print(str(datetime.timedelta(seconds=(toc - tic))))
|
Add path to convergence test lspr zip file
|
Add path to convergence test lspr zip file
|
Python
|
bsd-3-clause
|
barbagroup/pygbe,barbagroup/pygbe,barbagroup/pygbe
|
import os
import time
import subprocess
import datetime
from check_for_meshes import check_mesh
# tests to run
tests = ['sphere_lspr.py', 'sphere_multiple_lspr.py']
# specify CUDA device to use
CUDA_DEVICE = '0'
ENV = os.environ.copy()
ENV['CUDA_DEVICE'] = CUDA_DEVICE
- mesh_file = ''
+ mesh_file = 'https://zenodo.org/record/580786/files/pygbe-lspr_convergence_test_meshes.zip'
folder_name = 'lspr_convergence_test_meshes'
rename_folder = 'geometry_lspr'
size = '~3MB'
check_mesh(mesh_file, folder_name, rename_folder, size)
tic = time.time()
for test in tests:
subprocess.call(['python', '{}'.format(test)])
toc = time.time()
print("Total runtime for convergence tests: ")
print(str(datetime.timedelta(seconds=(toc - tic))))
|
Add path to convergence test lspr zip file
|
## Code Before:
import os
import time
import subprocess
import datetime
from check_for_meshes import check_mesh
# tests to run
tests = ['sphere_lspr.py', 'sphere_multiple_lspr.py']
# specify CUDA device to use
CUDA_DEVICE = '0'
ENV = os.environ.copy()
ENV['CUDA_DEVICE'] = CUDA_DEVICE
mesh_file = ''
folder_name = 'lspr_convergence_test_meshes'
rename_folder = 'geometry_lspr'
size = '~3MB'
check_mesh(mesh_file, folder_name, rename_folder, size)
tic = time.time()
for test in tests:
subprocess.call(['python', '{}'.format(test)])
toc = time.time()
print("Total runtime for convergence tests: ")
print(str(datetime.timedelta(seconds=(toc - tic))))
## Instruction:
Add path to convergence test lspr zip file
## Code After:
import os
import time
import subprocess
import datetime
from check_for_meshes import check_mesh
# tests to run
tests = ['sphere_lspr.py', 'sphere_multiple_lspr.py']
# specify CUDA device to use
CUDA_DEVICE = '0'
ENV = os.environ.copy()
ENV['CUDA_DEVICE'] = CUDA_DEVICE
mesh_file = 'https://zenodo.org/record/580786/files/pygbe-lspr_convergence_test_meshes.zip'
folder_name = 'lspr_convergence_test_meshes'
rename_folder = 'geometry_lspr'
size = '~3MB'
check_mesh(mesh_file, folder_name, rename_folder, size)
tic = time.time()
for test in tests:
subprocess.call(['python', '{}'.format(test)])
toc = time.time()
print("Total runtime for convergence tests: ")
print(str(datetime.timedelta(seconds=(toc - tic))))
|
...
mesh_file = 'https://zenodo.org/record/580786/files/pygbe-lspr_convergence_test_meshes.zip'
folder_name = 'lspr_convergence_test_meshes'
...
|
6c6f6ec6c5a895f083ff8c9b9a0d76791bb13ce9
|
app/eve_api/tasks/static.py
|
app/eve_api/tasks/static.py
|
from celery.decorators import task
from eve_proxy.models import CachedDocument
from eve_api.utils import basic_xml_parse_doc
from eve_api.models import EVESkill, EVESkillGroup
@task()
def import_eve_skills():
"""
Imports the skill tree and groups
"""
char_doc = CachedDocument.objects.api_query('/eve/SkillTree.xml.aspx')
d = basic_xml_parse_doc(char_doc)['eveapi']
if 'error' in d:
return
values = d['result']
for group in values['skillGroups']:
gobj, created = EVESkillGroup.objects.get_or_create(id=group['groupID'])
if created:
gobj.name = group['groupName']
gobj.save()
for skill in group['skills']:
skillobj, created = EVESkill.objects.get_or_create(id=skill['typeID'])
if created or not skillobj.name or not skillobj.group:
skillobj.name = skill['typeName']
skillobj.group = gobj
skillobj.save()
|
from celery.decorators import task
from eve_proxy.models import CachedDocument
from eve_api.utils import basic_xml_parse_doc
from eve_api.models import EVESkill, EVESkillGroup
@task()
def import_eve_skills():
"""
Imports the skill tree and groups
"""
char_doc = CachedDocument.objects.api_query('/eve/SkillTree.xml.aspx')
d = basic_xml_parse_doc(char_doc)['eveapi']
if 'error' in d:
return
values = d['result']
for group in values['skillGroups']:
gobj, created = EVESkillGroup.objects.get_or_create(id=group['groupID'])
if created or not gobj.name or not gobj.name == group['groupName']:
gobj.name = group['groupName']
gobj.save()
for skill in group['skills']:
skillobj, created = EVESkill.objects.get_or_create(id=skill['typeID'])
if created or not skillobj.name or not skillobj.group or not skillobj.name == skill['typeName']:
skillobj.name = skill['typeName']
skillobj.group = gobj
skillobj.save()
|
Support if skill group/types are changed
|
Support if skill group/types are changed
|
Python
|
bsd-3-clause
|
nikdoof/test-auth
|
from celery.decorators import task
from eve_proxy.models import CachedDocument
from eve_api.utils import basic_xml_parse_doc
from eve_api.models import EVESkill, EVESkillGroup
@task()
def import_eve_skills():
"""
Imports the skill tree and groups
"""
char_doc = CachedDocument.objects.api_query('/eve/SkillTree.xml.aspx')
d = basic_xml_parse_doc(char_doc)['eveapi']
if 'error' in d:
return
values = d['result']
for group in values['skillGroups']:
gobj, created = EVESkillGroup.objects.get_or_create(id=group['groupID'])
- if created:
+ if created or not gobj.name or not gobj.name == group['groupName']:
gobj.name = group['groupName']
gobj.save()
for skill in group['skills']:
skillobj, created = EVESkill.objects.get_or_create(id=skill['typeID'])
- if created or not skillobj.name or not skillobj.group:
+ if created or not skillobj.name or not skillobj.group or not skillobj.name == skill['typeName']:
skillobj.name = skill['typeName']
skillobj.group = gobj
skillobj.save()
|
Support if skill group/types are changed
|
## Code Before:
from celery.decorators import task
from eve_proxy.models import CachedDocument
from eve_api.utils import basic_xml_parse_doc
from eve_api.models import EVESkill, EVESkillGroup
@task()
def import_eve_skills():
"""
Imports the skill tree and groups
"""
char_doc = CachedDocument.objects.api_query('/eve/SkillTree.xml.aspx')
d = basic_xml_parse_doc(char_doc)['eveapi']
if 'error' in d:
return
values = d['result']
for group in values['skillGroups']:
gobj, created = EVESkillGroup.objects.get_or_create(id=group['groupID'])
if created:
gobj.name = group['groupName']
gobj.save()
for skill in group['skills']:
skillobj, created = EVESkill.objects.get_or_create(id=skill['typeID'])
if created or not skillobj.name or not skillobj.group:
skillobj.name = skill['typeName']
skillobj.group = gobj
skillobj.save()
## Instruction:
Support if skill group/types are changed
## Code After:
from celery.decorators import task
from eve_proxy.models import CachedDocument
from eve_api.utils import basic_xml_parse_doc
from eve_api.models import EVESkill, EVESkillGroup
@task()
def import_eve_skills():
"""
Imports the skill tree and groups
"""
char_doc = CachedDocument.objects.api_query('/eve/SkillTree.xml.aspx')
d = basic_xml_parse_doc(char_doc)['eveapi']
if 'error' in d:
return
values = d['result']
for group in values['skillGroups']:
gobj, created = EVESkillGroup.objects.get_or_create(id=group['groupID'])
if created or not gobj.name or not gobj.name == group['groupName']:
gobj.name = group['groupName']
gobj.save()
for skill in group['skills']:
skillobj, created = EVESkill.objects.get_or_create(id=skill['typeID'])
if created or not skillobj.name or not skillobj.group or not skillobj.name == skill['typeName']:
skillobj.name = skill['typeName']
skillobj.group = gobj
skillobj.save()
|
// ... existing code ...
gobj, created = EVESkillGroup.objects.get_or_create(id=group['groupID'])
if created or not gobj.name or not gobj.name == group['groupName']:
gobj.name = group['groupName']
// ... modified code ...
skillobj, created = EVESkill.objects.get_or_create(id=skill['typeID'])
if created or not skillobj.name or not skillobj.group or not skillobj.name == skill['typeName']:
skillobj.name = skill['typeName']
// ... rest of the code ...
|
9ea35a99c30f2ec7ed3946e71a286e689d2a50a3
|
api/tests/test_signup.py
|
api/tests/test_signup.py
|
from django.test import TestCase
from api.views.signup import signup
from rest_framework.test import APIRequestFactory
from api import factories, serializers
from api.models import User
from api.serializers import UserSerializer
class SignupTest(TestCase):
PASSWORD = 'test'
def setUp(self):
self.factory = APIRequestFactory()
self.user = factories.UserFactory.build()
def test_signup_works(self):
serializer = UserSerializer(self.user)
request_data = serializer.data
request_data['password'] = self.PASSWORD
request_data['password_confirmation'] = self.PASSWORD
request = self.factory.post('/api/signup/', request_data, format='json')
response = signup(request)
new_user = response.data
self.assertEqual(response.status_code, 201)
self.assertEqual(new_user.username, self.user.username)
self.assertEqual(new_user.email, self.user.email)
self.assertEqual(new_user.first_name, self.user.first_name)
self.assertEqual(new_user.last_name, self.user.last_name)
|
from django.test import TestCase
from api.views.signup import signup
from rest_framework.test import APIRequestFactory
from api import factories
from api.serializers import UserSerializer
class SignupTest(TestCase):
PASSWORD = 'test'
REQUIRED_FIELD_ERROR = 'This field is required.'
def setUp(self):
self.factory = APIRequestFactory()
self.user = factories.UserFactory.build()
def test_signup_works(self):
serializer = UserSerializer(self.user)
request_data = serializer.data
request_data['password'] = self.PASSWORD
request_data['password_confirmation'] = self.PASSWORD
request = self.factory.post('/api/signup/', request_data, format='json')
response = signup(request)
new_user = response.data
self.assertEqual(response.status_code, 201)
self.assertEqual(new_user.username, self.user.username)
self.assertEqual(new_user.email, self.user.email)
self.assertEqual(new_user.first_name, self.user.first_name)
self.assertEqual(new_user.last_name, self.user.last_name)
def test_signup_returns_errors_on_missing_required_fields(self):
request = self.factory.post('/api/signup/', {}, format='json')
response = signup(request)
data = response.data
print(data)
self.assertEqual(response.status_code, 400)
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['username'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['password'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['email'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['first_name'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['last_name'])
|
Add test for errors, but User fields need to become required first
|
Add test for errors, but User fields need to become required first
|
Python
|
mit
|
frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq
|
from django.test import TestCase
from api.views.signup import signup
from rest_framework.test import APIRequestFactory
- from api import factories, serializers
+ from api import factories
- from api.models import User
from api.serializers import UserSerializer
class SignupTest(TestCase):
PASSWORD = 'test'
+ REQUIRED_FIELD_ERROR = 'This field is required.'
def setUp(self):
self.factory = APIRequestFactory()
self.user = factories.UserFactory.build()
def test_signup_works(self):
serializer = UserSerializer(self.user)
request_data = serializer.data
request_data['password'] = self.PASSWORD
request_data['password_confirmation'] = self.PASSWORD
request = self.factory.post('/api/signup/', request_data, format='json')
response = signup(request)
new_user = response.data
self.assertEqual(response.status_code, 201)
self.assertEqual(new_user.username, self.user.username)
self.assertEqual(new_user.email, self.user.email)
self.assertEqual(new_user.first_name, self.user.first_name)
self.assertEqual(new_user.last_name, self.user.last_name)
+ def test_signup_returns_errors_on_missing_required_fields(self):
+ request = self.factory.post('/api/signup/', {}, format='json')
+ response = signup(request)
+
+ data = response.data
+ print(data)
+ self.assertEqual(response.status_code, 400)
+ self.assertTrue(self.REQUIRED_FIELD_ERROR in data['username'])
+ self.assertTrue(self.REQUIRED_FIELD_ERROR in data['password'])
+ self.assertTrue(self.REQUIRED_FIELD_ERROR in data['email'])
+ self.assertTrue(self.REQUIRED_FIELD_ERROR in data['first_name'])
+ self.assertTrue(self.REQUIRED_FIELD_ERROR in data['last_name'])
+
|
Add test for errors, but User fields need to become required first
|
## Code Before:
from django.test import TestCase
from api.views.signup import signup
from rest_framework.test import APIRequestFactory
from api import factories, serializers
from api.models import User
from api.serializers import UserSerializer
class SignupTest(TestCase):
PASSWORD = 'test'
def setUp(self):
self.factory = APIRequestFactory()
self.user = factories.UserFactory.build()
def test_signup_works(self):
serializer = UserSerializer(self.user)
request_data = serializer.data
request_data['password'] = self.PASSWORD
request_data['password_confirmation'] = self.PASSWORD
request = self.factory.post('/api/signup/', request_data, format='json')
response = signup(request)
new_user = response.data
self.assertEqual(response.status_code, 201)
self.assertEqual(new_user.username, self.user.username)
self.assertEqual(new_user.email, self.user.email)
self.assertEqual(new_user.first_name, self.user.first_name)
self.assertEqual(new_user.last_name, self.user.last_name)
## Instruction:
Add test for errors, but User fields need to become required first
## Code After:
from django.test import TestCase
from api.views.signup import signup
from rest_framework.test import APIRequestFactory
from api import factories
from api.serializers import UserSerializer
class SignupTest(TestCase):
PASSWORD = 'test'
REQUIRED_FIELD_ERROR = 'This field is required.'
def setUp(self):
self.factory = APIRequestFactory()
self.user = factories.UserFactory.build()
def test_signup_works(self):
serializer = UserSerializer(self.user)
request_data = serializer.data
request_data['password'] = self.PASSWORD
request_data['password_confirmation'] = self.PASSWORD
request = self.factory.post('/api/signup/', request_data, format='json')
response = signup(request)
new_user = response.data
self.assertEqual(response.status_code, 201)
self.assertEqual(new_user.username, self.user.username)
self.assertEqual(new_user.email, self.user.email)
self.assertEqual(new_user.first_name, self.user.first_name)
self.assertEqual(new_user.last_name, self.user.last_name)
def test_signup_returns_errors_on_missing_required_fields(self):
request = self.factory.post('/api/signup/', {}, format='json')
response = signup(request)
data = response.data
print(data)
self.assertEqual(response.status_code, 400)
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['username'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['password'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['email'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['first_name'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['last_name'])
|
# ... existing code ...
from api import factories
from api.serializers import UserSerializer
# ... modified code ...
PASSWORD = 'test'
REQUIRED_FIELD_ERROR = 'This field is required.'
...
self.assertEqual(new_user.last_name, self.user.last_name)
def test_signup_returns_errors_on_missing_required_fields(self):
request = self.factory.post('/api/signup/', {}, format='json')
response = signup(request)
data = response.data
print(data)
self.assertEqual(response.status_code, 400)
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['username'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['password'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['email'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['first_name'])
self.assertTrue(self.REQUIRED_FIELD_ERROR in data['last_name'])
# ... rest of the code ...
|
f559001d2c46fade2d9b62f9cb7a3f8053e8b80f
|
OMDB_api_scrape.py
|
OMDB_api_scrape.py
|
import json, requests, sys, os
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
theJSON = json.loads(response.text)
# Save the JSON file
with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile:
json.dump(theJSON, outfile)
|
import requests, sys, os
import lxml.etree
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
# Save the XML file
with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile:
outfile.write(response.text)
|
Convert OMDB scrapper to grab xml
|
Convert OMDB scrapper to grab xml
|
Python
|
mit
|
samcheck/PyMedia,samcheck/PyMedia,samcheck/PyMedia
|
- import json, requests, sys, os
+ import requests, sys, os
+ import lxml.etree
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
- url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
+ url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
- theJSON = json.loads(response.text)
+ # Save the XML file
+ with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile:
+ outfile.write(response.text)
- # Save the JSON file
- with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile:
- json.dump(theJSON, outfile)
-
|
Convert OMDB scrapper to grab xml
|
## Code Before:
import json, requests, sys, os
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
theJSON = json.loads(response.text)
# Save the JSON file
with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile:
json.dump(theJSON, outfile)
## Instruction:
Convert OMDB scrapper to grab xml
## Code After:
import requests, sys, os
import lxml.etree
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
# Save the XML file
with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile:
outfile.write(response.text)
|
// ... existing code ...
import requests, sys, os
import lxml.etree
// ... modified code ...
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml'
...
# Save the XML file
with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile:
outfile.write(response.text)
// ... rest of the code ...
|
2bcc941b015c443c64f08a13012e8caf70028754
|
ideascube/search/migrations/0001_initial.py
|
ideascube/search/migrations/0001_initial.py
|
from __future__ import unicode_literals
from django.db import migrations, models
import ideascube.search.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Search',
fields=[
('rowid', models.IntegerField(serialize=False, primary_key=True)),
('model', models.CharField(max_length=64)),
('model_id', models.IntegerField()),
('public', models.BooleanField(default=True)),
('text', ideascube.search.models.SearchField()),
],
options={
'db_table': 'idx',
'managed': False,
},
),
]
|
from __future__ import unicode_literals
from django.db import migrations
from ideascube.search.utils import create_index_table
class CreateSearchModel(migrations.CreateModel):
def database_forwards(self, *_):
# Don't run the parent method, we create the table our own way
create_index_table()
class Migration(migrations.Migration):
dependencies = [
]
operations = [
CreateSearchModel(
name='Search',
fields=[],
options={
'db_table': 'idx',
'managed': False,
},
),
]
|
Fix the initial search migration
|
Fix the initial search migration
There is no point in creating the model in this way, that's just not how
it's used: instead we want to use the FTS4 extension from SQLite.
|
Python
|
agpl-3.0
|
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
|
from __future__ import unicode_literals
- from django.db import migrations, models
+ from django.db import migrations
- import ideascube.search.models
+ from ideascube.search.utils import create_index_table
+
+
+ class CreateSearchModel(migrations.CreateModel):
+ def database_forwards(self, *_):
+ # Don't run the parent method, we create the table our own way
+ create_index_table()
class Migration(migrations.Migration):
dependencies = [
]
operations = [
- migrations.CreateModel(
+ CreateSearchModel(
name='Search',
- fields=[
+ fields=[],
- ('rowid', models.IntegerField(serialize=False, primary_key=True)),
- ('model', models.CharField(max_length=64)),
- ('model_id', models.IntegerField()),
- ('public', models.BooleanField(default=True)),
- ('text', ideascube.search.models.SearchField()),
- ],
options={
'db_table': 'idx',
'managed': False,
},
),
]
|
Fix the initial search migration
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
import ideascube.search.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Search',
fields=[
('rowid', models.IntegerField(serialize=False, primary_key=True)),
('model', models.CharField(max_length=64)),
('model_id', models.IntegerField()),
('public', models.BooleanField(default=True)),
('text', ideascube.search.models.SearchField()),
],
options={
'db_table': 'idx',
'managed': False,
},
),
]
## Instruction:
Fix the initial search migration
## Code After:
from __future__ import unicode_literals
from django.db import migrations
from ideascube.search.utils import create_index_table
class CreateSearchModel(migrations.CreateModel):
def database_forwards(self, *_):
# Don't run the parent method, we create the table our own way
create_index_table()
class Migration(migrations.Migration):
dependencies = [
]
operations = [
CreateSearchModel(
name='Search',
fields=[],
options={
'db_table': 'idx',
'managed': False,
},
),
]
|
...
from django.db import migrations
from ideascube.search.utils import create_index_table
class CreateSearchModel(migrations.CreateModel):
def database_forwards(self, *_):
# Don't run the parent method, we create the table our own way
create_index_table()
...
operations = [
CreateSearchModel(
name='Search',
fields=[],
options={
...
|
49a7968e51ce850428936fb2fc66c905ce8b8998
|
head1stpython/Chapter3/sketch.py
|
head1stpython/Chapter3/sketch.py
|
import os
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Change path for the current directory
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end = '')
print(' said: ', end = '')
print(line_spoken, end = '')
except:
pass
data.close()
|
import os
#Change path for the current directory
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Check if file exists
if os.path.exists('sketch.txt'):
#Load the text file into 'data' variable
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
#We use try/except to handle errors that can occur with bad input
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end = '')
print(' said: ', end = '')
print(line_spoken, end = '')
except:
pass
#After all the iteration and printing, we close the file
data.close()
#If file does exists, we simply quit and display an error for the user/dev
else:
print('The data file is missing!')
|
Validate if the file exists (if/else)
|
Validate if the file exists (if/else)
|
Python
|
unlicense
|
israelzuniga/python-octo-wookie
|
import os
+ #Change path for the current directory
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
- #Change path for the current directory
+ #Check if file exists
+ if os.path.exists('sketch.txt'):
+
+ #Load the text file into 'data' variable
- data = open('sketch.txt')
+ data = open('sketch.txt')
+ #Start iteration over the text file
+ for each_line in data:
+ #We use try/except to handle errors that can occur with bad input
+ try:
+ (role, line_spoken) = each_line.split(':', 1)
+ print(role, end = '')
+ print(' said: ', end = '')
+ print(line_spoken, end = '')
+ except:
+ pass
+ #After all the iteration and printing, we close the file
+ data.close()
- #Start iteration over the text file
- for each_line in data:
- try:
- (role, line_spoken) = each_line.split(':', 1)
- print(role, end = '')
- print(' said: ', end = '')
- print(line_spoken, end = '')
- except:
- pass
- data.close()
+ #If file does exists, we simply quit and display an error for the user/dev
+ else:
+ print('The data file is missing!')
|
Validate if the file exists (if/else)
|
## Code Before:
import os
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Change path for the current directory
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end = '')
print(' said: ', end = '')
print(line_spoken, end = '')
except:
pass
data.close()
## Instruction:
Validate if the file exists (if/else)
## Code After:
import os
#Change path for the current directory
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Check if file exists
if os.path.exists('sketch.txt'):
#Load the text file into 'data' variable
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
#We use try/except to handle errors that can occur with bad input
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end = '')
print(' said: ', end = '')
print(line_spoken, end = '')
except:
pass
#After all the iteration and printing, we close the file
data.close()
#If file does exists, we simply quit and display an error for the user/dev
else:
print('The data file is missing!')
|
// ... existing code ...
#Change path for the current directory
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Check if file exists
if os.path.exists('sketch.txt'):
#Load the text file into 'data' variable
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
#We use try/except to handle errors that can occur with bad input
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end = '')
print(' said: ', end = '')
print(line_spoken, end = '')
except:
pass
#After all the iteration and printing, we close the file
data.close()
#If file does exists, we simply quit and display an error for the user/dev
else:
print('The data file is missing!')
// ... rest of the code ...
|
082076cce996593c9959fc0743f13b62d2e4842b
|
chared/__init__.py
|
chared/__init__.py
|
try:
__version__ = 'v' + __import__('pkg_resources').get_distribution('chared').version
except:
__version__ = 'r$Rev$'
|
try:
__version__ = 'v' + __import__('pkg_resources').get_distribution('chared').version
except:
import re
__version__ = re.sub('.*(\d+).*', r'rev\1', '$Rev$')
|
Make sure the version is displayed as r<revision number> if the information about the package version is not available.
|
Make sure the version is displayed as r<revision number> if the information about the package version is not available.
|
Python
|
bsd-2-clause
|
gilesbrown/chared,xmichelf/chared
|
try:
__version__ = 'v' + __import__('pkg_resources').get_distribution('chared').version
except:
- __version__ = 'r$Rev$'
+ import re
+ __version__ = re.sub('.*(\d+).*', r'rev\1', '$Rev$')
|
Make sure the version is displayed as r<revision number> if the information about the package version is not available.
|
## Code Before:
try:
__version__ = 'v' + __import__('pkg_resources').get_distribution('chared').version
except:
__version__ = 'r$Rev$'
## Instruction:
Make sure the version is displayed as r<revision number> if the information about the package version is not available.
## Code After:
try:
__version__ = 'v' + __import__('pkg_resources').get_distribution('chared').version
except:
import re
__version__ = re.sub('.*(\d+).*', r'rev\1', '$Rev$')
|
# ... existing code ...
except:
import re
__version__ = re.sub('.*(\d+).*', r'rev\1', '$Rev$')
# ... rest of the code ...
|
4719401819a877ceebfcc49f1084fb01395a3f4d
|
nyuki/bus/persistence/mongo_backend.py
|
nyuki/bus/persistence/mongo_backend.py
|
from datetime import datetime
import logging
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import AutoReconnect
log = logging.getLogger(__name__)
class MongoBackend(object):
def __init__(self, name):
self.name = name
self.host = None
self._collection = None
async def init(self, host, ttl=60):
self.host = host
# Get collection for this nyuki
client = AsyncIOMotorClient(host)
db = client['bus_persistence']
self._collection = db[self.name]
# Set a TTL to the documents in this collection
try:
await self._collection.create_index(
'created_at', expireAfterSeconds=ttl*60
)
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
async def store(self, topic, message):
await self._collection.insert({
'created_at': datetime.utcnow(),
'topic': str(topic),
'message': message
})
async def retrieve(self, since=None):
if since:
cursor = self._collection.find({'created_at': {'$gte': since}})
else:
cursor = self._collection.find()
cursor.sort('created_at')
return await cursor.to_list(None)
|
from datetime import datetime
import logging
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import AutoReconnect
log = logging.getLogger(__name__)
class MongoBackend(object):
def __init__(self, name):
self.name = name
self.host = None
self._collection = None
async def init(self, host, ttl=60):
self.host = host
# Get collection for this nyuki
client = AsyncIOMotorClient(host)
db = client['bus_persistence']
self._collection = db[self.name]
# Set a TTL to the documents in this collection
try:
await self._collection.create_index(
'created_at', expireAfterSeconds=ttl*60
)
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
async def store(self, topic, message):
try:
await self._collection.insert({
'created_at': datetime.utcnow(),
'topic': str(topic),
'message': message
})
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
async def retrieve(self, since=None):
if since:
cursor = self._collection.find({'created_at': {'$gte': since}})
else:
cursor = self._collection.find()
cursor.sort('created_at')
try:
return await cursor.to_list(None)
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
|
Add failsafe mongo calls
|
Add failsafe mongo calls [ci skip]
|
Python
|
apache-2.0
|
optiflows/nyuki,gdraynz/nyuki,gdraynz/nyuki,optiflows/nyuki
|
from datetime import datetime
import logging
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import AutoReconnect
log = logging.getLogger(__name__)
class MongoBackend(object):
def __init__(self, name):
self.name = name
self.host = None
self._collection = None
async def init(self, host, ttl=60):
self.host = host
# Get collection for this nyuki
client = AsyncIOMotorClient(host)
db = client['bus_persistence']
self._collection = db[self.name]
# Set a TTL to the documents in this collection
try:
await self._collection.create_index(
'created_at', expireAfterSeconds=ttl*60
)
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
async def store(self, topic, message):
+ try:
- await self._collection.insert({
+ await self._collection.insert({
- 'created_at': datetime.utcnow(),
+ 'created_at': datetime.utcnow(),
- 'topic': str(topic),
+ 'topic': str(topic),
- 'message': message
+ 'message': message
- })
+ })
+ except AutoReconnect:
+ log.error("Could not reach mongo at address '%s'", self.host)
async def retrieve(self, since=None):
if since:
cursor = self._collection.find({'created_at': {'$gte': since}})
else:
cursor = self._collection.find()
cursor.sort('created_at')
- return await cursor.to_list(None)
+ try:
+ return await cursor.to_list(None)
+ except AutoReconnect:
+ log.error("Could not reach mongo at address '%s'", self.host)
+
|
Add failsafe mongo calls
|
## Code Before:
from datetime import datetime
import logging
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import AutoReconnect
log = logging.getLogger(__name__)
class MongoBackend(object):
def __init__(self, name):
self.name = name
self.host = None
self._collection = None
async def init(self, host, ttl=60):
self.host = host
# Get collection for this nyuki
client = AsyncIOMotorClient(host)
db = client['bus_persistence']
self._collection = db[self.name]
# Set a TTL to the documents in this collection
try:
await self._collection.create_index(
'created_at', expireAfterSeconds=ttl*60
)
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
async def store(self, topic, message):
await self._collection.insert({
'created_at': datetime.utcnow(),
'topic': str(topic),
'message': message
})
async def retrieve(self, since=None):
if since:
cursor = self._collection.find({'created_at': {'$gte': since}})
else:
cursor = self._collection.find()
cursor.sort('created_at')
return await cursor.to_list(None)
## Instruction:
Add failsafe mongo calls
## Code After:
from datetime import datetime
import logging
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import AutoReconnect
log = logging.getLogger(__name__)
class MongoBackend(object):
def __init__(self, name):
self.name = name
self.host = None
self._collection = None
async def init(self, host, ttl=60):
self.host = host
# Get collection for this nyuki
client = AsyncIOMotorClient(host)
db = client['bus_persistence']
self._collection = db[self.name]
# Set a TTL to the documents in this collection
try:
await self._collection.create_index(
'created_at', expireAfterSeconds=ttl*60
)
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
async def store(self, topic, message):
try:
await self._collection.insert({
'created_at': datetime.utcnow(),
'topic': str(topic),
'message': message
})
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
async def retrieve(self, since=None):
if since:
cursor = self._collection.find({'created_at': {'$gte': since}})
else:
cursor = self._collection.find()
cursor.sort('created_at')
try:
return await cursor.to_list(None)
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
|
...
async def store(self, topic, message):
try:
await self._collection.insert({
'created_at': datetime.utcnow(),
'topic': str(topic),
'message': message
})
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
...
cursor.sort('created_at')
try:
return await cursor.to_list(None)
except AutoReconnect:
log.error("Could not reach mongo at address '%s'", self.host)
...
|
fa991297168f216c208d53b880124a4f23250034
|
setup.py
|
setup.py
|
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
|
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"gzip",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
|
Add gzip to cx-freeze packages
|
Add gzip to cx-freeze packages
|
Python
|
mit
|
virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool
|
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
+ "gzip",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
|
Add gzip to cx-freeze packages
|
## Code Before:
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
## Instruction:
Add gzip to cx-freeze packages
## Code After:
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"gzip",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
|
...
"cffi",
"gzip",
"idna",
...
|
8fd5c5c8c7aec1cc045f7f2fcbecb16be129c19b
|
jobs/templatetags/jobs_tags.py
|
jobs/templatetags/jobs_tags.py
|
from django import template
from django.db.models import ObjectDoesNotExist
from jobs.models import JobPostingListPage
register = template.Library()
@register.simple_tag(takes_context=True)
def get_active_posting_page(context):
try:
root = context['page'].get_root()
listing_pages = JobPostingListPage.objects.descendant_of(root)
if listing_pages.count() > 0:
listing_page = listing_pages[0]
if listing_page.subpages.count() > 0:
if listing_page.subpages.count() == 1:
return listing_page.subpages[0]
return listing_page
return None
except ObjectDoesNotExist:
return None
|
from django import template
from django.db.models import ObjectDoesNotExist
from jobs.models import JobPostingListPage
register = template.Library()
@register.simple_tag(takes_context=True)
def get_active_posting_page(context):
if 'page' not in context:
return None
try:
root = context['page'].get_root()
listing_pages = JobPostingListPage.objects.descendant_of(root)
if listing_pages.count() > 0:
listing_page = listing_pages[0]
if listing_page.subpages.count() > 0:
if listing_page.subpages.count() == 1:
return listing_page.subpages[0]
return listing_page
return None
except ObjectDoesNotExist:
return None
|
Add fix for non pages like search.
|
Add fix for non pages like search.
|
Python
|
mit
|
OpenCanada/website,OpenCanada/website,OpenCanada/website,OpenCanada/website
|
from django import template
from django.db.models import ObjectDoesNotExist
from jobs.models import JobPostingListPage
register = template.Library()
@register.simple_tag(takes_context=True)
def get_active_posting_page(context):
+ if 'page' not in context:
+ return None
+
try:
root = context['page'].get_root()
listing_pages = JobPostingListPage.objects.descendant_of(root)
if listing_pages.count() > 0:
listing_page = listing_pages[0]
if listing_page.subpages.count() > 0:
if listing_page.subpages.count() == 1:
return listing_page.subpages[0]
return listing_page
return None
except ObjectDoesNotExist:
return None
|
Add fix for non pages like search.
|
## Code Before:
from django import template
from django.db.models import ObjectDoesNotExist
from jobs.models import JobPostingListPage
register = template.Library()
@register.simple_tag(takes_context=True)
def get_active_posting_page(context):
try:
root = context['page'].get_root()
listing_pages = JobPostingListPage.objects.descendant_of(root)
if listing_pages.count() > 0:
listing_page = listing_pages[0]
if listing_page.subpages.count() > 0:
if listing_page.subpages.count() == 1:
return listing_page.subpages[0]
return listing_page
return None
except ObjectDoesNotExist:
return None
## Instruction:
Add fix for non pages like search.
## Code After:
from django import template
from django.db.models import ObjectDoesNotExist
from jobs.models import JobPostingListPage
register = template.Library()
@register.simple_tag(takes_context=True)
def get_active_posting_page(context):
if 'page' not in context:
return None
try:
root = context['page'].get_root()
listing_pages = JobPostingListPage.objects.descendant_of(root)
if listing_pages.count() > 0:
listing_page = listing_pages[0]
if listing_page.subpages.count() > 0:
if listing_page.subpages.count() == 1:
return listing_page.subpages[0]
return listing_page
return None
except ObjectDoesNotExist:
return None
|
...
def get_active_posting_page(context):
if 'page' not in context:
return None
try:
...
|
7d10b9d803089d1cf8a0c06219608d31bf5fb84f
|
src/collectors/MongoDBCollector/MongoDBCollector.py
|
src/collectors/MongoDBCollector/MongoDBCollector.py
|
try:
from numbers import Number
import pymongo
except ImportError:
Number = None
import diamond
class MongoDBCollector(diamond.collector.Collector):
"""Collects data from MongoDB's db.serverStatus() command
Collects all number values from the db.serverStatus() command, other
values are ignored.
"""
def get_default_config(self):
"""
Returns the default collector settings
"""
return {
'path': 'mongo',
'host': 'localhost'
}
def collect(self):
"""Collect number values from db.serverStatus()"""
if Number is None:
self.log.error('Unable to import either Number or pymongo')
return {}
conn = pymongo.Connection(self.config['host'],slave_okay=True)
data = conn.db.command('serverStatus')
for key in data:
self._publish_metrics([], key, data)
def _publish_metrics(self, prev_keys, key, data):
"""Recursively publish keys"""
value = data[key]
keys = prev_keys + [key]
if isinstance(value, dict):
for new_key in value:
self._publish_metrics(keys, new_key, value)
elif isinstance(value, Number):
self.publish('.'.join(keys), value)
|
try:
from numbers import Number
import pymongo
from pymongo import ReadPreference
except ImportError:
Number = None
import diamond
class MongoDBCollector(diamond.collector.Collector):
"""Collects data from MongoDB's db.serverStatus() command
Collects all number values from the db.serverStatus() command, other
values are ignored.
"""
def get_default_config(self):
"""
Returns the default collector settings
"""
return {
'path': 'mongo',
'host': 'localhost'
}
def collect(self):
"""Collect number values from db.serverStatus()"""
if Number is None:
self.log.error('Unable to import either Number or pymongo')
return {}
conn = pymongo.Connection(self.config['host'],read_preference=ReadPreference.SECONDARY)
data = conn.db.command('serverStatus')
for key in data:
self._publish_metrics([], key, data)
def _publish_metrics(self, prev_keys, key, data):
"""Recursively publish keys"""
value = data[key]
keys = prev_keys + [key]
if isinstance(value, dict):
for new_key in value:
self._publish_metrics(keys, new_key, value)
elif isinstance(value, Number):
self.publish('.'.join(keys), value)
|
Replace deprecated slave_ok for read_preference in pymongo.Connection
|
Replace deprecated slave_ok for read_preference in pymongo.Connection
See: http://api.mongodb.org/python/current/api/pymongo/connection.html
|
Python
|
mit
|
jriguera/Diamond,MichaelDoyle/Diamond,Netuitive/netuitive-diamond,hamelg/Diamond,dcsquared13/Diamond,sebbrandt87/Diamond,python-diamond/Diamond,gg7/diamond,sebbrandt87/Diamond,actmd/Diamond,signalfx/Diamond,Basis/Diamond,bmhatfield/Diamond,python-diamond/Diamond,krbaker/Diamond,jumping/Diamond,signalfx/Diamond,rtoma/Diamond,datafiniti/Diamond,CYBERBUGJR/Diamond,metamx/Diamond,ramjothikumar/Diamond,Clever/Diamond,dcsquared13/Diamond,socialwareinc/Diamond,jumping/Diamond,szibis/Diamond,zoidbergwill/Diamond,Ssawa/Diamond,h00dy/Diamond,tellapart/Diamond,janisz/Diamond-1,MichaelDoyle/Diamond,EzyInsights/Diamond,works-mobile/Diamond,thardie/Diamond,Netuitive/netuitive-diamond,codepython/Diamond,Netuitive/netuitive-diamond,MediaMath/Diamond,cannium/Diamond,hvnsweeting/Diamond,MediaMath/Diamond,Ssawa/Diamond,jumping/Diamond,skbkontur/Diamond,eMerzh/Diamond-1,anandbhoraskar/Diamond,krbaker/Diamond,acquia/Diamond,Precis/Diamond,gg7/diamond,cannium/Diamond,tusharmakkar08/Diamond,stuartbfox/Diamond,skbkontur/Diamond,zoidbergwill/Diamond,Slach/Diamond,actmd/Diamond,mzupan/Diamond,socialwareinc/Diamond,janisz/Diamond-1,MichaelDoyle/Diamond,eMerzh/Diamond-1,thardie/Diamond,jaingaurav/Diamond,h00dy/Diamond,saucelabs/Diamond,EzyInsights/Diamond,skbkontur/Diamond,Nihn/Diamond-1,Ormod/Diamond,TinLe/Diamond,Netuitive/netuitive-diamond,jaingaurav/Diamond,Netuitive/Diamond,Slach/Diamond,Netuitive/Diamond,ceph/Diamond,mzupan/Diamond,mzupan/Diamond,tusharmakkar08/Diamond,tellapart/Diamond,hamelg/Diamond,CYBERBUGJR/Diamond,Netuitive/Diamond,rtoma/Diamond,Ormod/Diamond,Ensighten/Diamond,bmhatfield/Diamond,cannium/Diamond,skbkontur/Diamond,cannium/Diamond,acquia/Diamond,Slach/Diamond,Ensighten/Diamond,bmhatfield/Diamond,jumping/Diamond,joel-airspring/Diamond,dcsquared13/Diamond,Basis/Diamond,Ssawa/Diamond,Precis/Diamond,tuenti/Diamond,ramjothikumar/Diamond,MichaelDoyle/Diamond,Ormod/Diamond,russss/Diamond,szibis/Diamond,works-mobile/Diamond,hamelg/Diamond,CYBERBUGJR/Diamond,russss/Diamond,tellapart/Diamond,anandbhoraskar/Diamond,gg7/diamond,timchenxiaoyu/Diamond,Precis/Diamond,zoidbergwill/Diamond,TAKEALOT/Diamond,codepython/Diamond,Netuitive/Diamond,signalfx/Diamond,Precis/Diamond,works-mobile/Diamond,russss/Diamond,h00dy/Diamond,timchenxiaoyu/Diamond,TinLe/Diamond,szibis/Diamond,jaingaurav/Diamond,TAKEALOT/Diamond,stuartbfox/Diamond,datafiniti/Diamond,saucelabs/Diamond,tellapart/Diamond,jriguera/Diamond,saucelabs/Diamond,Ensighten/Diamond,python-diamond/Diamond,disqus/Diamond,hamelg/Diamond,datafiniti/Diamond,tuenti/Diamond,datafiniti/Diamond,mfriedenhagen/Diamond,timchenxiaoyu/Diamond,Basis/Diamond,acquia/Diamond,mfriedenhagen/Diamond,eMerzh/Diamond-1,EzyInsights/Diamond,TAKEALOT/Diamond,dcsquared13/Diamond,anandbhoraskar/Diamond,saucelabs/Diamond,ceph/Diamond,EzyInsights/Diamond,joel-airspring/Diamond,metamx/Diamond,actmd/Diamond,TinLe/Diamond,krbaker/Diamond,jaingaurav/Diamond,MediaMath/Diamond,ceph/Diamond,disqus/Diamond,anandbhoraskar/Diamond,socialwareinc/Diamond,hvnsweeting/Diamond,jriguera/Diamond,tusharmakkar08/Diamond,rtoma/Diamond,bmhatfield/Diamond,tuenti/Diamond,Basis/Diamond,joel-airspring/Diamond,acquia/Diamond,works-mobile/Diamond,janisz/Diamond-1,Nihn/Diamond-1,thardie/Diamond,tusharmakkar08/Diamond,ceph/Diamond,russss/Diamond,jriguera/Diamond,Ormod/Diamond,codepython/Diamond,socialwareinc/Diamond,Clever/Diamond,tuenti/Diamond,Clever/Diamond,ramjothikumar/Diamond,thardie/Diamond,CYBERBUGJR/Diamond,sebbrandt87/Diamond,Nihn/Diamond-1,Nihn/Diamond-1,codepython/Diamond,stuartbfox/Diamond,TAKEALOT/Diamond,szibis/Diamond,actmd/Diamond,gg7/diamond,mfriedenhagen/Diamond,joel-airspring/Diamond,timchenxiaoyu/Diamond,h00dy/Diamond,stuartbfox/Diamond,disqus/Diamond,sebbrandt87/Diamond,MediaMath/Diamond,metamx/Diamond,signalfx/Diamond,Clever/Diamond,krbaker/Diamond,ramjothikumar/Diamond,Ensighten/Diamond,mfriedenhagen/Diamond,eMerzh/Diamond-1,hvnsweeting/Diamond,mzupan/Diamond,TinLe/Diamond,hvnsweeting/Diamond,Ssawa/Diamond,janisz/Diamond-1,Slach/Diamond,zoidbergwill/Diamond,rtoma/Diamond
|
try:
from numbers import Number
import pymongo
+ from pymongo import ReadPreference
except ImportError:
Number = None
import diamond
class MongoDBCollector(diamond.collector.Collector):
"""Collects data from MongoDB's db.serverStatus() command
Collects all number values from the db.serverStatus() command, other
values are ignored.
"""
def get_default_config(self):
"""
Returns the default collector settings
"""
return {
'path': 'mongo',
'host': 'localhost'
}
def collect(self):
"""Collect number values from db.serverStatus()"""
if Number is None:
self.log.error('Unable to import either Number or pymongo')
return {}
- conn = pymongo.Connection(self.config['host'],slave_okay=True)
+ conn = pymongo.Connection(self.config['host'],read_preference=ReadPreference.SECONDARY)
data = conn.db.command('serverStatus')
for key in data:
self._publish_metrics([], key, data)
def _publish_metrics(self, prev_keys, key, data):
"""Recursively publish keys"""
value = data[key]
keys = prev_keys + [key]
if isinstance(value, dict):
for new_key in value:
self._publish_metrics(keys, new_key, value)
elif isinstance(value, Number):
self.publish('.'.join(keys), value)
|
Replace deprecated slave_ok for read_preference in pymongo.Connection
|
## Code Before:
try:
from numbers import Number
import pymongo
except ImportError:
Number = None
import diamond
class MongoDBCollector(diamond.collector.Collector):
"""Collects data from MongoDB's db.serverStatus() command
Collects all number values from the db.serverStatus() command, other
values are ignored.
"""
def get_default_config(self):
"""
Returns the default collector settings
"""
return {
'path': 'mongo',
'host': 'localhost'
}
def collect(self):
"""Collect number values from db.serverStatus()"""
if Number is None:
self.log.error('Unable to import either Number or pymongo')
return {}
conn = pymongo.Connection(self.config['host'],slave_okay=True)
data = conn.db.command('serverStatus')
for key in data:
self._publish_metrics([], key, data)
def _publish_metrics(self, prev_keys, key, data):
"""Recursively publish keys"""
value = data[key]
keys = prev_keys + [key]
if isinstance(value, dict):
for new_key in value:
self._publish_metrics(keys, new_key, value)
elif isinstance(value, Number):
self.publish('.'.join(keys), value)
## Instruction:
Replace deprecated slave_ok for read_preference in pymongo.Connection
## Code After:
try:
from numbers import Number
import pymongo
from pymongo import ReadPreference
except ImportError:
Number = None
import diamond
class MongoDBCollector(diamond.collector.Collector):
"""Collects data from MongoDB's db.serverStatus() command
Collects all number values from the db.serverStatus() command, other
values are ignored.
"""
def get_default_config(self):
"""
Returns the default collector settings
"""
return {
'path': 'mongo',
'host': 'localhost'
}
def collect(self):
"""Collect number values from db.serverStatus()"""
if Number is None:
self.log.error('Unable to import either Number or pymongo')
return {}
conn = pymongo.Connection(self.config['host'],read_preference=ReadPreference.SECONDARY)
data = conn.db.command('serverStatus')
for key in data:
self._publish_metrics([], key, data)
def _publish_metrics(self, prev_keys, key, data):
"""Recursively publish keys"""
value = data[key]
keys = prev_keys + [key]
if isinstance(value, dict):
for new_key in value:
self._publish_metrics(keys, new_key, value)
elif isinstance(value, Number):
self.publish('.'.join(keys), value)
|
// ... existing code ...
import pymongo
from pymongo import ReadPreference
except ImportError:
// ... modified code ...
conn = pymongo.Connection(self.config['host'],read_preference=ReadPreference.SECONDARY)
data = conn.db.command('serverStatus')
// ... rest of the code ...
|
620bf504292583b2547cf7489eeeaaa582ddad77
|
indra/tests/test_ctd.py
|
indra/tests/test_ctd.py
|
import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 4, cp.statements
|
import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 3, cp.statements
assert isinstance(cp.statements[0], Dephosphorylation)
assert cp.statements[0].enz.name == 'wortmannin'
assert isinstance(cp.statements[1], Dephosphorylation)
assert cp.statements[1].enz.name == 'YM-254890'
assert isinstance(cp.statements[2], Phosphorylation)
assert cp.statements[2].enz.name == 'zinc atom'
|
Fix and extend test conditions
|
Fix and extend test conditions
|
Python
|
bsd-2-clause
|
sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra,bgyori/indra,sorgerlab/belpy
|
import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
- assert len(cp.statements) == 4, cp.statements
+ assert len(cp.statements) == 3, cp.statements
+ assert isinstance(cp.statements[0], Dephosphorylation)
+ assert cp.statements[0].enz.name == 'wortmannin'
+ assert isinstance(cp.statements[1], Dephosphorylation)
+ assert cp.statements[1].enz.name == 'YM-254890'
+ assert isinstance(cp.statements[2], Phosphorylation)
+ assert cp.statements[2].enz.name == 'zinc atom'
|
Fix and extend test conditions
|
## Code Before:
import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 4, cp.statements
## Instruction:
Fix and extend test conditions
## Code After:
import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 3, cp.statements
assert isinstance(cp.statements[0], Dephosphorylation)
assert cp.statements[0].enz.name == 'wortmannin'
assert isinstance(cp.statements[1], Dephosphorylation)
assert cp.statements[1].enz.name == 'YM-254890'
assert isinstance(cp.statements[2], Phosphorylation)
assert cp.statements[2].enz.name == 'zinc atom'
|
...
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 3, cp.statements
assert isinstance(cp.statements[0], Dephosphorylation)
assert cp.statements[0].enz.name == 'wortmannin'
assert isinstance(cp.statements[1], Dephosphorylation)
assert cp.statements[1].enz.name == 'YM-254890'
assert isinstance(cp.statements[2], Phosphorylation)
assert cp.statements[2].enz.name == 'zinc atom'
...
|
dd0405965f816a2a71bfb6d7a3f939691a6ab6d8
|
ibmcnx/doc/DataSources.py
|
ibmcnx/doc/DataSources.py
|
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dsidlist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dsidlist.append(str(db).replace('"',''))
n += 1
dsidlist.sort()
for dsid in dsidlist:
print "AdminConfig.list( dsid ): "
AdminConfig.showAttribute(dsid,"propertySet")
|
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dsidlist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dsidlist.append(str(db).replace('"',''))
n += 1
dsidlist.sort()
for dsid in dsidlist:
propertySet = AdminConfig.showAttribute(dsid,"propertySet")
propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()
|
Create documentation of DataSource Settings
|
8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
|
Python
|
apache-2.0
|
stoeps13/ibmcnx2,stoeps13/ibmcnx2
|
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dsidlist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dsidlist.append(str(db).replace('"',''))
n += 1
dsidlist.sort()
for dsid in dsidlist:
- print "AdminConfig.list( dsid ): "
- AdminConfig.showAttribute(dsid,"propertySet")
+ propertySet = AdminConfig.showAttribute(dsid,"propertySet")
+ propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()
|
Create documentation of DataSource Settings
|
## Code Before:
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dsidlist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dsidlist.append(str(db).replace('"',''))
n += 1
dsidlist.sort()
for dsid in dsidlist:
print "AdminConfig.list( dsid ): "
AdminConfig.showAttribute(dsid,"propertySet")
## Instruction:
Create documentation of DataSource Settings
## Code After:
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dsidlist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dsidlist.append(str(db).replace('"',''))
n += 1
dsidlist.sort()
for dsid in dsidlist:
propertySet = AdminConfig.showAttribute(dsid,"propertySet")
propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()
|
...
for dsid in dsidlist:
propertySet = AdminConfig.showAttribute(dsid,"propertySet")
propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()
...
|
c28ae7e4b0637a2c4db120d9add13d5589ddca40
|
runtests.py
|
runtests.py
|
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
try:
django.setup()
except AttributeError: # 1.6 or lower
pass
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
Remove compat shim as it doesn't apply
|
Remove compat shim as it doesn't apply
|
Python
|
mit
|
sergei-maertens/django-systemjs,sergei-maertens/django-systemjs,sergei-maertens/django-systemjs,sergei-maertens/django-systemjs
|
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
- try:
- django.setup()
+ django.setup()
- except AttributeError: # 1.6 or lower
- pass
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
Remove compat shim as it doesn't apply
|
## Code Before:
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
try:
django.setup()
except AttributeError: # 1.6 or lower
pass
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
## Instruction:
Remove compat shim as it doesn't apply
## Code After:
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
// ... existing code ...
django.setup()
// ... rest of the code ...
|
8fa1cae882c0ff020c0b9c3c2fac9e4248d46ce4
|
deploy/common/sqlite_wrapper.py
|
deploy/common/sqlite_wrapper.py
|
import sqlite3
class SQLiteWrapper:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cursor = self.conn.cursor()
self.cursor.execute("PRAGMA cache_size=-16000")
self.cursor.execute("PRAGMA synchronous=OFF")
self.conn.commit()
def query(self, sql, params=None, iterator=False, fetch_one=False, multi=False, many_rows=None):
try:
with self.conn as conn:
cursor = conn.cursor()
if many_rows:
cursor.executemany(sql, many_rows)
return
if multi:
cursor.executescript(sql)
if params is None and not multi:
cursor.execute(sql)
if params and not multi:
cursor.execute(sql, params)
if iterator:
return cursor
if fetch_one:
return cursor.fetchone()[0]
if not multi:
return cursor.fetchall()
except Exception as e:
raise Exception('Error in executing query ' + sql + ': ' + format(e))
def close(self):
self.conn.close()
|
import sqlite3
class SQLiteWrapper:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cursor = self.conn.cursor()
self.cursor.execute("PRAGMA page_size=4096")
self.cursor.execute("PRAGMA cache_size=-16000")
self.cursor.execute("PRAGMA synchronous=NORMAL")
self.conn.commit()
def query(self, sql, params=None, iterator=False, fetch_one=False, multi=False, many_rows=None):
try:
with self.conn as conn:
cursor = conn.cursor()
if many_rows:
cursor.executemany(sql, many_rows)
return
if multi:
cursor.executescript(sql)
if params is None and not multi:
cursor.execute(sql)
if params and not multi:
cursor.execute(sql, params)
if iterator:
return cursor
if fetch_one:
return cursor.fetchone()[0]
if not multi:
return cursor.fetchall()
except Exception as e:
raise Exception('Error in executing query ' + sql + ': ' + format(e))
def close(self):
self.conn.close()
|
Use PRAGMA synchronous=NORMAL instead of OFF, and set page_size to 4096.
|
Use PRAGMA synchronous=NORMAL instead of OFF, and set page_size to 4096.
|
Python
|
mit
|
mikispag/bitiodine
|
import sqlite3
class SQLiteWrapper:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cursor = self.conn.cursor()
+ self.cursor.execute("PRAGMA page_size=4096")
self.cursor.execute("PRAGMA cache_size=-16000")
- self.cursor.execute("PRAGMA synchronous=OFF")
+ self.cursor.execute("PRAGMA synchronous=NORMAL")
self.conn.commit()
def query(self, sql, params=None, iterator=False, fetch_one=False, multi=False, many_rows=None):
try:
with self.conn as conn:
cursor = conn.cursor()
if many_rows:
cursor.executemany(sql, many_rows)
return
if multi:
cursor.executescript(sql)
if params is None and not multi:
cursor.execute(sql)
if params and not multi:
cursor.execute(sql, params)
if iterator:
return cursor
if fetch_one:
return cursor.fetchone()[0]
if not multi:
return cursor.fetchall()
except Exception as e:
raise Exception('Error in executing query ' + sql + ': ' + format(e))
def close(self):
self.conn.close()
|
Use PRAGMA synchronous=NORMAL instead of OFF, and set page_size to 4096.
|
## Code Before:
import sqlite3
class SQLiteWrapper:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cursor = self.conn.cursor()
self.cursor.execute("PRAGMA cache_size=-16000")
self.cursor.execute("PRAGMA synchronous=OFF")
self.conn.commit()
def query(self, sql, params=None, iterator=False, fetch_one=False, multi=False, many_rows=None):
try:
with self.conn as conn:
cursor = conn.cursor()
if many_rows:
cursor.executemany(sql, many_rows)
return
if multi:
cursor.executescript(sql)
if params is None and not multi:
cursor.execute(sql)
if params and not multi:
cursor.execute(sql, params)
if iterator:
return cursor
if fetch_one:
return cursor.fetchone()[0]
if not multi:
return cursor.fetchall()
except Exception as e:
raise Exception('Error in executing query ' + sql + ': ' + format(e))
def close(self):
self.conn.close()
## Instruction:
Use PRAGMA synchronous=NORMAL instead of OFF, and set page_size to 4096.
## Code After:
import sqlite3
class SQLiteWrapper:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.cursor = self.conn.cursor()
self.cursor.execute("PRAGMA page_size=4096")
self.cursor.execute("PRAGMA cache_size=-16000")
self.cursor.execute("PRAGMA synchronous=NORMAL")
self.conn.commit()
def query(self, sql, params=None, iterator=False, fetch_one=False, multi=False, many_rows=None):
try:
with self.conn as conn:
cursor = conn.cursor()
if many_rows:
cursor.executemany(sql, many_rows)
return
if multi:
cursor.executescript(sql)
if params is None and not multi:
cursor.execute(sql)
if params and not multi:
cursor.execute(sql, params)
if iterator:
return cursor
if fetch_one:
return cursor.fetchone()[0]
if not multi:
return cursor.fetchall()
except Exception as e:
raise Exception('Error in executing query ' + sql + ': ' + format(e))
def close(self):
self.conn.close()
|
# ... existing code ...
self.cursor = self.conn.cursor()
self.cursor.execute("PRAGMA page_size=4096")
self.cursor.execute("PRAGMA cache_size=-16000")
self.cursor.execute("PRAGMA synchronous=NORMAL")
self.conn.commit()
# ... rest of the code ...
|
7ef053749f4bfbcf7c2007a57d16139cfea09588
|
jsonapi_requests/configuration.py
|
jsonapi_requests/configuration.py
|
from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
return self._config_dict['API_ROOT']
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
|
from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
url = self._config_dict['API_ROOT']
if not url.endswith('/'):
url += '/'
return url
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
|
Append slash to API root if needed.
|
Append slash to API root if needed.
|
Python
|
bsd-3-clause
|
socialwifi/jsonapi-requests
|
from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
- return self._config_dict['API_ROOT']
+ url = self._config_dict['API_ROOT']
+ if not url.endswith('/'):
+ url += '/'
+ return url
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
|
Append slash to API root if needed.
|
## Code Before:
from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
return self._config_dict['API_ROOT']
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
## Instruction:
Append slash to API root if needed.
## Code After:
from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
url = self._config_dict['API_ROOT']
if not url.endswith('/'):
url += '/'
return url
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
|
...
def API_ROOT(self):
url = self._config_dict['API_ROOT']
if not url.endswith('/'):
url += '/'
return url
...
|
5c9e9d33113c7fcf49223853abf52f1e91b17687
|
frappe/integrations/doctype/google_maps_settings/google_maps_settings.py
|
frappe/integrations/doctype/google_maps_settings/google_maps_settings.py
|
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
import googlemaps
import datetime
class GoogleMapsSettings(Document):
def validate(self):
if self.enabled:
if not self.client_key:
frappe.throw(_("Client key is required"))
if not self.home_address:
frappe.throw(_("Home Address is required"))
def get_client(self):
try:
client = googlemaps.Client(key=self.client_key)
except Exception as e:
frappe.throw(e.message)
return client
|
from __future__ import unicode_literals
import googlemaps
import frappe
from frappe import _
from frappe.model.document import Document
class GoogleMapsSettings(Document):
def validate(self):
if self.enabled:
if not self.client_key:
frappe.throw(_("Client key is required"))
if not self.home_address:
frappe.throw(_("Home Address is required"))
def get_client(self):
if not self.enabled:
frappe.throw(_("Google Maps integration is not enabled"))
try:
client = googlemaps.Client(key=self.client_key)
except Exception as e:
frappe.throw(e.message)
return client
|
Check if Google Maps is enabled when trying to get the client
|
Check if Google Maps is enabled when trying to get the client
|
Python
|
mit
|
adityahase/frappe,adityahase/frappe,ESS-LLP/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,yashodhank/frappe,RicardoJohann/frappe,yashodhank/frappe,ESS-LLP/frappe,frappe/frappe,mhbu50/frappe,saurabh6790/frappe,saurabh6790/frappe,adityahase/frappe,vjFaLk/frappe,yashodhank/frappe,mhbu50/frappe,vjFaLk/frappe,almeidapaulopt/frappe,frappe/frappe,vjFaLk/frappe,StrellaGroup/frappe,ESS-LLP/frappe,yashodhank/frappe,RicardoJohann/frappe,mhbu50/frappe,mhbu50/frappe,RicardoJohann/frappe,RicardoJohann/frappe,saurabh6790/frappe,StrellaGroup/frappe,frappe/frappe,ESS-LLP/frappe,saurabh6790/frappe,adityahase/frappe,vjFaLk/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe
|
from __future__ import unicode_literals
+
+ import googlemaps
+
import frappe
from frappe import _
from frappe.model.document import Document
+
- import googlemaps
- import datetime
class GoogleMapsSettings(Document):
def validate(self):
if self.enabled:
if not self.client_key:
frappe.throw(_("Client key is required"))
if not self.home_address:
frappe.throw(_("Home Address is required"))
def get_client(self):
+ if not self.enabled:
+ frappe.throw(_("Google Maps integration is not enabled"))
+
try:
client = googlemaps.Client(key=self.client_key)
except Exception as e:
frappe.throw(e.message)
return client
|
Check if Google Maps is enabled when trying to get the client
|
## Code Before:
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
import googlemaps
import datetime
class GoogleMapsSettings(Document):
def validate(self):
if self.enabled:
if not self.client_key:
frappe.throw(_("Client key is required"))
if not self.home_address:
frappe.throw(_("Home Address is required"))
def get_client(self):
try:
client = googlemaps.Client(key=self.client_key)
except Exception as e:
frappe.throw(e.message)
return client
## Instruction:
Check if Google Maps is enabled when trying to get the client
## Code After:
from __future__ import unicode_literals
import googlemaps
import frappe
from frappe import _
from frappe.model.document import Document
class GoogleMapsSettings(Document):
def validate(self):
if self.enabled:
if not self.client_key:
frappe.throw(_("Client key is required"))
if not self.home_address:
frappe.throw(_("Home Address is required"))
def get_client(self):
if not self.enabled:
frappe.throw(_("Google Maps integration is not enabled"))
try:
client = googlemaps.Client(key=self.client_key)
except Exception as e:
frappe.throw(e.message)
return client
|
# ... existing code ...
from __future__ import unicode_literals
import googlemaps
import frappe
# ... modified code ...
from frappe.model.document import Document
...
def get_client(self):
if not self.enabled:
frappe.throw(_("Google Maps integration is not enabled"))
try:
# ... rest of the code ...
|
39086b074dbac8d6d743ede09ce3556e4861e5a4
|
wdim/client/blob.py
|
wdim/client/blob.py
|
import json
import hashlib
from wdim.client.storable import Storable
class Blob(Storable):
HASH_METHOD = 'sha1'
@classmethod
def _create(cls, data):
sha = hashlib(cls.HASH_METHOD, json.dumps(data))
return cls(sha, data)
@classmethod
def _from_document(cls, document):
return cls(document['data'])
@property
def hash(self):
return self._id
def __init__(self, data):
self.data = data
def to_document(self):
return {
'_id': self.hash,
'data': self.data
}
|
import json
import hashlib
from wdim import exceptions
from wdim.client import fields
from wdim.client.storable import Storable
class Blob(Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data):
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
def hash(self):
return self._id
|
Reimplement Blob, switch to sha256
|
Reimplement Blob, switch to sha256
|
Python
|
mit
|
chrisseto/Still
|
import json
import hashlib
+ from wdim import exceptions
+ from wdim.client import fields
from wdim.client.storable import Storable
class Blob(Storable):
- HASH_METHOD = 'sha1'
+ HASH_METHOD = 'sha256'
+
+ _id = fields.StringField(unique=True)
+ data = fields.DictField()
@classmethod
- def _create(cls, data):
+ async def create(cls, data):
- sha = hashlib(cls.HASH_METHOD, json.dumps(data))
+ sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
- return cls(sha, data)
-
- @classmethod
- def _from_document(cls, document):
- return cls(document['data'])
+ try:
+ # Classmethod supers need arguments for some reason
+ return await super(Blob, cls).create(_id=sha, data=data)
+ except exceptions.UniqueViolation:
+ return await cls.load(sha)
@property
def hash(self):
return self._id
- def __init__(self, data):
- self.data = data
-
- def to_document(self):
- return {
- '_id': self.hash,
- 'data': self.data
- }
-
|
Reimplement Blob, switch to sha256
|
## Code Before:
import json
import hashlib
from wdim.client.storable import Storable
class Blob(Storable):
HASH_METHOD = 'sha1'
@classmethod
def _create(cls, data):
sha = hashlib(cls.HASH_METHOD, json.dumps(data))
return cls(sha, data)
@classmethod
def _from_document(cls, document):
return cls(document['data'])
@property
def hash(self):
return self._id
def __init__(self, data):
self.data = data
def to_document(self):
return {
'_id': self.hash,
'data': self.data
}
## Instruction:
Reimplement Blob, switch to sha256
## Code After:
import json
import hashlib
from wdim import exceptions
from wdim.client import fields
from wdim.client.storable import Storable
class Blob(Storable):
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
@classmethod
async def create(cls, data):
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
@property
def hash(self):
return self._id
|
...
from wdim import exceptions
from wdim.client import fields
from wdim.client.storable import Storable
...
HASH_METHOD = 'sha256'
_id = fields.StringField(unique=True)
data = fields.DictField()
...
@classmethod
async def create(cls, data):
sha = hashlib.new(cls.HASH_METHOD, json.dumps(data).encode('utf-8')).hexdigest()
try:
# Classmethod supers need arguments for some reason
return await super(Blob, cls).create(_id=sha, data=data)
except exceptions.UniqueViolation:
return await cls.load(sha)
...
return self._id
...
|
056cb6d5dff67fe029a080abeaba36faee5cff60
|
lib/test_util.py
|
lib/test_util.py
|
from lettuce import world
from tornado.escape import json_decode
from tornado.httpclient import HTTPClient
from newebe.settings import TORNADO_PORT
client = HTTPClient()
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
def fetch_documents_from_url(url):
'''
Retrieve newebe documents from a givent url
'''
response = client.fetch(url)
assert response.code == 200
assert response.headers["Content-Type"] == "application/json"
world.data = json_decode(response.body)
return world.data["rows"]
def fetch_documents(path):
fetch_documents_from_url(ROOT_URL + path)
|
from lettuce import world
from tornado.escape import json_decode
from tornado.httpclient import HTTPClient
from newebe.settings import TORNADO_PORT
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
class NewebeClient(HTTPClient):
'''
Tornado client wrapper to write POST, PUT and delete request faster.
'''
def get(self, url):
return HTTPClient.fetch(self, url)
def post(self, url, body):
return HTTPClient.fetch(self, url, method="POST", body=body)
def put(self, url, body):
return HTTPClient.fetch(self, url, method="PUT", body=body)
def delete(self, url):
return HTTPClient.fetch(self, url, method="DELETE")
def fetch_documents_from_url(self, url):
'''
Retrieve newebe documents from a givent url
'''
response = self.get(url)
assert response.code == 200
assert response.headers["Content-Type"] == "application/json"
world.data = json_decode(response.body)
return world.data["rows"]
def fetch_documents(self, path):
self.fetch_documents_from_url(ROOT_URL + path)
|
Make newebe HTTP client for easier requesting
|
Make newebe HTTP client for easier requesting
|
Python
|
agpl-3.0
|
gelnior/newebe,gelnior/newebe,gelnior/newebe,gelnior/newebe
|
from lettuce import world
from tornado.escape import json_decode
from tornado.httpclient import HTTPClient
from newebe.settings import TORNADO_PORT
- client = HTTPClient()
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
- def fetch_documents_from_url(url):
+ class NewebeClient(HTTPClient):
'''
- Retrieve newebe documents from a givent url
+ Tornado client wrapper to write POST, PUT and delete request faster.
'''
- response = client.fetch(url)
+ def get(self, url):
+ return HTTPClient.fetch(self, url)
+
+ def post(self, url, body):
+ return HTTPClient.fetch(self, url, method="POST", body=body)
+
+ def put(self, url, body):
+ return HTTPClient.fetch(self, url, method="PUT", body=body)
+
+ def delete(self, url):
+ return HTTPClient.fetch(self, url, method="DELETE")
+
+ def fetch_documents_from_url(self, url):
+ '''
+ Retrieve newebe documents from a givent url
+ '''
+ response = self.get(url)
+
- assert response.code == 200
+ assert response.code == 200
- assert response.headers["Content-Type"] == "application/json"
+ assert response.headers["Content-Type"] == "application/json"
- world.data = json_decode(response.body)
+ world.data = json_decode(response.body)
- return world.data["rows"]
+ return world.data["rows"]
- def fetch_documents(path):
+ def fetch_documents(self, path):
- fetch_documents_from_url(ROOT_URL + path)
+ self.fetch_documents_from_url(ROOT_URL + path)
|
Make newebe HTTP client for easier requesting
|
## Code Before:
from lettuce import world
from tornado.escape import json_decode
from tornado.httpclient import HTTPClient
from newebe.settings import TORNADO_PORT
client = HTTPClient()
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
def fetch_documents_from_url(url):
'''
Retrieve newebe documents from a givent url
'''
response = client.fetch(url)
assert response.code == 200
assert response.headers["Content-Type"] == "application/json"
world.data = json_decode(response.body)
return world.data["rows"]
def fetch_documents(path):
fetch_documents_from_url(ROOT_URL + path)
## Instruction:
Make newebe HTTP client for easier requesting
## Code After:
from lettuce import world
from tornado.escape import json_decode
from tornado.httpclient import HTTPClient
from newebe.settings import TORNADO_PORT
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
class NewebeClient(HTTPClient):
'''
Tornado client wrapper to write POST, PUT and delete request faster.
'''
def get(self, url):
return HTTPClient.fetch(self, url)
def post(self, url, body):
return HTTPClient.fetch(self, url, method="POST", body=body)
def put(self, url, body):
return HTTPClient.fetch(self, url, method="PUT", body=body)
def delete(self, url):
return HTTPClient.fetch(self, url, method="DELETE")
def fetch_documents_from_url(self, url):
'''
Retrieve newebe documents from a givent url
'''
response = self.get(url)
assert response.code == 200
assert response.headers["Content-Type"] == "application/json"
world.data = json_decode(response.body)
return world.data["rows"]
def fetch_documents(self, path):
self.fetch_documents_from_url(ROOT_URL + path)
|
// ... existing code ...
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
// ... modified code ...
class NewebeClient(HTTPClient):
'''
Tornado client wrapper to write POST, PUT and delete request faster.
'''
def get(self, url):
return HTTPClient.fetch(self, url)
def post(self, url, body):
return HTTPClient.fetch(self, url, method="POST", body=body)
def put(self, url, body):
return HTTPClient.fetch(self, url, method="PUT", body=body)
def delete(self, url):
return HTTPClient.fetch(self, url, method="DELETE")
def fetch_documents_from_url(self, url):
'''
Retrieve newebe documents from a givent url
'''
response = self.get(url)
assert response.code == 200
assert response.headers["Content-Type"] == "application/json"
world.data = json_decode(response.body)
return world.data["rows"]
def fetch_documents(self, path):
self.fetch_documents_from_url(ROOT_URL + path)
// ... rest of the code ...
|
174d9862242cecdf89c3fd398b93e805e49dea44
|
tinned_django/manage.py
|
tinned_django/manage.py
|
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Development")
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Development")
if len(sys.argv) > 1 and sys.argv[1] == 'test':
os.environ['DJANGO_CONFIGURATION'] = 'Testing'
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
Set up test environment when launching tests.
|
Set up test environment when launching tests.
|
Python
|
mit
|
futurecolors/tinned-django,futurecolors/tinned-django
|
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Development")
+ if len(sys.argv) > 1 and sys.argv[1] == 'test':
+ os.environ['DJANGO_CONFIGURATION'] = 'Testing'
+
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
Set up test environment when launching tests.
|
## Code Before:
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Development")
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
## Instruction:
Set up test environment when launching tests.
## Code After:
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Development")
if len(sys.argv) > 1 and sys.argv[1] == 'test':
os.environ['DJANGO_CONFIGURATION'] = 'Testing'
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
// ... existing code ...
if len(sys.argv) > 1 and sys.argv[1] == 'test':
os.environ['DJANGO_CONFIGURATION'] = 'Testing'
from configurations.management import execute_from_command_line
// ... rest of the code ...
|
1993a0adad94b0ed22557e2ee87326fc1eca0793
|
cumulusci/robotframework/locators_50.py
|
cumulusci/robotframework/locators_50.py
|
from cumulusci.robotframework import locators_49
import copy
lex_locators = copy.deepcopy(locators_49.lex_locators)
lex_locators["object"][
"button"
] = "//div[contains(@class, 'slds-page-header')]//*[self::a[@title='{title}'] or self::button[@name='{title}']]"
lex_locators["record"]["header"][
"field_value_link"
] = "//records-lwc-highlights-panel//force-highlights-details-item[.//*[.='{}']]//a"
lex_locators["record"]["related"][
"card"
] = "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]"
|
from cumulusci.robotframework import locators_49
import copy
lex_locators = copy.deepcopy(locators_49.lex_locators)
lex_locators["object"][
"button"
] = "//div[contains(@class, 'slds-page-header')]//*[self::a[@title='{title}'] or self::button[@name='{title}']]"
lex_locators["record"]["header"][
"field_value_link"
] = "//records-lwc-highlights-panel//force-highlights-details-item[.//*[.='{}']]//a"
lex_locators["record"]["related"] = {
"button": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//a[@title='{}']",
"card": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]",
"count": "//*[@data-component-id='force_relatedListContainer']//article//span[@title='{}']/following-sibling::span",
"link": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//*[text()='{}']",
"popup_trigger": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//span[text()='Show Actions']",
}
|
Update all related list locators
|
Update all related list locators
|
Python
|
bsd-3-clause
|
SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
|
from cumulusci.robotframework import locators_49
import copy
lex_locators = copy.deepcopy(locators_49.lex_locators)
lex_locators["object"][
"button"
] = "//div[contains(@class, 'slds-page-header')]//*[self::a[@title='{title}'] or self::button[@name='{title}']]"
lex_locators["record"]["header"][
"field_value_link"
] = "//records-lwc-highlights-panel//force-highlights-details-item[.//*[.='{}']]//a"
- lex_locators["record"]["related"][
- "card"
- ] = "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]"
+ lex_locators["record"]["related"] = {
+ "button": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//a[@title='{}']",
+ "card": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]",
+ "count": "//*[@data-component-id='force_relatedListContainer']//article//span[@title='{}']/following-sibling::span",
+ "link": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//*[text()='{}']",
+ "popup_trigger": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//span[text()='Show Actions']",
+ }
+
|
Update all related list locators
|
## Code Before:
from cumulusci.robotframework import locators_49
import copy
lex_locators = copy.deepcopy(locators_49.lex_locators)
lex_locators["object"][
"button"
] = "//div[contains(@class, 'slds-page-header')]//*[self::a[@title='{title}'] or self::button[@name='{title}']]"
lex_locators["record"]["header"][
"field_value_link"
] = "//records-lwc-highlights-panel//force-highlights-details-item[.//*[.='{}']]//a"
lex_locators["record"]["related"][
"card"
] = "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]"
## Instruction:
Update all related list locators
## Code After:
from cumulusci.robotframework import locators_49
import copy
lex_locators = copy.deepcopy(locators_49.lex_locators)
lex_locators["object"][
"button"
] = "//div[contains(@class, 'slds-page-header')]//*[self::a[@title='{title}'] or self::button[@name='{title}']]"
lex_locators["record"]["header"][
"field_value_link"
] = "//records-lwc-highlights-panel//force-highlights-details-item[.//*[.='{}']]//a"
lex_locators["record"]["related"] = {
"button": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//a[@title='{}']",
"card": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]",
"count": "//*[@data-component-id='force_relatedListContainer']//article//span[@title='{}']/following-sibling::span",
"link": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//*[text()='{}']",
"popup_trigger": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//span[text()='Show Actions']",
}
|
# ... existing code ...
lex_locators["record"]["related"] = {
"button": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//a[@title='{}']",
"card": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]",
"count": "//*[@data-component-id='force_relatedListContainer']//article//span[@title='{}']/following-sibling::span",
"link": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//*[text()='{}']",
"popup_trigger": "//*[@data-component-id='force_relatedListContainer']//article[.//span[@title='{}']]//span[text()='Show Actions']",
}
# ... rest of the code ...
|
b4e3461277669bf42225d278d491b7c714968491
|
vm_server/test/execute_macro/code/execute.py
|
vm_server/test/execute_macro/code/execute.py
|
import os
import shutil
import win32com.client
import pythoncom
import repackage
repackage.up()
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
path_to_file = current_path + "\\action\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
shutil.move(path_to_file, current_path +
"\\action\\output\\excelsheet.xlsm")
shutil.move(current_path + "\\action\\data\\output.txt", current_path +
"\\action\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
|
import os
import shutil
import win32com.client
import pythoncom
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
path_to_file = ".\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
shutil.move(path_to_file, ".\\output\\excelsheet.xlsm")
shutil.move(".\\data\\output.txt", ".\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
|
Modify excel screenshot test so that it works with the new directory structure
|
Modify excel screenshot test so that it works with the new directory structure
|
Python
|
apache-2.0
|
googleinterns/automated-windows-vms,googleinterns/automated-windows-vms
|
import os
import shutil
import win32com.client
import pythoncom
- import repackage
- repackage.up()
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
- path_to_file = current_path + "\\action\\data\\excelsheet.xlsm"
+ path_to_file = ".\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
+ shutil.move(path_to_file, ".\\output\\excelsheet.xlsm")
+ shutil.move(".\\data\\output.txt", ".\\output\\output.txt")
- shutil.move(path_to_file, current_path +
- "\\action\\output\\excelsheet.xlsm")
- shutil.move(current_path + "\\action\\data\\output.txt", current_path +
- "\\action\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
|
Modify excel screenshot test so that it works with the new directory structure
|
## Code Before:
import os
import shutil
import win32com.client
import pythoncom
import repackage
repackage.up()
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
path_to_file = current_path + "\\action\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
shutil.move(path_to_file, current_path +
"\\action\\output\\excelsheet.xlsm")
shutil.move(current_path + "\\action\\data\\output.txt", current_path +
"\\action\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
## Instruction:
Modify excel screenshot test so that it works with the new directory structure
## Code After:
import os
import shutil
import win32com.client
import pythoncom
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
path_to_file = ".\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
shutil.move(path_to_file, ".\\output\\excelsheet.xlsm")
shutil.move(".\\data\\output.txt", ".\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
|
...
import pythoncom
...
current_path = os.path.dirname(os.getcwd())
path_to_file = ".\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
...
del xl_file
shutil.move(path_to_file, ".\\output\\excelsheet.xlsm")
shutil.move(".\\data\\output.txt", ".\\output\\output.txt")
print("Action successfully executed")
...
|
6ac67683c1aea8578d1b9b5ad9d41280d6789f58
|
schematics/types/temporal.py
|
schematics/types/temporal.py
|
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def __set__(self, instance, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = TimeStampType.timestamp_to_date(value)
except TypeError:
pass
super(TimeStampType, self).__set__(instance, value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
return TimeStampType.timestamp_to_date(value)
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
Fix TimeStampType to use convert method
|
Fix TimeStampType to use convert method
|
Python
|
bsd-3-clause
|
nKey/schematics
|
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
- def __set__(self, instance, value):
+ def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
+ value = float(value)
- value = TimeStampType.timestamp_to_date(value)
+ return TimeStampType.timestamp_to_date(value)
- except TypeError:
+ except (TypeError, ValueError):
pass
- super(TimeStampType, self).__set__(instance, value)
+ return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
Fix TimeStampType to use convert method
|
## Code Before:
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def __set__(self, instance, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = TimeStampType.timestamp_to_date(value)
except TypeError:
pass
super(TimeStampType, self).__set__(instance, value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
## Instruction:
Fix TimeStampType to use convert method
## Code After:
from __future__ import absolute_import
import datetime
from time import mktime
try:
from dateutil.tz import tzutc, tzlocal
except ImportError:
raise ImportError(
'Using the datetime fields requires the dateutil library. '
'You can obtain dateutil from http://labix.org/python-dateutil'
)
from .base import DateTimeType
class TimeStampType(DateTimeType):
"""Variant of a datetime field that saves itself as a unix timestamp (int)
instead of a ISO-8601 string.
"""
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
will fallback to DateTimeType's value parsing.
A datetime may be used (and is encouraged).
"""
if not value:
return
try:
value = float(value)
return TimeStampType.timestamp_to_date(value)
except (TypeError, ValueError):
pass
return super(TimeStampType, self).convert(value)
@classmethod
def timestamp_to_date(cls, value):
return datetime.datetime.fromtimestamp(value, tz=tzutc())
@classmethod
def date_to_timestamp(cls, value):
if value.tzinfo is None:
value = value.replace(tzinfo=tzlocal())
return int(round(mktime(value.astimezone(tzutc()).timetuple())))
def to_primitive(self, value):
v = TimeStampType.date_to_timestamp(value)
return v
|
# ... existing code ...
def convert(self, value):
"""Will try to parse the value as a timestamp. If that fails it
# ... modified code ...
try:
value = float(value)
return TimeStampType.timestamp_to_date(value)
except (TypeError, ValueError):
pass
...
return super(TimeStampType, self).convert(value)
# ... rest of the code ...
|
e0510ea02ad1998973a9e0733f2342b06ddcf182
|
test/python_api/default-constructor/sb_breakpointlocation.py
|
test/python_api/default-constructor/sb_breakpointlocation.py
|
import sys
import lldb
def fuzz_obj(obj):
obj.GetLoadAddress()
obj.SetEnabled(True)
obj.IsEnabled()
obj.SetCondition("i >= 10")
obj.GetCondition()
obj.SetThreadID(0)
obj.GetThreadID()
obj.SetThreadIndex(0)
obj.GetThreadIndex()
obj.SetThreadName("worker thread")
obj.GetThreadName()
obj.SetQueueName("my queue")
obj.GetQueueName()
obj.IsResolved()
obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose)
breakpoint = obj.GetBreakpoint()
# Do fuzz testing on the breakpoint obj, it should not crash lldb.
import sb_breakpoint
sb_breakpoint.fuzz_obj(breakpoint)
|
import sys
import lldb
def fuzz_obj(obj):
obj.GetAddress()
obj.GetLoadAddress()
obj.SetEnabled(True)
obj.IsEnabled()
obj.SetCondition("i >= 10")
obj.GetCondition()
obj.SetThreadID(0)
obj.GetThreadID()
obj.SetThreadIndex(0)
obj.GetThreadIndex()
obj.SetThreadName("worker thread")
obj.GetThreadName()
obj.SetQueueName("my queue")
obj.GetQueueName()
obj.IsResolved()
obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose)
breakpoint = obj.GetBreakpoint()
# Do fuzz testing on the breakpoint obj, it should not crash lldb.
import sb_breakpoint
sb_breakpoint.fuzz_obj(breakpoint)
|
Add fuzz call for SBBreakpointLocation.GetAddress().
|
Add fuzz call for SBBreakpointLocation.GetAddress().
git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@141443 91177308-0d34-0410-b5e6-96231b3b80d8
|
Python
|
apache-2.0
|
apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb
|
import sys
import lldb
def fuzz_obj(obj):
+ obj.GetAddress()
obj.GetLoadAddress()
obj.SetEnabled(True)
obj.IsEnabled()
obj.SetCondition("i >= 10")
obj.GetCondition()
obj.SetThreadID(0)
obj.GetThreadID()
obj.SetThreadIndex(0)
obj.GetThreadIndex()
obj.SetThreadName("worker thread")
obj.GetThreadName()
obj.SetQueueName("my queue")
obj.GetQueueName()
obj.IsResolved()
obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose)
breakpoint = obj.GetBreakpoint()
# Do fuzz testing on the breakpoint obj, it should not crash lldb.
import sb_breakpoint
sb_breakpoint.fuzz_obj(breakpoint)
|
Add fuzz call for SBBreakpointLocation.GetAddress().
|
## Code Before:
import sys
import lldb
def fuzz_obj(obj):
obj.GetLoadAddress()
obj.SetEnabled(True)
obj.IsEnabled()
obj.SetCondition("i >= 10")
obj.GetCondition()
obj.SetThreadID(0)
obj.GetThreadID()
obj.SetThreadIndex(0)
obj.GetThreadIndex()
obj.SetThreadName("worker thread")
obj.GetThreadName()
obj.SetQueueName("my queue")
obj.GetQueueName()
obj.IsResolved()
obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose)
breakpoint = obj.GetBreakpoint()
# Do fuzz testing on the breakpoint obj, it should not crash lldb.
import sb_breakpoint
sb_breakpoint.fuzz_obj(breakpoint)
## Instruction:
Add fuzz call for SBBreakpointLocation.GetAddress().
## Code After:
import sys
import lldb
def fuzz_obj(obj):
obj.GetAddress()
obj.GetLoadAddress()
obj.SetEnabled(True)
obj.IsEnabled()
obj.SetCondition("i >= 10")
obj.GetCondition()
obj.SetThreadID(0)
obj.GetThreadID()
obj.SetThreadIndex(0)
obj.GetThreadIndex()
obj.SetThreadName("worker thread")
obj.GetThreadName()
obj.SetQueueName("my queue")
obj.GetQueueName()
obj.IsResolved()
obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose)
breakpoint = obj.GetBreakpoint()
# Do fuzz testing on the breakpoint obj, it should not crash lldb.
import sb_breakpoint
sb_breakpoint.fuzz_obj(breakpoint)
|
// ... existing code ...
def fuzz_obj(obj):
obj.GetAddress()
obj.GetLoadAddress()
// ... rest of the code ...
|
b0a94dc2f696464db999e652b4a9dbdaf96f8532
|
backend/talks/forms.py
|
backend/talks/forms.py
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code')
language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code')
def clean(self):
cleaned_data = super().clean()
conference = cleaned_data['conference']
if not conference.is_cfp_open:
raise forms.ValidationError(_('The call for papers is not open!'))
def save(self, commit=True):
self.instance.owner = self.context.user
return super().save(commit=commit)
class Meta:
model = Talk
fields = ('title', 'abstract', 'topic', 'language', 'conference')
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code', required=True)
language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code', required=True)
def clean(self):
cleaned_data = super().clean()
conference = cleaned_data.get('conference')
if conference and not conference.is_cfp_open:
raise forms.ValidationError(_('The call for papers is not open!'))
def save(self, commit=True):
self.instance.owner = self.context.user
return super().save(commit=commit)
class Meta:
model = Talk
fields = ('title', 'abstract', 'topic', 'language', 'conference')
|
Mark conference and language as required
|
Mark conference and language as required
|
Python
|
mit
|
patrick91/pycon,patrick91/pycon
|
from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
- conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code')
+ conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code', required=True)
- language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code')
+ language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code', required=True)
def clean(self):
cleaned_data = super().clean()
- conference = cleaned_data['conference']
+ conference = cleaned_data.get('conference')
- if not conference.is_cfp_open:
+ if conference and not conference.is_cfp_open:
raise forms.ValidationError(_('The call for papers is not open!'))
def save(self, commit=True):
self.instance.owner = self.context.user
return super().save(commit=commit)
class Meta:
model = Talk
fields = ('title', 'abstract', 'topic', 'language', 'conference')
|
Mark conference and language as required
|
## Code Before:
from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code')
language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code')
def clean(self):
cleaned_data = super().clean()
conference = cleaned_data['conference']
if not conference.is_cfp_open:
raise forms.ValidationError(_('The call for papers is not open!'))
def save(self, commit=True):
self.instance.owner = self.context.user
return super().save(commit=commit)
class Meta:
model = Talk
fields = ('title', 'abstract', 'topic', 'language', 'conference')
## Instruction:
Mark conference and language as required
## Code After:
from django import forms
from django.utils.translation import ugettext_lazy as _
from api.forms import GrapheneModelForm
from languages.models import Language
from conferences.models import Conference
from .models import Talk
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code', required=True)
language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code', required=True)
def clean(self):
cleaned_data = super().clean()
conference = cleaned_data.get('conference')
if conference and not conference.is_cfp_open:
raise forms.ValidationError(_('The call for papers is not open!'))
def save(self, commit=True):
self.instance.owner = self.context.user
return super().save(commit=commit)
class Meta:
model = Talk
fields = ('title', 'abstract', 'topic', 'language', 'conference')
|
// ... existing code ...
class ProposeTalkForm(GrapheneModelForm):
conference = forms.ModelChoiceField(queryset=Conference.objects.all(), to_field_name='code', required=True)
language = forms.ModelChoiceField(queryset=Language.objects.all(), to_field_name='code', required=True)
// ... modified code ...
cleaned_data = super().clean()
conference = cleaned_data.get('conference')
if conference and not conference.is_cfp_open:
raise forms.ValidationError(_('The call for papers is not open!'))
// ... rest of the code ...
|
2c3ddc18477561f4880c2b857c4aa8a0f8478dfd
|
src/psycholinguistic_db/psycholinguistic_db_creator.py
|
src/psycholinguistic_db/psycholinguistic_db_creator.py
|
__author__ = 'Somsubhra Bairi'
__email__ = '[email protected]'
# All imports
from logger import Logger
# The psycholinguistic database creator
class PsycholinguisticDbCreator:
# Constructor for the database creator
def __init__(self, in_file, out_file):
self.in_file = in_file
self.out_file = out_file
# Create the database
def create(self):
Logger.log_message('Creating psycholinguistic dictionary database')
input_file = open(self.in_file, 'r')
output_file = open(self.out_file, 'w')
for line in input_file.readlines():
output_file.write(';'.join(word.lower() for word in line.split()) + '\n')
input_file.close()
output_file.close()
Logger.log_success('Created psycholinguistic dictionary database')
|
__author__ = 'Somsubhra Bairi'
__email__ = '[email protected]'
# All imports
from logger import Logger
from nltk import PorterStemmer
# The psycholinguistic database creator
class PsycholinguisticDbCreator:
# Constructor for the database creator
def __init__(self, in_file, out_file):
self.in_file = in_file
self.out_file = out_file
self.kf_frequencies = {}
self.syllables = {}
# Create the database
def create(self):
Logger.log_message('Creating psycholinguistic dictionary database')
input_file = open(self.in_file, 'r')
output_file = open(self.out_file, 'w')
for line in input_file.readlines():
items = line.split()
word = PorterStemmer().stem_word(items[2].lower())
kff = items[1]
syl = items[0]
if word in self.kf_frequencies:
# Select the stemmed word with the maximum KF Frequency
if kff > self.kf_frequencies[word]:
self.kf_frequencies[word] = kff
else:
self.kf_frequencies[word] = kff
if word in self.syllables:
# Select the stemmed word with minimum number of syllables
if syl < self.syllables[word]:
self.syllables[word] = syl
else:
self.syllables[word] = syl
# Dump the contents to the output file
for word in self.kf_frequencies:
output_file.write(word + ";" + self.kf_frequencies[word] + ";" + self.syllables[word] + "\n")
input_file.close()
output_file.close()
Logger.log_success('Created psycholinguistic dictionary database')
|
Create the psycholinguistic_db according to our needs
|
Create the psycholinguistic_db according to our needs
|
Python
|
mit
|
Somsubhra/Enrich,Somsubhra/Enrich,Somsubhra/Enrich
|
__author__ = 'Somsubhra Bairi'
__email__ = '[email protected]'
# All imports
from logger import Logger
+
+ from nltk import PorterStemmer
# The psycholinguistic database creator
class PsycholinguisticDbCreator:
# Constructor for the database creator
def __init__(self, in_file, out_file):
self.in_file = in_file
self.out_file = out_file
+ self.kf_frequencies = {}
+ self.syllables = {}
# Create the database
def create(self):
Logger.log_message('Creating psycholinguistic dictionary database')
input_file = open(self.in_file, 'r')
output_file = open(self.out_file, 'w')
for line in input_file.readlines():
- output_file.write(';'.join(word.lower() for word in line.split()) + '\n')
+ items = line.split()
+ word = PorterStemmer().stem_word(items[2].lower())
+ kff = items[1]
+ syl = items[0]
+
+ if word in self.kf_frequencies:
+ # Select the stemmed word with the maximum KF Frequency
+ if kff > self.kf_frequencies[word]:
+ self.kf_frequencies[word] = kff
+ else:
+ self.kf_frequencies[word] = kff
+
+ if word in self.syllables:
+ # Select the stemmed word with minimum number of syllables
+ if syl < self.syllables[word]:
+ self.syllables[word] = syl
+ else:
+ self.syllables[word] = syl
+
+ # Dump the contents to the output file
+ for word in self.kf_frequencies:
+ output_file.write(word + ";" + self.kf_frequencies[word] + ";" + self.syllables[word] + "\n")
input_file.close()
output_file.close()
Logger.log_success('Created psycholinguistic dictionary database')
|
Create the psycholinguistic_db according to our needs
|
## Code Before:
__author__ = 'Somsubhra Bairi'
__email__ = '[email protected]'
# All imports
from logger import Logger
# The psycholinguistic database creator
class PsycholinguisticDbCreator:
# Constructor for the database creator
def __init__(self, in_file, out_file):
self.in_file = in_file
self.out_file = out_file
# Create the database
def create(self):
Logger.log_message('Creating psycholinguistic dictionary database')
input_file = open(self.in_file, 'r')
output_file = open(self.out_file, 'w')
for line in input_file.readlines():
output_file.write(';'.join(word.lower() for word in line.split()) + '\n')
input_file.close()
output_file.close()
Logger.log_success('Created psycholinguistic dictionary database')
## Instruction:
Create the psycholinguistic_db according to our needs
## Code After:
__author__ = 'Somsubhra Bairi'
__email__ = '[email protected]'
# All imports
from logger import Logger
from nltk import PorterStemmer
# The psycholinguistic database creator
class PsycholinguisticDbCreator:
# Constructor for the database creator
def __init__(self, in_file, out_file):
self.in_file = in_file
self.out_file = out_file
self.kf_frequencies = {}
self.syllables = {}
# Create the database
def create(self):
Logger.log_message('Creating psycholinguistic dictionary database')
input_file = open(self.in_file, 'r')
output_file = open(self.out_file, 'w')
for line in input_file.readlines():
items = line.split()
word = PorterStemmer().stem_word(items[2].lower())
kff = items[1]
syl = items[0]
if word in self.kf_frequencies:
# Select the stemmed word with the maximum KF Frequency
if kff > self.kf_frequencies[word]:
self.kf_frequencies[word] = kff
else:
self.kf_frequencies[word] = kff
if word in self.syllables:
# Select the stemmed word with minimum number of syllables
if syl < self.syllables[word]:
self.syllables[word] = syl
else:
self.syllables[word] = syl
# Dump the contents to the output file
for word in self.kf_frequencies:
output_file.write(word + ";" + self.kf_frequencies[word] + ";" + self.syllables[word] + "\n")
input_file.close()
output_file.close()
Logger.log_success('Created psycholinguistic dictionary database')
|
// ... existing code ...
from logger import Logger
from nltk import PorterStemmer
// ... modified code ...
self.out_file = out_file
self.kf_frequencies = {}
self.syllables = {}
...
for line in input_file.readlines():
items = line.split()
word = PorterStemmer().stem_word(items[2].lower())
kff = items[1]
syl = items[0]
if word in self.kf_frequencies:
# Select the stemmed word with the maximum KF Frequency
if kff > self.kf_frequencies[word]:
self.kf_frequencies[word] = kff
else:
self.kf_frequencies[word] = kff
if word in self.syllables:
# Select the stemmed word with minimum number of syllables
if syl < self.syllables[word]:
self.syllables[word] = syl
else:
self.syllables[word] = syl
# Dump the contents to the output file
for word in self.kf_frequencies:
output_file.write(word + ";" + self.kf_frequencies[word] + ";" + self.syllables[word] + "\n")
// ... rest of the code ...
|
370c49eba30253f259454884441e9921b51719ab
|
dudebot/ai.py
|
dudebot/ai.py
|
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
pass
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
return False, ''
class message_must_begin_with_prefix(object):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the given prefix.
That way you can have your dude bot only respond to messages that, for
example, begin with 'dude '.
"""
def __init__(self, desired_prefix):
self.desired_prefix = desired_prefix
def __call__(self, func):
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(self.desired_prefix):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
def message_must_begin_with_nickname(func):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the bot AI's nickname.
"""
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(botai.nickname):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
Add some decorators to make life easier.
|
Add some decorators to make life easier.
|
Python
|
bsd-2-clause
|
sujaymansingh/dudebot
|
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
- pass
+ return False, ''
+
+
+ class message_must_begin_with_prefix(object):
+ """A simple decorator so that a bot AI can ignore all messages that don't
+ begin with the given prefix.
+ That way you can have your dude bot only respond to messages that, for
+ example, begin with 'dude '.
+ """
+
+ def __init__(self, desired_prefix):
+ self.desired_prefix = desired_prefix
+
+ def __call__(self, func):
+ def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
+ if message.startswith(self.desired_prefix):
+ return func(botai, sender_nickname, message, *args, **kwargs)
+ else:
+ return False, ''
+ return wrapped_func
+
+
+ def message_must_begin_with_nickname(func):
+ """A simple decorator so that a bot AI can ignore all messages that don't
+ begin with the bot AI's nickname.
+ """
+ def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
+ if message.startswith(botai.nickname):
+ return func(botai, sender_nickname, message, *args, **kwargs)
+ else:
+ return False, ''
+ return wrapped_func
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
Add some decorators to make life easier.
|
## Code Before:
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
pass
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
## Instruction:
Add some decorators to make life easier.
## Code After:
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
return False, ''
class message_must_begin_with_prefix(object):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the given prefix.
That way you can have your dude bot only respond to messages that, for
example, begin with 'dude '.
"""
def __init__(self, desired_prefix):
self.desired_prefix = desired_prefix
def __call__(self, func):
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(self.desired_prefix):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
def message_must_begin_with_nickname(func):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the bot AI's nickname.
"""
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(botai.nickname):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
...
def respond(self, sender_nickname, message):
return False, ''
class message_must_begin_with_prefix(object):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the given prefix.
That way you can have your dude bot only respond to messages that, for
example, begin with 'dude '.
"""
def __init__(self, desired_prefix):
self.desired_prefix = desired_prefix
def __call__(self, func):
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(self.desired_prefix):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
def message_must_begin_with_nickname(func):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the bot AI's nickname.
"""
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(botai.nickname):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
...
|
037fcccebae10f608f5a2711fbbc659411d6879b
|
okdataset/context.py
|
okdataset/context.py
|
class DsContext(object):
def __init__(self, config="okdataset.yml"):
self.workers = 8
|
import yaml
import os
"""
DataSet context
"""
class Context(object):
def __init__(self, config=os.path.dirname(os.path.realpath(__file__)) + "/../okdataset.yml"):
self.workers = 8
self.config = yaml.load(open(config).read())
|
Put yaml config in Context.
|
Put yaml config in Context.
|
Python
|
mit
|
anthonyserious/okdataset,anthonyserious/okdataset
|
+ import yaml
+ import os
+
+ """
+ DataSet context
+ """
- class DsContext(object):
+ class Context(object):
- def __init__(self, config="okdataset.yml"):
+ def __init__(self, config=os.path.dirname(os.path.realpath(__file__)) + "/../okdataset.yml"):
self.workers = 8
+ self.config = yaml.load(open(config).read())
+
|
Put yaml config in Context.
|
## Code Before:
class DsContext(object):
def __init__(self, config="okdataset.yml"):
self.workers = 8
## Instruction:
Put yaml config in Context.
## Code After:
import yaml
import os
"""
DataSet context
"""
class Context(object):
def __init__(self, config=os.path.dirname(os.path.realpath(__file__)) + "/../okdataset.yml"):
self.workers = 8
self.config = yaml.load(open(config).read())
|
# ... existing code ...
import yaml
import os
"""
DataSet context
"""
class Context(object):
def __init__(self, config=os.path.dirname(os.path.realpath(__file__)) + "/../okdataset.yml"):
self.workers = 8
self.config = yaml.load(open(config).read())
# ... rest of the code ...
|
6c67d06a691be8a930c0e82fcf404057580645d8
|
tests/conftest.py
|
tests/conftest.py
|
import os
import sys
from pathlib import Path
import pytest
if sys.version_info < (3, 4):
print("Requires Python 3.4+")
sys.exit(1)
TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(TESTS_ROOT)
@pytest.fixture
def resources():
return Path(TESTS_ROOT) / 'resources'
@pytest.fixture(scope="function")
def outdir(tmp_path):
return tmp_path
@pytest.fixture(scope="function")
def outpdf(tmp_path):
return tmp_path / 'out.pdf'
|
import os
import sys
from pathlib import Path
import pytest
if sys.version_info < (3, 4):
print("Requires Python 3.4+")
sys.exit(1)
TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(TESTS_ROOT)
@pytest.fixture(scope="session")
def resources():
return Path(TESTS_ROOT) / 'resources'
@pytest.fixture(scope="function")
def outdir(tmp_path):
return tmp_path
@pytest.fixture(scope="function")
def outpdf(tmp_path):
return tmp_path / 'out.pdf'
|
Fix warning from hypothesis above scope of resources() fixture
|
Fix warning from hypothesis above scope of resources() fixture
|
Python
|
mpl-2.0
|
pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf
|
import os
import sys
from pathlib import Path
import pytest
-
if sys.version_info < (3, 4):
print("Requires Python 3.4+")
sys.exit(1)
TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(TESTS_ROOT)
- @pytest.fixture
+ @pytest.fixture(scope="session")
def resources():
return Path(TESTS_ROOT) / 'resources'
@pytest.fixture(scope="function")
def outdir(tmp_path):
return tmp_path
@pytest.fixture(scope="function")
def outpdf(tmp_path):
return tmp_path / 'out.pdf'
|
Fix warning from hypothesis above scope of resources() fixture
|
## Code Before:
import os
import sys
from pathlib import Path
import pytest
if sys.version_info < (3, 4):
print("Requires Python 3.4+")
sys.exit(1)
TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(TESTS_ROOT)
@pytest.fixture
def resources():
return Path(TESTS_ROOT) / 'resources'
@pytest.fixture(scope="function")
def outdir(tmp_path):
return tmp_path
@pytest.fixture(scope="function")
def outpdf(tmp_path):
return tmp_path / 'out.pdf'
## Instruction:
Fix warning from hypothesis above scope of resources() fixture
## Code After:
import os
import sys
from pathlib import Path
import pytest
if sys.version_info < (3, 4):
print("Requires Python 3.4+")
sys.exit(1)
TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(TESTS_ROOT)
@pytest.fixture(scope="session")
def resources():
return Path(TESTS_ROOT) / 'resources'
@pytest.fixture(scope="function")
def outdir(tmp_path):
return tmp_path
@pytest.fixture(scope="function")
def outpdf(tmp_path):
return tmp_path / 'out.pdf'
|
// ... existing code ...
import pytest
// ... modified code ...
@pytest.fixture(scope="session")
def resources():
// ... rest of the code ...
|
1ff4b0473c79150d5387ed2174b120128d465737
|
app.py
|
app.py
|
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, world!"
if __name__ == "__main__":
app.run();
|
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, world!"
@app.route("/user/<username>")
def show_user(username):
return "User page for user " + username
@app.route("/game/<gamename>")
def show_game(gamename):
return "Game page for game " + gamename
@app.route("/game/<gamename>/submit")
def show_submit_score(gamename):
return "Submit a score for game " + gamename
@app.route("/game/<gamename>/leaderboard")
def show_leaderboard(gamename):
return "Show the leaderboard for game " + gamename
if __name__ == "__main__":
app.run();
|
Add stub methods for expected paths
|
Add stub methods for expected paths
|
Python
|
mit
|
JamesLaverack/scoreboard,JamesLaverack/scoreboard,JamesLaverack/scoreboard
|
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, world!"
+ @app.route("/user/<username>")
+ def show_user(username):
+ return "User page for user " + username
+
+ @app.route("/game/<gamename>")
+ def show_game(gamename):
+ return "Game page for game " + gamename
+
+ @app.route("/game/<gamename>/submit")
+ def show_submit_score(gamename):
+ return "Submit a score for game " + gamename
+
+ @app.route("/game/<gamename>/leaderboard")
+ def show_leaderboard(gamename):
+ return "Show the leaderboard for game " + gamename
+
if __name__ == "__main__":
app.run();
|
Add stub methods for expected paths
|
## Code Before:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, world!"
if __name__ == "__main__":
app.run();
## Instruction:
Add stub methods for expected paths
## Code After:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, world!"
@app.route("/user/<username>")
def show_user(username):
return "User page for user " + username
@app.route("/game/<gamename>")
def show_game(gamename):
return "Game page for game " + gamename
@app.route("/game/<gamename>/submit")
def show_submit_score(gamename):
return "Submit a score for game " + gamename
@app.route("/game/<gamename>/leaderboard")
def show_leaderboard(gamename):
return "Show the leaderboard for game " + gamename
if __name__ == "__main__":
app.run();
|
# ... existing code ...
@app.route("/user/<username>")
def show_user(username):
return "User page for user " + username
@app.route("/game/<gamename>")
def show_game(gamename):
return "Game page for game " + gamename
@app.route("/game/<gamename>/submit")
def show_submit_score(gamename):
return "Submit a score for game " + gamename
@app.route("/game/<gamename>/leaderboard")
def show_leaderboard(gamename):
return "Show the leaderboard for game " + gamename
if __name__ == "__main__":
# ... rest of the code ...
|
e98b9e1da819c571e165c55e222a3aa5a20e709b
|
mrbelvedereci/build/apps.py
|
mrbelvedereci/build/apps.py
|
from __future__ import unicode_literals
from django.apps import AppConfig
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
|
from __future__ import unicode_literals
from django.apps import AppConfig
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
def ready(self):
import mrbelvedereci.build.handlers
|
Include handlers in build app
|
Include handlers in build app
|
Python
|
bsd-3-clause
|
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
|
from __future__ import unicode_literals
from django.apps import AppConfig
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
+ def ready(self):
+ import mrbelvedereci.build.handlers
+
|
Include handlers in build app
|
## Code Before:
from __future__ import unicode_literals
from django.apps import AppConfig
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
## Instruction:
Include handlers in build app
## Code After:
from __future__ import unicode_literals
from django.apps import AppConfig
class BuildConfig(AppConfig):
name = 'mrbelvedereci.build'
def ready(self):
import mrbelvedereci.build.handlers
|
...
name = 'mrbelvedereci.build'
def ready(self):
import mrbelvedereci.build.handlers
...
|
c0fd2b981f2657e0a78de028335ea172735c5f6b
|
zaqar/common/cli.py
|
zaqar/common/cli.py
|
from __future__ import print_function
import functools
import sys
from zaqar.i18n import _
from zaqar.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _fail(returncode, ex):
"""Handles terminal errors.
:param returncode: process return code to pass to sys.exit
:param ex: the error that occurred
"""
LOG.exception(ex)
sys.exit(returncode)
def runnable(func):
"""Entry point wrapper.
Note: This call blocks until the process is killed
or interrupted.
"""
@functools.wraps(func)
def _wrapper():
try:
logging.setup('zaqar')
func()
except KeyboardInterrupt:
LOG.info(_(u'Terminating'))
except Exception as ex:
_fail(1, ex)
return _wrapper
|
from __future__ import print_function
import functools
import sys
from zaqar.i18n import _
from zaqar.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _fail(returncode, ex):
"""Handles terminal errors.
:param returncode: process return code to pass to sys.exit
:param ex: the error that occurred
"""
print(ex, file=sys.stderr)
LOG.exception(ex)
sys.exit(returncode)
def runnable(func):
"""Entry point wrapper.
Note: This call blocks until the process is killed
or interrupted.
"""
@functools.wraps(func)
def _wrapper():
try:
logging.setup('zaqar')
func()
except KeyboardInterrupt:
LOG.info(_(u'Terminating'))
except Exception as ex:
_fail(1, ex)
return _wrapper
|
Fix regression: No handlers could be found for logger when start
|
Fix regression: No handlers could be found for logger when start
This change fixed a function regression on bug/1201562.
Closes-Bug: #1201562
Change-Id: I3994c97633f5d09cccf6defdf0eac3957d63304e
Signed-off-by: Zhi Yan Liu <[email protected]>
|
Python
|
apache-2.0
|
openstack/zaqar,openstack/zaqar,openstack/zaqar,openstack/zaqar
|
from __future__ import print_function
import functools
import sys
from zaqar.i18n import _
from zaqar.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _fail(returncode, ex):
"""Handles terminal errors.
:param returncode: process return code to pass to sys.exit
:param ex: the error that occurred
"""
+
+ print(ex, file=sys.stderr)
LOG.exception(ex)
sys.exit(returncode)
def runnable(func):
"""Entry point wrapper.
Note: This call blocks until the process is killed
or interrupted.
"""
@functools.wraps(func)
def _wrapper():
try:
logging.setup('zaqar')
func()
except KeyboardInterrupt:
LOG.info(_(u'Terminating'))
except Exception as ex:
_fail(1, ex)
return _wrapper
|
Fix regression: No handlers could be found for logger when start
|
## Code Before:
from __future__ import print_function
import functools
import sys
from zaqar.i18n import _
from zaqar.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _fail(returncode, ex):
"""Handles terminal errors.
:param returncode: process return code to pass to sys.exit
:param ex: the error that occurred
"""
LOG.exception(ex)
sys.exit(returncode)
def runnable(func):
"""Entry point wrapper.
Note: This call blocks until the process is killed
or interrupted.
"""
@functools.wraps(func)
def _wrapper():
try:
logging.setup('zaqar')
func()
except KeyboardInterrupt:
LOG.info(_(u'Terminating'))
except Exception as ex:
_fail(1, ex)
return _wrapper
## Instruction:
Fix regression: No handlers could be found for logger when start
## Code After:
from __future__ import print_function
import functools
import sys
from zaqar.i18n import _
from zaqar.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _fail(returncode, ex):
"""Handles terminal errors.
:param returncode: process return code to pass to sys.exit
:param ex: the error that occurred
"""
print(ex, file=sys.stderr)
LOG.exception(ex)
sys.exit(returncode)
def runnable(func):
"""Entry point wrapper.
Note: This call blocks until the process is killed
or interrupted.
"""
@functools.wraps(func)
def _wrapper():
try:
logging.setup('zaqar')
func()
except KeyboardInterrupt:
LOG.info(_(u'Terminating'))
except Exception as ex:
_fail(1, ex)
return _wrapper
|
# ... existing code ...
"""
print(ex, file=sys.stderr)
# ... rest of the code ...
|
e53715c6ee7896d459a46c810480b12dc7a6b5ad
|
tg/dottednames/jinja_lookup.py
|
tg/dottednames/jinja_lookup.py
|
"""Genshi template loader that supports dotted names."""
from os.path import exists, getmtime
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import FileSystemLoader
from tg import config
class JinjaTemplateLoader(FileSystemLoader):
"""Jinja template loader supporting dotted filenames. Based on Genshi Loader
"""
template_extension = '.jinja'
def get_source(self, environment, template):
# Check if dottedname
if not template.endswith(self.template_extension):
# Get the actual filename from dotted finder
finder = config['pylons.app_globals'].dotted_filename_finder
template = finder.get_dotted_filename(
template_name=template,
template_extension=self.template_extension)
else:
return FileSystemLoader.get_source(self, environment, template)
# Check if the template exists
if not exists(template):
raise TemplateNotFound(template)
# Get modification time
mtime = getmtime(template)
# Read the source
fd = file(template)
try:
source = fd.read().decode('utf-8')
finally:
fd.close()
return source, template, lambda: mtime == getmtime(template)
|
"""Genshi template loader that supports dotted names."""
from os.path import exists, getmtime
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import FileSystemLoader
from tg import config
class JinjaTemplateLoader(FileSystemLoader):
"""Jinja template loader supporting dotted filenames. Based on Genshi Loader
"""
template_extension = '.jinja'
def get_source(self, environment, template):
# Check if dottedname
if not template.endswith(self.template_extension):
# Get the actual filename from dotted finder
finder = config['tg.app_globals'].dotted_filename_finder
template = finder.get_dotted_filename(
template_name=template,
template_extension=self.template_extension)
else:
return FileSystemLoader.get_source(self, environment, template)
# Check if the template exists
if not exists(template):
raise TemplateNotFound(template)
# Get modification time
mtime = getmtime(template)
# Read the source
fd = open(template, 'rb')
try:
source = fd.read().decode('utf-8')
finally:
fd.close()
return source, template, lambda: mtime == getmtime(template)
|
Fix jinja loader on Py3
|
Fix jinja loader on Py3
|
Python
|
mit
|
lucius-feng/tg2,lucius-feng/tg2
|
"""Genshi template loader that supports dotted names."""
from os.path import exists, getmtime
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import FileSystemLoader
from tg import config
class JinjaTemplateLoader(FileSystemLoader):
"""Jinja template loader supporting dotted filenames. Based on Genshi Loader
"""
template_extension = '.jinja'
def get_source(self, environment, template):
# Check if dottedname
if not template.endswith(self.template_extension):
# Get the actual filename from dotted finder
- finder = config['pylons.app_globals'].dotted_filename_finder
+ finder = config['tg.app_globals'].dotted_filename_finder
template = finder.get_dotted_filename(
template_name=template,
template_extension=self.template_extension)
else:
return FileSystemLoader.get_source(self, environment, template)
# Check if the template exists
if not exists(template):
raise TemplateNotFound(template)
# Get modification time
mtime = getmtime(template)
# Read the source
- fd = file(template)
+ fd = open(template, 'rb')
try:
source = fd.read().decode('utf-8')
finally:
fd.close()
return source, template, lambda: mtime == getmtime(template)
|
Fix jinja loader on Py3
|
## Code Before:
"""Genshi template loader that supports dotted names."""
from os.path import exists, getmtime
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import FileSystemLoader
from tg import config
class JinjaTemplateLoader(FileSystemLoader):
"""Jinja template loader supporting dotted filenames. Based on Genshi Loader
"""
template_extension = '.jinja'
def get_source(self, environment, template):
# Check if dottedname
if not template.endswith(self.template_extension):
# Get the actual filename from dotted finder
finder = config['pylons.app_globals'].dotted_filename_finder
template = finder.get_dotted_filename(
template_name=template,
template_extension=self.template_extension)
else:
return FileSystemLoader.get_source(self, environment, template)
# Check if the template exists
if not exists(template):
raise TemplateNotFound(template)
# Get modification time
mtime = getmtime(template)
# Read the source
fd = file(template)
try:
source = fd.read().decode('utf-8')
finally:
fd.close()
return source, template, lambda: mtime == getmtime(template)
## Instruction:
Fix jinja loader on Py3
## Code After:
"""Genshi template loader that supports dotted names."""
from os.path import exists, getmtime
from jinja2.exceptions import TemplateNotFound
from jinja2.loaders import FileSystemLoader
from tg import config
class JinjaTemplateLoader(FileSystemLoader):
"""Jinja template loader supporting dotted filenames. Based on Genshi Loader
"""
template_extension = '.jinja'
def get_source(self, environment, template):
# Check if dottedname
if not template.endswith(self.template_extension):
# Get the actual filename from dotted finder
finder = config['tg.app_globals'].dotted_filename_finder
template = finder.get_dotted_filename(
template_name=template,
template_extension=self.template_extension)
else:
return FileSystemLoader.get_source(self, environment, template)
# Check if the template exists
if not exists(template):
raise TemplateNotFound(template)
# Get modification time
mtime = getmtime(template)
# Read the source
fd = open(template, 'rb')
try:
source = fd.read().decode('utf-8')
finally:
fd.close()
return source, template, lambda: mtime == getmtime(template)
|
# ... existing code ...
# Get the actual filename from dotted finder
finder = config['tg.app_globals'].dotted_filename_finder
template = finder.get_dotted_filename(
# ... modified code ...
# Read the source
fd = open(template, 'rb')
try:
# ... rest of the code ...
|
42709afec9f2e2ed419365f61324ce0c8ff96423
|
budget/forms.py
|
budget/forms.py
|
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
|
import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
|
Split the start_date for better data entry (and Javascript date pickers).
|
Split the start_date for better data entry (and Javascript date pickers).
|
Python
|
bsd-3-clause
|
jokimies/django-pj-budget,jokimies/django-pj-budget,toastdriven/django-budget,toastdriven/django-budget,jokimies/django-pj-budget
|
+ import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
+ start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
+
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
|
Split the start_date for better data entry (and Javascript date pickers).
|
## Code Before:
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
## Instruction:
Split the start_date for better data entry (and Javascript date pickers).
## Code After:
import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
|
# ... existing code ...
import datetime
from django import forms
# ... modified code ...
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
# ... rest of the code ...
|
236f10e790757db0cc563f5f19ca5863877b1e7f
|
busstops/management/tests/test_import_singapore.py
|
busstops/management/tests/test_import_singapore.py
|
import os
import vcr
from django.test import TestCase, override_settings
from django.core.management import call_command
from ...models import StopPoint, Service, Place
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures')
class ImportSingaporeTest(TestCase):
@classmethod
def setUpTestData(cls):
with vcr.use_cassette(os.path.join(FIXTURES_DIR, 'singapore.yaml')):
call_command('import_singapore')
call_command('import_singapore_places')
def test_import_stops(self):
self.assertEqual(499, StopPoint.objects.all().count())
stop = StopPoint.objects.first()
self.assertEqual(str(stop), 'AFT BRAS BASAH STN EXIT A')
def test_import_services(self):
service = Service.objects.get()
self.assertEqual(service.operator.get().name, 'SBS Transit')
self.assertEqual(service.slug, 'sg-sbst-10')
def test_import_places(self):
self.assertEqual(307, Place.objects.count())
place = Place.objects.get(name='Central Singapore')
response = self.client.get(place.get_absolute_url())
self.assertContains(response, '<h1>Central Singapore</h1>')
self.assertContains(response, 'Fort Canning')
self.assertContains(response, 'Bayfront Subzone')
|
import os
import vcr
from django.test import TestCase
from django.core.management import call_command
from ...models import StopPoint, Service, Place
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures')
class ImportSingaporeTest(TestCase):
@classmethod
def setUpTestData(cls):
with vcr.use_cassette(os.path.join(FIXTURES_DIR, 'singapore.yaml')):
call_command('import_singapore')
call_command('import_singapore_places')
def test_import_stops(self):
self.assertEqual(499, StopPoint.objects.all().count())
stop = StopPoint.objects.first()
self.assertEqual(str(stop), 'AFT BRAS BASAH STN EXIT A')
def test_import_services(self):
service = Service.objects.get()
self.assertEqual(service.operator.get().name, 'SBS Transit')
self.assertEqual(service.slug, 'sg-sbst-10')
def test_import_places(self):
self.assertEqual(307, Place.objects.count())
place = Place.objects.get(name='Central Singapore')
response = self.client.get(place.get_absolute_url())
self.assertContains(response, '<h1>Central Singapore</h1>')
self.assertContains(response, 'Fort Canning')
self.assertContains(response, 'Bayfront Subzone')
|
Remove unused import to fix flake8
|
Remove unused import to fix flake8
|
Python
|
mpl-2.0
|
jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk
|
import os
import vcr
- from django.test import TestCase, override_settings
+ from django.test import TestCase
from django.core.management import call_command
from ...models import StopPoint, Service, Place
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures')
class ImportSingaporeTest(TestCase):
@classmethod
def setUpTestData(cls):
with vcr.use_cassette(os.path.join(FIXTURES_DIR, 'singapore.yaml')):
call_command('import_singapore')
call_command('import_singapore_places')
def test_import_stops(self):
self.assertEqual(499, StopPoint.objects.all().count())
stop = StopPoint.objects.first()
self.assertEqual(str(stop), 'AFT BRAS BASAH STN EXIT A')
def test_import_services(self):
service = Service.objects.get()
self.assertEqual(service.operator.get().name, 'SBS Transit')
self.assertEqual(service.slug, 'sg-sbst-10')
def test_import_places(self):
self.assertEqual(307, Place.objects.count())
place = Place.objects.get(name='Central Singapore')
response = self.client.get(place.get_absolute_url())
self.assertContains(response, '<h1>Central Singapore</h1>')
self.assertContains(response, 'Fort Canning')
self.assertContains(response, 'Bayfront Subzone')
|
Remove unused import to fix flake8
|
## Code Before:
import os
import vcr
from django.test import TestCase, override_settings
from django.core.management import call_command
from ...models import StopPoint, Service, Place
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures')
class ImportSingaporeTest(TestCase):
@classmethod
def setUpTestData(cls):
with vcr.use_cassette(os.path.join(FIXTURES_DIR, 'singapore.yaml')):
call_command('import_singapore')
call_command('import_singapore_places')
def test_import_stops(self):
self.assertEqual(499, StopPoint.objects.all().count())
stop = StopPoint.objects.first()
self.assertEqual(str(stop), 'AFT BRAS BASAH STN EXIT A')
def test_import_services(self):
service = Service.objects.get()
self.assertEqual(service.operator.get().name, 'SBS Transit')
self.assertEqual(service.slug, 'sg-sbst-10')
def test_import_places(self):
self.assertEqual(307, Place.objects.count())
place = Place.objects.get(name='Central Singapore')
response = self.client.get(place.get_absolute_url())
self.assertContains(response, '<h1>Central Singapore</h1>')
self.assertContains(response, 'Fort Canning')
self.assertContains(response, 'Bayfront Subzone')
## Instruction:
Remove unused import to fix flake8
## Code After:
import os
import vcr
from django.test import TestCase
from django.core.management import call_command
from ...models import StopPoint, Service, Place
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures')
class ImportSingaporeTest(TestCase):
@classmethod
def setUpTestData(cls):
with vcr.use_cassette(os.path.join(FIXTURES_DIR, 'singapore.yaml')):
call_command('import_singapore')
call_command('import_singapore_places')
def test_import_stops(self):
self.assertEqual(499, StopPoint.objects.all().count())
stop = StopPoint.objects.first()
self.assertEqual(str(stop), 'AFT BRAS BASAH STN EXIT A')
def test_import_services(self):
service = Service.objects.get()
self.assertEqual(service.operator.get().name, 'SBS Transit')
self.assertEqual(service.slug, 'sg-sbst-10')
def test_import_places(self):
self.assertEqual(307, Place.objects.count())
place = Place.objects.get(name='Central Singapore')
response = self.client.get(place.get_absolute_url())
self.assertContains(response, '<h1>Central Singapore</h1>')
self.assertContains(response, 'Fort Canning')
self.assertContains(response, 'Bayfront Subzone')
|
...
import vcr
from django.test import TestCase
from django.core.management import call_command
...
|
911fa61043cb034202aacc7ca3e92ceac048265c
|
greengraph/graph_command.py
|
greengraph/graph_command.py
|
from .greengraph import GreenGraph
from .googlemap import GoogleMap
from argparse import ArgumentParser
import IPython
if __name__ == "__main__":
parser = ArgumentParser(description = 'Generate pictures between 2 location')
parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start')
parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end')
parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20)
parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true")
parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename')
args = parser.parse_args()
my_data = GreenGraph(args.start, args.end)
if args.greenbetween:
print(my_data.green_between(args.steps))
else:
for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps):
IPython.core.display.Image(GoogleMap(*location).image)
|
from .greengraph import GreenGraph
from .googlemap import GoogleMap
from argparse import ArgumentParser
from IPython.display import Image
from IPython.display import display
if __name__ == "__main__":
parser = ArgumentParser(description = 'Generate pictures between 2 location')
parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start')
parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end')
parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20)
parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true")
parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename')
args = parser.parse_args()
my_data = GreenGraph(args.start, args.end)
if args.greenbetween:
print(my_data.green_between(args.steps))
else:
for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps):
display(Image(GoogleMap(*location).image))
|
Fix displaying multiple images command
|
Fix displaying multiple images command
|
Python
|
mit
|
manhdao/greengraph-MPHYSG001
|
from .greengraph import GreenGraph
from .googlemap import GoogleMap
from argparse import ArgumentParser
- import IPython
+ from IPython.display import Image
+ from IPython.display import display
if __name__ == "__main__":
parser = ArgumentParser(description = 'Generate pictures between 2 location')
parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start')
parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end')
parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20)
parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true")
parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename')
args = parser.parse_args()
my_data = GreenGraph(args.start, args.end)
if args.greenbetween:
print(my_data.green_between(args.steps))
else:
for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps):
- IPython.core.display.Image(GoogleMap(*location).image)
+ display(Image(GoogleMap(*location).image))
|
Fix displaying multiple images command
|
## Code Before:
from .greengraph import GreenGraph
from .googlemap import GoogleMap
from argparse import ArgumentParser
import IPython
if __name__ == "__main__":
parser = ArgumentParser(description = 'Generate pictures between 2 location')
parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start')
parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end')
parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20)
parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true")
parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename')
args = parser.parse_args()
my_data = GreenGraph(args.start, args.end)
if args.greenbetween:
print(my_data.green_between(args.steps))
else:
for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps):
IPython.core.display.Image(GoogleMap(*location).image)
## Instruction:
Fix displaying multiple images command
## Code After:
from .greengraph import GreenGraph
from .googlemap import GoogleMap
from argparse import ArgumentParser
from IPython.display import Image
from IPython.display import display
if __name__ == "__main__":
parser = ArgumentParser(description = 'Generate pictures between 2 location')
parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start')
parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end')
parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20)
parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true")
parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename')
args = parser.parse_args()
my_data = GreenGraph(args.start, args.end)
if args.greenbetween:
print(my_data.green_between(args.steps))
else:
for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps):
display(Image(GoogleMap(*location).image))
|
...
from argparse import ArgumentParser
from IPython.display import Image
from IPython.display import display
...
for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps):
display(Image(GoogleMap(*location).image))
...
|
ff476b33c26a9067e6ac64b2c161d29b0febea33
|
py/capnptools/examples/tests/test_books.py
|
py/capnptools/examples/tests/test_books.py
|
import unittest
from examples import books
class BooksTest(unittest.TestCase):
def test_builder(self):
book = books.MallocMessageBuilder().init_root(books.Book)
book.title = 'Moby-Dick; or, The Whale'
book.authors = ['Herman Melville']
self.assertEqual(
{
'title': 'Moby-Dick; or, The Whale',
'authors': ['Herman Melville'],
},
book._as_dict(),
)
book = book._as_reader()
self.assertEqual('Moby-Dick; or, The Whale', book.title)
self.assertEqual(['Herman Melville'], book.authors._as_dict())
self.assertEqual(
{
'title': 'Moby-Dick; or, The Whale',
'authors': ['Herman Melville'],
},
book._as_dict(),
)
if __name__ == '__main__':
unittest.main()
|
import unittest
import os
import tempfile
from examples import books
class BooksTest(unittest.TestCase):
BOOK = {
'title': 'Moby-Dick; or, The Whale',
'authors': ['Herman Melville'],
}
def test_builder(self):
book = books.MallocMessageBuilder().init_root(books.Book)
book.title = self.BOOK['title']
book.authors = self.BOOK['authors']
self.assertEqual(self.BOOK, book._as_dict())
book = book._as_reader()
self.assertEqual(self.BOOK['title'], book.title)
self.assertEqual(self.BOOK['authors'], book.authors._as_dict())
self.assertEqual(self.BOOK, book._as_dict())
def test_write(self):
builder = books.MallocMessageBuilder()
book = builder.init_root(books.Book)
book.title = self.BOOK['title']
book.authors = self.BOOK['authors']
for read_cls, write_func in [
('StreamFdMessageReader', 'write_to'),
('PackedFdMessageReader', 'write_packed_to')]:
with self.subTest(read_cls=read_cls, write_func=write_func):
fd, path = tempfile.mkstemp()
try:
getattr(builder, write_func)(fd)
os.close(fd)
fd = os.open(path, os.O_RDONLY)
reader = getattr(books, read_cls)(fd)
book = reader.get_root(books.Book)
self.assertEqual(self.BOOK, book._as_dict())
finally:
os.unlink(path)
os.close(fd)
if __name__ == '__main__':
unittest.main()
|
Add unit tests for write_to and write_packed_to
|
Add unit tests for write_to and write_packed_to
|
Python
|
mit
|
clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage
|
import unittest
+
+ import os
+ import tempfile
from examples import books
class BooksTest(unittest.TestCase):
+ BOOK = {
+ 'title': 'Moby-Dick; or, The Whale',
+ 'authors': ['Herman Melville'],
+ }
+
def test_builder(self):
+
book = books.MallocMessageBuilder().init_root(books.Book)
+ book.title = self.BOOK['title']
+ book.authors = self.BOOK['authors']
+ self.assertEqual(self.BOOK, book._as_dict())
- book.title = 'Moby-Dick; or, The Whale'
- book.authors = ['Herman Melville']
- self.assertEqual(
- {
- 'title': 'Moby-Dick; or, The Whale',
- 'authors': ['Herman Melville'],
- },
- book._as_dict(),
- )
book = book._as_reader()
- self.assertEqual('Moby-Dick; or, The Whale', book.title)
+ self.assertEqual(self.BOOK['title'], book.title)
- self.assertEqual(['Herman Melville'], book.authors._as_dict())
+ self.assertEqual(self.BOOK['authors'], book.authors._as_dict())
- self.assertEqual(
- {
- 'title': 'Moby-Dick; or, The Whale',
- 'authors': ['Herman Melville'],
- },
- book._as_dict(),
- )
+ self.assertEqual(self.BOOK, book._as_dict())
+
+ def test_write(self):
+
+ builder = books.MallocMessageBuilder()
+ book = builder.init_root(books.Book)
+ book.title = self.BOOK['title']
+ book.authors = self.BOOK['authors']
+
+ for read_cls, write_func in [
+ ('StreamFdMessageReader', 'write_to'),
+ ('PackedFdMessageReader', 'write_packed_to')]:
+
+ with self.subTest(read_cls=read_cls, write_func=write_func):
+ fd, path = tempfile.mkstemp()
+ try:
+ getattr(builder, write_func)(fd)
+ os.close(fd)
+
+ fd = os.open(path, os.O_RDONLY)
+ reader = getattr(books, read_cls)(fd)
+ book = reader.get_root(books.Book)
+ self.assertEqual(self.BOOK, book._as_dict())
+
+ finally:
+ os.unlink(path)
+ os.close(fd)
if __name__ == '__main__':
unittest.main()
|
Add unit tests for write_to and write_packed_to
|
## Code Before:
import unittest
from examples import books
class BooksTest(unittest.TestCase):
def test_builder(self):
book = books.MallocMessageBuilder().init_root(books.Book)
book.title = 'Moby-Dick; or, The Whale'
book.authors = ['Herman Melville']
self.assertEqual(
{
'title': 'Moby-Dick; or, The Whale',
'authors': ['Herman Melville'],
},
book._as_dict(),
)
book = book._as_reader()
self.assertEqual('Moby-Dick; or, The Whale', book.title)
self.assertEqual(['Herman Melville'], book.authors._as_dict())
self.assertEqual(
{
'title': 'Moby-Dick; or, The Whale',
'authors': ['Herman Melville'],
},
book._as_dict(),
)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add unit tests for write_to and write_packed_to
## Code After:
import unittest
import os
import tempfile
from examples import books
class BooksTest(unittest.TestCase):
BOOK = {
'title': 'Moby-Dick; or, The Whale',
'authors': ['Herman Melville'],
}
def test_builder(self):
book = books.MallocMessageBuilder().init_root(books.Book)
book.title = self.BOOK['title']
book.authors = self.BOOK['authors']
self.assertEqual(self.BOOK, book._as_dict())
book = book._as_reader()
self.assertEqual(self.BOOK['title'], book.title)
self.assertEqual(self.BOOK['authors'], book.authors._as_dict())
self.assertEqual(self.BOOK, book._as_dict())
def test_write(self):
builder = books.MallocMessageBuilder()
book = builder.init_root(books.Book)
book.title = self.BOOK['title']
book.authors = self.BOOK['authors']
for read_cls, write_func in [
('StreamFdMessageReader', 'write_to'),
('PackedFdMessageReader', 'write_packed_to')]:
with self.subTest(read_cls=read_cls, write_func=write_func):
fd, path = tempfile.mkstemp()
try:
getattr(builder, write_func)(fd)
os.close(fd)
fd = os.open(path, os.O_RDONLY)
reader = getattr(books, read_cls)(fd)
book = reader.get_root(books.Book)
self.assertEqual(self.BOOK, book._as_dict())
finally:
os.unlink(path)
os.close(fd)
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
import unittest
import os
import tempfile
// ... modified code ...
BOOK = {
'title': 'Moby-Dick; or, The Whale',
'authors': ['Herman Melville'],
}
def test_builder(self):
book = books.MallocMessageBuilder().init_root(books.Book)
book.title = self.BOOK['title']
book.authors = self.BOOK['authors']
self.assertEqual(self.BOOK, book._as_dict())
...
book = book._as_reader()
self.assertEqual(self.BOOK['title'], book.title)
self.assertEqual(self.BOOK['authors'], book.authors._as_dict())
self.assertEqual(self.BOOK, book._as_dict())
def test_write(self):
builder = books.MallocMessageBuilder()
book = builder.init_root(books.Book)
book.title = self.BOOK['title']
book.authors = self.BOOK['authors']
for read_cls, write_func in [
('StreamFdMessageReader', 'write_to'),
('PackedFdMessageReader', 'write_packed_to')]:
with self.subTest(read_cls=read_cls, write_func=write_func):
fd, path = tempfile.mkstemp()
try:
getattr(builder, write_func)(fd)
os.close(fd)
fd = os.open(path, os.O_RDONLY)
reader = getattr(books, read_cls)(fd)
book = reader.get_root(books.Book)
self.assertEqual(self.BOOK, book._as_dict())
finally:
os.unlink(path)
os.close(fd)
// ... rest of the code ...
|
e76ca364ab979e309d34ff458ef2629145a52ce2
|
magnum/db/sqlalchemy/alembic/versions/a1136d335540_add_docker_storage_driver_column.py
|
magnum/db/sqlalchemy/alembic/versions/a1136d335540_add_docker_storage_driver_column.py
|
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
docker_storage_driver_enum.create(op.get_bind(), checkfirst=True)
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
Fix for enum type docker_storage_driver
|
Fix for enum type docker_storage_driver
Create enum type "docker_storage_driver" for migration
This is fixing
oslo_db.exception.DBError: (psycopg2.ProgrammingError) type
"docker_storage_driver" does not exist
Closes-Bug: #1609776
Change-Id: I92d427e90bd73b4114d8688d3761cabac450fc9d
|
Python
|
apache-2.0
|
openstack/magnum,openstack/magnum,ArchiFleKs/magnum,ArchiFleKs/magnum
|
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
+ docker_storage_driver_enum.create(op.get_bind(), checkfirst=True)
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
Fix for enum type docker_storage_driver
|
## Code Before:
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
## Instruction:
Fix for enum type docker_storage_driver
## Code After:
# revision identifiers, used by Alembic.
revision = 'a1136d335540'
down_revision = 'd072f58ab240'
from alembic import op
import sqlalchemy as sa
docker_storage_driver_enum = sa.Enum('devicemapper', 'overlay',
name='docker_storage_driver')
def upgrade():
docker_storage_driver_enum.create(op.get_bind(), checkfirst=True)
op.add_column('baymodel', sa.Column('docker_storage_driver',
docker_storage_driver_enum,
nullable=True))
|
// ... existing code ...
def upgrade():
docker_storage_driver_enum.create(op.get_bind(), checkfirst=True)
op.add_column('baymodel', sa.Column('docker_storage_driver',
// ... rest of the code ...
|
09618bd6cdef2025ea02a999a869c9c6a0560989
|
mockserver/manager.py
|
mockserver/manager.py
|
from flask_script import Manager
import mockserver
from mockserver.database import database
import json
import codecs
import os
manager = Manager(mockserver.get_app())
@manager.command
def init():
if os.path.exists(mockserver.db_file):
os.remove(mockserver.db_file)
database.db.create_all()
@manager.command
def dump(bak_file):
print('Dump %s start' % bak_file)
all_interfaces = database.Interface.query.all()
if len(all_interfaces) == 0:
print('Not found any data to dump.')
return
all_data = []
for interface in all_interfaces:
all_data.append(interface.to_dict())
f = codecs.open(bak_file, 'w', 'utf-8')
f.write(json.dumps(all_data, ensure_ascii=False, indent=4))
f.close()
print('Dump completed')
@manager.command
def load(bak_file):
print('Load %s start' % bak_file)
f = codecs.open(bak_file, 'r')
all_data = json.loads(f.read())
f.close()
for data in all_data:
interface = database.Interface.from_dict(data)
if len(database.Interface.query.filter_by(name=interface.name).all()) > 0:
interface.name = '[Dup.]' + interface.name
database.db.session.add(interface)
database.db.session.commit()
|
from flask_script import Manager
import mockserver
from mockserver.database import database
import json
import codecs
import os
manager = Manager(mockserver.get_app())
@manager.command
def init():
if os.path.exists(mockserver.db_file):
os.remove(mockserver.db_file)
database.db.create_all()
@manager.command
def dump(bak_file):
print('Dump %s start' % bak_file)
all_interfaces = database.Interface.query.all()
if len(all_interfaces) == 0:
print('Not found any data to dump.')
return
all_data = []
for interface in all_interfaces:
all_data.append(interface.to_dict())
f = codecs.open(bak_file, 'w', 'utf-8')
f.write(json.dumps(all_data, ensure_ascii=False, indent=4))
f.close()
print('Dump completed')
@manager.command
def load(bak_file):
print('Load %s start' % bak_file)
f = codecs.open(bak_file, 'r', 'utf-8')
all_data = json.loads(f.read())
f.close()
for data in all_data:
interface = database.Interface.from_dict(data)
if len(database.Interface.query.filter_by(name=interface.name).all()) > 0:
interface.name = '[Dup.]' + interface.name
database.db.session.add(interface)
database.db.session.commit()
print('Load completed')
|
Fix bug: file encoding is GBK on windows system.
|
Fix bug: file encoding is GBK on windows system.
|
Python
|
apache-2.0
|
IfengAutomation/mockserver,IfengAutomation/mockserver,IfengAutomation/mockserver
|
from flask_script import Manager
import mockserver
from mockserver.database import database
import json
import codecs
import os
manager = Manager(mockserver.get_app())
@manager.command
def init():
if os.path.exists(mockserver.db_file):
os.remove(mockserver.db_file)
database.db.create_all()
@manager.command
def dump(bak_file):
print('Dump %s start' % bak_file)
all_interfaces = database.Interface.query.all()
if len(all_interfaces) == 0:
print('Not found any data to dump.')
return
all_data = []
for interface in all_interfaces:
all_data.append(interface.to_dict())
f = codecs.open(bak_file, 'w', 'utf-8')
f.write(json.dumps(all_data, ensure_ascii=False, indent=4))
f.close()
print('Dump completed')
@manager.command
def load(bak_file):
print('Load %s start' % bak_file)
- f = codecs.open(bak_file, 'r')
+ f = codecs.open(bak_file, 'r', 'utf-8')
all_data = json.loads(f.read())
f.close()
for data in all_data:
interface = database.Interface.from_dict(data)
if len(database.Interface.query.filter_by(name=interface.name).all()) > 0:
interface.name = '[Dup.]' + interface.name
database.db.session.add(interface)
database.db.session.commit()
+ print('Load completed')
|
Fix bug: file encoding is GBK on windows system.
|
## Code Before:
from flask_script import Manager
import mockserver
from mockserver.database import database
import json
import codecs
import os
manager = Manager(mockserver.get_app())
@manager.command
def init():
if os.path.exists(mockserver.db_file):
os.remove(mockserver.db_file)
database.db.create_all()
@manager.command
def dump(bak_file):
print('Dump %s start' % bak_file)
all_interfaces = database.Interface.query.all()
if len(all_interfaces) == 0:
print('Not found any data to dump.')
return
all_data = []
for interface in all_interfaces:
all_data.append(interface.to_dict())
f = codecs.open(bak_file, 'w', 'utf-8')
f.write(json.dumps(all_data, ensure_ascii=False, indent=4))
f.close()
print('Dump completed')
@manager.command
def load(bak_file):
print('Load %s start' % bak_file)
f = codecs.open(bak_file, 'r')
all_data = json.loads(f.read())
f.close()
for data in all_data:
interface = database.Interface.from_dict(data)
if len(database.Interface.query.filter_by(name=interface.name).all()) > 0:
interface.name = '[Dup.]' + interface.name
database.db.session.add(interface)
database.db.session.commit()
## Instruction:
Fix bug: file encoding is GBK on windows system.
## Code After:
from flask_script import Manager
import mockserver
from mockserver.database import database
import json
import codecs
import os
manager = Manager(mockserver.get_app())
@manager.command
def init():
if os.path.exists(mockserver.db_file):
os.remove(mockserver.db_file)
database.db.create_all()
@manager.command
def dump(bak_file):
print('Dump %s start' % bak_file)
all_interfaces = database.Interface.query.all()
if len(all_interfaces) == 0:
print('Not found any data to dump.')
return
all_data = []
for interface in all_interfaces:
all_data.append(interface.to_dict())
f = codecs.open(bak_file, 'w', 'utf-8')
f.write(json.dumps(all_data, ensure_ascii=False, indent=4))
f.close()
print('Dump completed')
@manager.command
def load(bak_file):
print('Load %s start' % bak_file)
f = codecs.open(bak_file, 'r', 'utf-8')
all_data = json.loads(f.read())
f.close()
for data in all_data:
interface = database.Interface.from_dict(data)
if len(database.Interface.query.filter_by(name=interface.name).all()) > 0:
interface.name = '[Dup.]' + interface.name
database.db.session.add(interface)
database.db.session.commit()
print('Load completed')
|
// ... existing code ...
print('Load %s start' % bak_file)
f = codecs.open(bak_file, 'r', 'utf-8')
all_data = json.loads(f.read())
// ... modified code ...
database.db.session.commit()
print('Load completed')
// ... rest of the code ...
|
a8de8ebdfb31fd6fee78cfcdd4ef921ed54bf6f1
|
currencies/context_processors.py
|
currencies/context_processors.py
|
from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'currency': request.session['currency'], # DEPRECATED
'CURRENCY': request.session['currency']
}
|
from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'CURRENCY': request.session['currency']
}
|
Remove the deprecated 'currency' context
|
Remove the deprecated 'currency' context
|
Python
|
bsd-3-clause
|
bashu/django-simple-currencies,pathakamit88/django-currencies,panosl/django-currencies,pathakamit88/django-currencies,mysociety/django-currencies,bashu/django-simple-currencies,ydaniv/django-currencies,racitup/django-currencies,marcosalcazar/django-currencies,panosl/django-currencies,jmp0xf/django-currencies,ydaniv/django-currencies,mysociety/django-currencies,racitup/django-currencies,marcosalcazar/django-currencies,barseghyanartur/django-currencies
|
from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
- 'currency': request.session['currency'], # DEPRECATED
'CURRENCY': request.session['currency']
}
|
Remove the deprecated 'currency' context
|
## Code Before:
from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'currency': request.session['currency'], # DEPRECATED
'CURRENCY': request.session['currency']
}
## Instruction:
Remove the deprecated 'currency' context
## Code After:
from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'CURRENCY': request.session['currency']
}
|
...
'CURRENCIES': currencies,
'CURRENCY': request.session['currency']
...
|
6e6aaac438a18220db20ad480a8a82af49c44caa
|
pages/serializers.py
|
pages/serializers.py
|
from rest_framework import serializers
from rest_framework.reverse import reverse
from pages import fields, mixins, models
from pages.utils import build_url
class PageSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.CharField()
regions = serializers.SerializerMethodField('rendered_regions')
class Meta:
fields = ('id', 'url', 'name', 'slug', 'regions')
model = models.Page
view_name = 'pages:page-detail'
extra_kwargs = {
'url': {'lookup_field': 'slug'},
}
def rendered_regions(self, obj):
return obj.rendered_regions(self.context['request'])
class JsonPageSerializer(PageSerializer):
def rendered_regions(self, obj):
"""Render regions as a json-serializable dictionary."""
return obj.render_json(self.context.get('request'))
class GroupSerializer(mixins.LinksMixin, serializers.HyperlinkedModelSerializer):
url = fields.AbsoluteURLIdentityField()
pages = serializers.SerializerMethodField('get_pages_link')
links_fields = ['pages']
class Meta:
model = models.Group
def get_pages_link(self, obj):
return build_url(
reverse('pages:page-list', request=self.context.get('request')),
{'group': obj.slug},
)
|
from rest_framework import serializers
from rest_framework.reverse import reverse
from pages import fields, mixins, models
from pages.utils import build_url
class PageSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.CharField()
regions = serializers.SerializerMethodField('rendered_regions')
class Meta:
fields = ('id', 'url', 'name', 'slug', 'regions')
model = models.Page
view_name = 'pages:page-detail'
extra_kwargs = {
'url': {'lookup_field': 'slug', 'view_name': 'pages:page-detail'},
}
def rendered_regions(self, obj):
return obj.rendered_regions(self.context['request'])
class JsonPageSerializer(PageSerializer):
def rendered_regions(self, obj):
"""Render regions as a json-serializable dictionary."""
return obj.render_json(self.context.get('request'))
class GroupSerializer(mixins.LinksMixin, serializers.HyperlinkedModelSerializer):
url = fields.AbsoluteURLIdentityField()
pages = serializers.SerializerMethodField('get_pages_link')
links_fields = ['pages']
class Meta:
model = models.Group
def get_pages_link(self, obj):
return build_url(
reverse('pages:page-list', request=self.context.get('request')),
{'group': obj.slug},
)
|
Add 'view_name' to url extra kwargs
|
Add 'view_name' to url extra kwargs
|
Python
|
bsd-2-clause
|
incuna/feincms-pages-api
|
from rest_framework import serializers
from rest_framework.reverse import reverse
from pages import fields, mixins, models
from pages.utils import build_url
class PageSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.CharField()
regions = serializers.SerializerMethodField('rendered_regions')
class Meta:
fields = ('id', 'url', 'name', 'slug', 'regions')
model = models.Page
view_name = 'pages:page-detail'
extra_kwargs = {
- 'url': {'lookup_field': 'slug'},
+ 'url': {'lookup_field': 'slug', 'view_name': 'pages:page-detail'},
}
def rendered_regions(self, obj):
return obj.rendered_regions(self.context['request'])
class JsonPageSerializer(PageSerializer):
def rendered_regions(self, obj):
"""Render regions as a json-serializable dictionary."""
return obj.render_json(self.context.get('request'))
class GroupSerializer(mixins.LinksMixin, serializers.HyperlinkedModelSerializer):
url = fields.AbsoluteURLIdentityField()
pages = serializers.SerializerMethodField('get_pages_link')
links_fields = ['pages']
class Meta:
model = models.Group
def get_pages_link(self, obj):
return build_url(
reverse('pages:page-list', request=self.context.get('request')),
{'group': obj.slug},
)
|
Add 'view_name' to url extra kwargs
|
## Code Before:
from rest_framework import serializers
from rest_framework.reverse import reverse
from pages import fields, mixins, models
from pages.utils import build_url
class PageSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.CharField()
regions = serializers.SerializerMethodField('rendered_regions')
class Meta:
fields = ('id', 'url', 'name', 'slug', 'regions')
model = models.Page
view_name = 'pages:page-detail'
extra_kwargs = {
'url': {'lookup_field': 'slug'},
}
def rendered_regions(self, obj):
return obj.rendered_regions(self.context['request'])
class JsonPageSerializer(PageSerializer):
def rendered_regions(self, obj):
"""Render regions as a json-serializable dictionary."""
return obj.render_json(self.context.get('request'))
class GroupSerializer(mixins.LinksMixin, serializers.HyperlinkedModelSerializer):
url = fields.AbsoluteURLIdentityField()
pages = serializers.SerializerMethodField('get_pages_link')
links_fields = ['pages']
class Meta:
model = models.Group
def get_pages_link(self, obj):
return build_url(
reverse('pages:page-list', request=self.context.get('request')),
{'group': obj.slug},
)
## Instruction:
Add 'view_name' to url extra kwargs
## Code After:
from rest_framework import serializers
from rest_framework.reverse import reverse
from pages import fields, mixins, models
from pages.utils import build_url
class PageSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.CharField()
regions = serializers.SerializerMethodField('rendered_regions')
class Meta:
fields = ('id', 'url', 'name', 'slug', 'regions')
model = models.Page
view_name = 'pages:page-detail'
extra_kwargs = {
'url': {'lookup_field': 'slug', 'view_name': 'pages:page-detail'},
}
def rendered_regions(self, obj):
return obj.rendered_regions(self.context['request'])
class JsonPageSerializer(PageSerializer):
def rendered_regions(self, obj):
"""Render regions as a json-serializable dictionary."""
return obj.render_json(self.context.get('request'))
class GroupSerializer(mixins.LinksMixin, serializers.HyperlinkedModelSerializer):
url = fields.AbsoluteURLIdentityField()
pages = serializers.SerializerMethodField('get_pages_link')
links_fields = ['pages']
class Meta:
model = models.Group
def get_pages_link(self, obj):
return build_url(
reverse('pages:page-list', request=self.context.get('request')),
{'group': obj.slug},
)
|
# ... existing code ...
extra_kwargs = {
'url': {'lookup_field': 'slug', 'view_name': 'pages:page-detail'},
}
# ... rest of the code ...
|
10554ed0c44f819985f9f6d1c97a265d281541a2
|
test/test_types.py
|
test/test_types.py
|
""" Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(4567))
|
""" Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertRaises(ValueError,
types.getPieceAbbreviation,
'abcd')
|
Update redundant test to check error handling
|
Update redundant test to check error handling
|
Python
|
mit
|
blairck/jaeger
|
""" Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
- self.assertEqual(None, types.getPieceAbbreviation(4567))
+ self.assertRaises(ValueError,
+ types.getPieceAbbreviation,
+ 'abcd')
+
|
Update redundant test to check error handling
|
## Code Before:
""" Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(4567))
## Instruction:
Update redundant test to check error handling
## Code After:
""" Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertRaises(ValueError,
types.getPieceAbbreviation,
'abcd')
|
# ... existing code ...
"Correctly convert a type to a character for display"
self.assertRaises(ValueError,
types.getPieceAbbreviation,
'abcd')
# ... rest of the code ...
|
6d52364c44cf7244b920d04fe6f5917cd99b7377
|
linkatos/utils.py
|
linkatos/utils.py
|
import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
|
import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
def is_fresh_url(expecting_confirmation, message_type):
return (not expecting_confirmation) and message_type is 'url'
|
Add back is_fresh_url which was deleted by mistake
|
fix: Add back is_fresh_url which was deleted by mistake
|
Python
|
mit
|
iwi/linkatos,iwi/linkatos
|
import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
+
+ def is_fresh_url(expecting_confirmation, message_type):
+ return (not expecting_confirmation) and message_type is 'url'
+
|
Add back is_fresh_url which was deleted by mistake
|
## Code Before:
import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
## Instruction:
Add back is_fresh_url which was deleted by mistake
## Code After:
import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
def is_fresh_url(expecting_confirmation, message_type):
return (not expecting_confirmation) and message_type is 'url'
|
# ... existing code ...
'item_user' in message)
def is_fresh_url(expecting_confirmation, message_type):
return (not expecting_confirmation) and message_type is 'url'
# ... rest of the code ...
|
0167e246b74789cc0181b603520ec7f58ef7b5fe
|
pandas/core/api.py
|
pandas/core/api.py
|
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
|
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
from pandas.core.config import get_option,set_option,reset_option,\
reset_options,describe_options
|
Add new core.config API functions to the pandas top level module
|
ENH: Add new core.config API functions to the pandas top level module
|
Python
|
bsd-3-clause
|
pandas-dev/pandas,GuessWhoSamFoo/pandas,TomAugspurger/pandas,toobaz/pandas,MJuddBooth/pandas,cython-testbed/pandas,TomAugspurger/pandas,nmartensen/pandas,cython-testbed/pandas,DGrady/pandas,DGrady/pandas,datapythonista/pandas,kdebrab/pandas,dsm054/pandas,Winand/pandas,linebp/pandas,dsm054/pandas,toobaz/pandas,jmmease/pandas,zfrenchee/pandas,jorisvandenbossche/pandas,cbertinato/pandas,linebp/pandas,harisbal/pandas,rs2/pandas,linebp/pandas,nmartensen/pandas,jmmease/pandas,jreback/pandas,linebp/pandas,cbertinato/pandas,zfrenchee/pandas,nmartensen/pandas,MJuddBooth/pandas,cython-testbed/pandas,amolkahat/pandas,jmmease/pandas,cython-testbed/pandas,GuessWhoSamFoo/pandas,harisbal/pandas,zfrenchee/pandas,jmmease/pandas,jorisvandenbossche/pandas,GuessWhoSamFoo/pandas,gfyoung/pandas,amolkahat/pandas,pandas-dev/pandas,jreback/pandas,kdebrab/pandas,MJuddBooth/pandas,datapythonista/pandas,pratapvardhan/pandas,amolkahat/pandas,Winand/pandas,cbertinato/pandas,jreback/pandas,gfyoung/pandas,pandas-dev/pandas,jreback/pandas,louispotok/pandas,linebp/pandas,toobaz/pandas,gfyoung/pandas,Winand/pandas,jorisvandenbossche/pandas,rs2/pandas,DGrady/pandas,dsm054/pandas,winklerand/pandas,kdebrab/pandas,winklerand/pandas,TomAugspurger/pandas,datapythonista/pandas,winklerand/pandas,kdebrab/pandas,zfrenchee/pandas,pratapvardhan/pandas,Winand/pandas,TomAugspurger/pandas,datapythonista/pandas,toobaz/pandas,DGrady/pandas,cbertinato/pandas,rs2/pandas,rs2/pandas,DGrady/pandas,toobaz/pandas,gfyoung/pandas,harisbal/pandas,jorisvandenbossche/pandas,nmartensen/pandas,louispotok/pandas,harisbal/pandas,amolkahat/pandas,linebp/pandas,cbertinato/pandas,Winand/pandas,louispotok/pandas,Winand/pandas,pratapvardhan/pandas,nmartensen/pandas,winklerand/pandas,DGrady/pandas,gfyoung/pandas,cython-testbed/pandas,pratapvardhan/pandas,louispotok/pandas,zfrenchee/pandas,MJuddBooth/pandas,GuessWhoSamFoo/pandas,pratapvardhan/pandas,winklerand/pandas,amolkahat/pandas,kdebrab/pandas,pandas-dev/pandas,harisbal/pandas,jreback/pandas,dsm054/pandas,GuessWhoSamFoo/pandas,MJuddBooth/pandas,jmmease/pandas,winklerand/pandas,dsm054/pandas,louispotok/pandas,jmmease/pandas,nmartensen/pandas
|
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
+ from pandas.core.config import get_option,set_option,reset_option,\
+ reset_options,describe_options
+
|
Add new core.config API functions to the pandas top level module
|
## Code Before:
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
## Instruction:
Add new core.config API functions to the pandas top level module
## Code After:
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
from pandas.core.config import get_option,set_option,reset_option,\
reset_options,describe_options
|
// ... existing code ...
import pandas.core.datetools as datetools
from pandas.core.config import get_option,set_option,reset_option,\
reset_options,describe_options
// ... rest of the code ...
|
23ad531d932b6c042c3bd0161b74a6088d02524f
|
myfedora/lib/app_globals.py
|
myfedora/lib/app_globals.py
|
"""The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}}
self.resourceviews = AppFactoryDict() # {name: ResourceView instance}
self.apps = AppFactoryDict() # {name: App instance}
# Our comet data streamer, responsible for polling the data
# streams, and providing data to the widgets
from myfedora.streams import DataStreamer
self.datastreamer = DataStreamer()
|
"""The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}}
self.resourceviews = AppFactoryDict() # {name: ResourceView instance}
self.apps = AppFactoryDict() # {name: App instance}
# Our comet data streamer, responsible for polling the data
# streams, and providing data to the widgets
#from myfedora.streams import DataStreamer
#self.datastreamer = DataStreamer()
FEED_CACHE = "/tmp/moksha-feeds"
from shove import Shove
from feedcache.cache import Cache
# is this not multi-process safe? or even thread safe?
self.feed_storage = Shove('file://' + FEED_CACHE)
self.feed_cache = Cache(self.feed_storage)
|
Add a feed_storage and feed_cache to our Globals object.
|
Add a feed_storage and feed_cache to our Globals object.
|
Python
|
agpl-3.0
|
fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages
|
"""The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}}
self.resourceviews = AppFactoryDict() # {name: ResourceView instance}
self.apps = AppFactoryDict() # {name: App instance}
# Our comet data streamer, responsible for polling the data
# streams, and providing data to the widgets
- from myfedora.streams import DataStreamer
+ #from myfedora.streams import DataStreamer
- self.datastreamer = DataStreamer()
+ #self.datastreamer = DataStreamer()
+ FEED_CACHE = "/tmp/moksha-feeds"
+
+ from shove import Shove
+ from feedcache.cache import Cache
+
+ # is this not multi-process safe? or even thread safe?
+ self.feed_storage = Shove('file://' + FEED_CACHE)
+ self.feed_cache = Cache(self.feed_storage)
+
|
Add a feed_storage and feed_cache to our Globals object.
|
## Code Before:
"""The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}}
self.resourceviews = AppFactoryDict() # {name: ResourceView instance}
self.apps = AppFactoryDict() # {name: App instance}
# Our comet data streamer, responsible for polling the data
# streams, and providing data to the widgets
from myfedora.streams import DataStreamer
self.datastreamer = DataStreamer()
## Instruction:
Add a feed_storage and feed_cache to our Globals object.
## Code After:
"""The application's Globals object"""
from app_factory import AppFactoryDict
class Globals(object):
"""Globals acts as a container for objects available throughout the
life of the application
"""
def __init__(self):
"""One instance of Globals is created during application
initialization and is available during requests via the 'g'
variable
"""
self.widgets = {'home': {}, 'canvas': {}, 'profile': {}, 'preview': {}, 'config':{}} # {viewtype: {name: Widget instance}}
self.resourceviews = AppFactoryDict() # {name: ResourceView instance}
self.apps = AppFactoryDict() # {name: App instance}
# Our comet data streamer, responsible for polling the data
# streams, and providing data to the widgets
#from myfedora.streams import DataStreamer
#self.datastreamer = DataStreamer()
FEED_CACHE = "/tmp/moksha-feeds"
from shove import Shove
from feedcache.cache import Cache
# is this not multi-process safe? or even thread safe?
self.feed_storage = Shove('file://' + FEED_CACHE)
self.feed_cache = Cache(self.feed_storage)
|
...
# streams, and providing data to the widgets
#from myfedora.streams import DataStreamer
#self.datastreamer = DataStreamer()
FEED_CACHE = "/tmp/moksha-feeds"
from shove import Shove
from feedcache.cache import Cache
# is this not multi-process safe? or even thread safe?
self.feed_storage = Shove('file://' + FEED_CACHE)
self.feed_cache = Cache(self.feed_storage)
...
|
f8b28c73e0bb46aaa760d4c4afadd75feacbe57a
|
tools/benchmark/benchmark_date_guessing.py
|
tools/benchmark/benchmark_date_guessing.py
|
import os
import pytest
import sys
from mediawords.tm.guess_date import guess_date, McGuessDateException
def main():
if (len(sys.argv) < 2):
sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>')
exit()
directory = os.fsencode(sys.argv[1]).decode("utf-8")
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory,filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(
url='http://dont.know.the.date/some/path.html',
html=content
)
print(date_guess.date)
main()
|
import os
import sys
from mediawords.tm.guess_date import guess_date
def benchmark_date_guessing():
"""Benchmark Python date guessing code."""
if len(sys.argv) < 2:
sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
directory = sys.argv[1]
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory, filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(url='http://dont.know.the.date/some/path.html',
html=content)
print(date_guess.date)
if __name__ == '__main__':
benchmark_date_guessing()
|
Clean up date guessing benchmarking code
|
Clean up date guessing benchmarking code
* Remove unused imports
* use sys.exit(message) instead of exit()
* Use Pythonic way to call main function (if __name__ == '__main__')
* Reformat code
* Avoid encoding / decoding things to / from UTF-8
|
Python
|
agpl-3.0
|
berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud
|
import os
- import pytest
import sys
- from mediawords.tm.guess_date import guess_date, McGuessDateException
+ from mediawords.tm.guess_date import guess_date
- def main():
- if (len(sys.argv) < 2):
- sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>')
- exit()
- directory = os.fsencode(sys.argv[1]).decode("utf-8")
+ def benchmark_date_guessing():
+ """Benchmark Python date guessing code."""
+ if len(sys.argv) < 2:
+ sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
+
+ directory = sys.argv[1]
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
- fh = open(os.path.join(directory,filename))
+ fh = open(os.path.join(directory, filename))
content = fh.read()
print(filename + ": " + str(len(content)))
- date_guess = guess_date(
- url='http://dont.know.the.date/some/path.html',
+ date_guess = guess_date(url='http://dont.know.the.date/some/path.html',
+ html=content)
- html=content
- )
print(date_guess.date)
- main()
+ if __name__ == '__main__':
+ benchmark_date_guessing()
+
|
Clean up date guessing benchmarking code
|
## Code Before:
import os
import pytest
import sys
from mediawords.tm.guess_date import guess_date, McGuessDateException
def main():
if (len(sys.argv) < 2):
sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>')
exit()
directory = os.fsencode(sys.argv[1]).decode("utf-8")
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory,filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(
url='http://dont.know.the.date/some/path.html',
html=content
)
print(date_guess.date)
main()
## Instruction:
Clean up date guessing benchmarking code
## Code After:
import os
import sys
from mediawords.tm.guess_date import guess_date
def benchmark_date_guessing():
"""Benchmark Python date guessing code."""
if len(sys.argv) < 2:
sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
directory = sys.argv[1]
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory, filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(url='http://dont.know.the.date/some/path.html',
html=content)
print(date_guess.date)
if __name__ == '__main__':
benchmark_date_guessing()
|
...
import os
import sys
...
from mediawords.tm.guess_date import guess_date
def benchmark_date_guessing():
"""Benchmark Python date guessing code."""
if len(sys.argv) < 2:
sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
directory = sys.argv[1]
...
if filename.endswith(".txt"):
fh = open(os.path.join(directory, filename))
content = fh.read()
...
print(filename + ": " + str(len(content)))
date_guess = guess_date(url='http://dont.know.the.date/some/path.html',
html=content)
print(date_guess.date)
...
if __name__ == '__main__':
benchmark_date_guessing()
...
|
57ca59e225119a031dee6b0c10a27c43a41f56ce
|
settings.py
|
settings.py
|
PROTOCOL = "http"
HOSTNAME = "localhost"
AUTHSERVERPORT = 1234
CHARSERVERPORT = 1235
MASTERZONESERVERPORT = 1236
ZONESTARTUPTIME = 10
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f'
ADMINISTRATORS = ['admin']
CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds.
MSPERSEC = 1000
CLIENT_NETWORK_FPS = 10
CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
|
PROTOCOL = "http"
HOSTNAME = "localhost"
AUTHSERVERPORT = 1234
CHARSERVERPORT = 1235
MASTERZONESERVERPORT = 1236
ZONESTARTPORT = 1300
ZONEENDPORT = 1400
ZONESTARTUPTIME = 10
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f'
ADMINISTRATORS = ['admin']
CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds.
MSPERSEC = 1000
CLIENT_NETWORK_FPS = 10
CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
|
Add a zone port range.
|
Add a zone port range.
|
Python
|
agpl-3.0
|
cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO
|
PROTOCOL = "http"
HOSTNAME = "localhost"
AUTHSERVERPORT = 1234
CHARSERVERPORT = 1235
MASTERZONESERVERPORT = 1236
+
+ ZONESTARTPORT = 1300
+ ZONEENDPORT = 1400
ZONESTARTUPTIME = 10
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f'
ADMINISTRATORS = ['admin']
CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds.
MSPERSEC = 1000
CLIENT_NETWORK_FPS = 10
CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
|
Add a zone port range.
|
## Code Before:
PROTOCOL = "http"
HOSTNAME = "localhost"
AUTHSERVERPORT = 1234
CHARSERVERPORT = 1235
MASTERZONESERVERPORT = 1236
ZONESTARTUPTIME = 10
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f'
ADMINISTRATORS = ['admin']
CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds.
MSPERSEC = 1000
CLIENT_NETWORK_FPS = 10
CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
## Instruction:
Add a zone port range.
## Code After:
PROTOCOL = "http"
HOSTNAME = "localhost"
AUTHSERVERPORT = 1234
CHARSERVERPORT = 1235
MASTERZONESERVERPORT = 1236
ZONESTARTPORT = 1300
ZONEENDPORT = 1400
ZONESTARTUPTIME = 10
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S:%f'
ADMINISTRATORS = ['admin']
CLIENT_TIMEOUT = 10 # Client gives up connecting after 10 seconds.
MSPERSEC = 1000
CLIENT_NETWORK_FPS = 10
CLIENT_UPDATE_FREQ = MSPERSEC/CLIENT_NETWORK_FPS
|
# ... existing code ...
MASTERZONESERVERPORT = 1236
ZONESTARTPORT = 1300
ZONEENDPORT = 1400
# ... rest of the code ...
|
fa3605047619495be3ddc3de8a3c3579d57deca4
|
djedi/tests/test_admin.py
|
djedi/tests/test_admin.py
|
from django.core.urlresolvers import reverse
from djedi.tests.base import ClientTest
class PanelTest(ClientTest):
def test_admin_panel(self):
url = reverse('index')
response = self.client.get(url)
self.assertIn(u'Djedi Test', response.content)
self.assertIn(u'window.DJEDI_NODES', response.content)
|
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode
from djedi.tests.base import ClientTest
class PanelTest(ClientTest):
def test_embed(self):
url = reverse('index')
response = self.client.get(url)
self.assertIn(u'Djedi Test', response.content)
self.assertIn(u'window.DJEDI_NODES', response.content)
def test_cms(self):
url = reverse('admin:djedi:cms')
response = self.client.get(url)
self.assertIn(u'<title>djedi cms</title>', response.content)
def test_django_admin(self):
# Patch django admin index
from django.contrib.admin.templatetags.log import AdminLogNode
_render = AdminLogNode.render
AdminLogNode.render = lambda x, y: None
url = reverse('admin:index')
response = self.client.get(url)
cms_url = reverse('admin:djedi:cms')
self.assertIn(u'<a href="%s">CMS</a>' % cms_url, smart_unicode(response.content))
# Rollback patch
AdminLogNode.render = _render
|
Add tests for rendering cms admin
|
Add tests for rendering cms admin
|
Python
|
bsd-3-clause
|
andreif/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms,andreif/djedi-cms,joar/djedi-cms,joar/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms,joar/djedi-cms
|
from django.core.urlresolvers import reverse
+ from django.utils.encoding import smart_unicode
from djedi.tests.base import ClientTest
class PanelTest(ClientTest):
- def test_admin_panel(self):
+ def test_embed(self):
url = reverse('index')
response = self.client.get(url)
self.assertIn(u'Djedi Test', response.content)
self.assertIn(u'window.DJEDI_NODES', response.content)
+ def test_cms(self):
+ url = reverse('admin:djedi:cms')
+ response = self.client.get(url)
+ self.assertIn(u'<title>djedi cms</title>', response.content)
+
+ def test_django_admin(self):
+ # Patch django admin index
+ from django.contrib.admin.templatetags.log import AdminLogNode
+ _render = AdminLogNode.render
+ AdminLogNode.render = lambda x, y: None
+
+ url = reverse('admin:index')
+ response = self.client.get(url)
+ cms_url = reverse('admin:djedi:cms')
+ self.assertIn(u'<a href="%s">CMS</a>' % cms_url, smart_unicode(response.content))
+
+ # Rollback patch
+ AdminLogNode.render = _render
+
|
Add tests for rendering cms admin
|
## Code Before:
from django.core.urlresolvers import reverse
from djedi.tests.base import ClientTest
class PanelTest(ClientTest):
def test_admin_panel(self):
url = reverse('index')
response = self.client.get(url)
self.assertIn(u'Djedi Test', response.content)
self.assertIn(u'window.DJEDI_NODES', response.content)
## Instruction:
Add tests for rendering cms admin
## Code After:
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode
from djedi.tests.base import ClientTest
class PanelTest(ClientTest):
def test_embed(self):
url = reverse('index')
response = self.client.get(url)
self.assertIn(u'Djedi Test', response.content)
self.assertIn(u'window.DJEDI_NODES', response.content)
def test_cms(self):
url = reverse('admin:djedi:cms')
response = self.client.get(url)
self.assertIn(u'<title>djedi cms</title>', response.content)
def test_django_admin(self):
# Patch django admin index
from django.contrib.admin.templatetags.log import AdminLogNode
_render = AdminLogNode.render
AdminLogNode.render = lambda x, y: None
url = reverse('admin:index')
response = self.client.get(url)
cms_url = reverse('admin:djedi:cms')
self.assertIn(u'<a href="%s">CMS</a>' % cms_url, smart_unicode(response.content))
# Rollback patch
AdminLogNode.render = _render
|
...
from django.core.urlresolvers import reverse
from django.utils.encoding import smart_unicode
from djedi.tests.base import ClientTest
...
def test_embed(self):
url = reverse('index')
...
self.assertIn(u'window.DJEDI_NODES', response.content)
def test_cms(self):
url = reverse('admin:djedi:cms')
response = self.client.get(url)
self.assertIn(u'<title>djedi cms</title>', response.content)
def test_django_admin(self):
# Patch django admin index
from django.contrib.admin.templatetags.log import AdminLogNode
_render = AdminLogNode.render
AdminLogNode.render = lambda x, y: None
url = reverse('admin:index')
response = self.client.get(url)
cms_url = reverse('admin:djedi:cms')
self.assertIn(u'<a href="%s">CMS</a>' % cms_url, smart_unicode(response.content))
# Rollback patch
AdminLogNode.render = _render
...
|
f3e0cc4b5a778b04373773dabd27be8782b1af93
|
cosmo_tester/test_suites/snapshots/conftest.py
|
cosmo_tester/test_suites/snapshots/conftest.py
|
import pytest
from cosmo_tester.framework.test_hosts import Hosts
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=3,
)
hosts.instances[0].image_type = request.param
vm = hosts.instances[2]
vm.image_name = test_config.platform['centos_7_image']
vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
yield hosts
finally:
hosts.destroy()
|
import pytest
from cosmo_tester.framework.test_hosts import Hosts, get_image
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=3,
)
hosts.instances[0] = get_image(request.param, test_config)
hosts.instances[1] = get_image('master', test_config)
hosts.instances[2] = get_image('centos', test_config)
vm = hosts.instances[2]
vm.image_name = test_config.platform['centos_7_image']
vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
yield hosts
finally:
hosts.destroy()
|
Use specified images for snapshot fixture
|
Use specified images for snapshot fixture
|
Python
|
apache-2.0
|
cloudify-cosmo/cloudify-system-tests,cloudify-cosmo/cloudify-system-tests
|
import pytest
- from cosmo_tester.framework.test_hosts import Hosts
+ from cosmo_tester.framework.test_hosts import Hosts, get_image
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=3,
)
- hosts.instances[0].image_type = request.param
+ hosts.instances[0] = get_image(request.param, test_config)
+ hosts.instances[1] = get_image('master', test_config)
+ hosts.instances[2] = get_image('centos', test_config)
vm = hosts.instances[2]
vm.image_name = test_config.platform['centos_7_image']
vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
yield hosts
finally:
hosts.destroy()
|
Use specified images for snapshot fixture
|
## Code Before:
import pytest
from cosmo_tester.framework.test_hosts import Hosts
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=3,
)
hosts.instances[0].image_type = request.param
vm = hosts.instances[2]
vm.image_name = test_config.platform['centos_7_image']
vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
yield hosts
finally:
hosts.destroy()
## Instruction:
Use specified images for snapshot fixture
## Code After:
import pytest
from cosmo_tester.framework.test_hosts import Hosts, get_image
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
@pytest.fixture(scope='function', params=get_multi_tenant_versions_list())
def hosts(request, ssh_key, module_tmpdir, test_config, logger):
hosts = Hosts(
ssh_key, module_tmpdir,
test_config, logger, request,
number_of_instances=3,
)
hosts.instances[0] = get_image(request.param, test_config)
hosts.instances[1] = get_image('master', test_config)
hosts.instances[2] = get_image('centos', test_config)
vm = hosts.instances[2]
vm.image_name = test_config.platform['centos_7_image']
vm.username = test_config['test_os_usernames']['centos_7']
hosts.create()
try:
yield hosts
finally:
hosts.destroy()
|
...
from cosmo_tester.framework.test_hosts import Hosts, get_image
from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list
...
hosts.instances[0] = get_image(request.param, test_config)
hosts.instances[1] = get_image('master', test_config)
hosts.instances[2] = get_image('centos', test_config)
...
|
29c20b0a55b0f003a5a5dd83d5d0f177eca6a5c6
|
valuenetwork/valueaccounting/migrations/0013_auto_20180530_2053.py
|
valuenetwork/valueaccounting/migrations/0013_auto_20180530_2053.py
|
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('valueaccounting', '0012_auto_20170717_1841'),
]
operations = [
migrations.AddField(
model_name='process',
name='plan',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='processes', to='valueaccounting.Order', verbose_name='plan'),
),
migrations.AlterField(
model_name='economicresourcetype',
name='behavior',
field=models.CharField(choices=[(b'work', 'Type of Work'), (b'account', 'Virtual Account'), (b'dig_curr', 'Digital Currency'), (b'dig_acct', 'Digital Currency Address'), (b'dig_wallet', 'Digital Currency Wallet'), (b'consumed', 'Produced/Changed + Consumed'), (b'used', 'Produced/Changed + Used'), (b'cited', 'Produced/Changed + Cited'), (b'produced', 'Produced/Changed only'), (b'other', 'Other')], default=b'other', max_length=12, verbose_name='behavior'),
),
]
|
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
#('valueaccounting', '0012_auto_20170717_1841')
('valueaccounting', '0013_auto_20171106_1539'),
]
operations = [
migrations.AddField(
model_name='process',
name='plan',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='processes', to='valueaccounting.Order', verbose_name='plan'),
),
#migrations.AlterField(
# model_name='economicresourcetype',
# name='behavior',
# field=models.CharField(choices=[(b'work', 'Type of Work'), (b'account', 'Virtual Account'), (b'dig_curr', 'Digital Currency'), (b'dig_acct', 'Digital Currency Address'), (b'dig_wallet', 'Digital Currency Wallet'), (b'consumed', 'Produced/Changed + Consumed'), (b'used', 'Produced/Changed + Used'), (b'cited', 'Produced/Changed + Cited'), (b'produced', 'Produced/Changed only'), (b'other', 'Other')], default=b'other', max_length=12, verbose_name='behavior'),
#),
]
|
Fix to migration dependency issue because of missing a migration in the api-extensions branch. Removed duplicate change and changed the dependency.
|
Fix to migration dependency issue because of missing a migration in the api-extensions branch. Removed duplicate change and changed the dependency.
|
Python
|
agpl-3.0
|
FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork
|
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
- ('valueaccounting', '0012_auto_20170717_1841'),
+ #('valueaccounting', '0012_auto_20170717_1841')
+ ('valueaccounting', '0013_auto_20171106_1539'),
]
operations = [
migrations.AddField(
model_name='process',
name='plan',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='processes', to='valueaccounting.Order', verbose_name='plan'),
),
- migrations.AlterField(
+ #migrations.AlterField(
- model_name='economicresourcetype',
+ # model_name='economicresourcetype',
- name='behavior',
+ # name='behavior',
- field=models.CharField(choices=[(b'work', 'Type of Work'), (b'account', 'Virtual Account'), (b'dig_curr', 'Digital Currency'), (b'dig_acct', 'Digital Currency Address'), (b'dig_wallet', 'Digital Currency Wallet'), (b'consumed', 'Produced/Changed + Consumed'), (b'used', 'Produced/Changed + Used'), (b'cited', 'Produced/Changed + Cited'), (b'produced', 'Produced/Changed only'), (b'other', 'Other')], default=b'other', max_length=12, verbose_name='behavior'),
+ # field=models.CharField(choices=[(b'work', 'Type of Work'), (b'account', 'Virtual Account'), (b'dig_curr', 'Digital Currency'), (b'dig_acct', 'Digital Currency Address'), (b'dig_wallet', 'Digital Currency Wallet'), (b'consumed', 'Produced/Changed + Consumed'), (b'used', 'Produced/Changed + Used'), (b'cited', 'Produced/Changed + Cited'), (b'produced', 'Produced/Changed only'), (b'other', 'Other')], default=b'other', max_length=12, verbose_name='behavior'),
- ),
+ #),
]
|
Fix to migration dependency issue because of missing a migration in the api-extensions branch. Removed duplicate change and changed the dependency.
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('valueaccounting', '0012_auto_20170717_1841'),
]
operations = [
migrations.AddField(
model_name='process',
name='plan',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='processes', to='valueaccounting.Order', verbose_name='plan'),
),
migrations.AlterField(
model_name='economicresourcetype',
name='behavior',
field=models.CharField(choices=[(b'work', 'Type of Work'), (b'account', 'Virtual Account'), (b'dig_curr', 'Digital Currency'), (b'dig_acct', 'Digital Currency Address'), (b'dig_wallet', 'Digital Currency Wallet'), (b'consumed', 'Produced/Changed + Consumed'), (b'used', 'Produced/Changed + Used'), (b'cited', 'Produced/Changed + Cited'), (b'produced', 'Produced/Changed only'), (b'other', 'Other')], default=b'other', max_length=12, verbose_name='behavior'),
),
]
## Instruction:
Fix to migration dependency issue because of missing a migration in the api-extensions branch. Removed duplicate change and changed the dependency.
## Code After:
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
#('valueaccounting', '0012_auto_20170717_1841')
('valueaccounting', '0013_auto_20171106_1539'),
]
operations = [
migrations.AddField(
model_name='process',
name='plan',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='processes', to='valueaccounting.Order', verbose_name='plan'),
),
#migrations.AlterField(
# model_name='economicresourcetype',
# name='behavior',
# field=models.CharField(choices=[(b'work', 'Type of Work'), (b'account', 'Virtual Account'), (b'dig_curr', 'Digital Currency'), (b'dig_acct', 'Digital Currency Address'), (b'dig_wallet', 'Digital Currency Wallet'), (b'consumed', 'Produced/Changed + Consumed'), (b'used', 'Produced/Changed + Used'), (b'cited', 'Produced/Changed + Cited'), (b'produced', 'Produced/Changed only'), (b'other', 'Other')], default=b'other', max_length=12, verbose_name='behavior'),
#),
]
|
# ... existing code ...
dependencies = [
#('valueaccounting', '0012_auto_20170717_1841')
('valueaccounting', '0013_auto_20171106_1539'),
]
# ... modified code ...
),
#migrations.AlterField(
# model_name='economicresourcetype',
# name='behavior',
# field=models.CharField(choices=[(b'work', 'Type of Work'), (b'account', 'Virtual Account'), (b'dig_curr', 'Digital Currency'), (b'dig_acct', 'Digital Currency Address'), (b'dig_wallet', 'Digital Currency Wallet'), (b'consumed', 'Produced/Changed + Consumed'), (b'used', 'Produced/Changed + Used'), (b'cited', 'Produced/Changed + Cited'), (b'produced', 'Produced/Changed only'), (b'other', 'Other')], default=b'other', max_length=12, verbose_name='behavior'),
#),
]
# ... rest of the code ...
|
eabe9c25d73a2644b8697f0e9304e61dee5be198
|
src/smdba/roller.py
|
src/smdba/roller.py
|
import time
import sys
import threading
class Roller(threading.Thread):
"""
Roller of some fun sequences while waiting.
"""
def __init__(self):
threading.Thread.__init__(self)
self.__sequence = ['-', '\\', '|', '/',]
self.__freq = .1
self.__offset = 0
self.__running = False
self.__message = None
def run(self):
"""
Run roller.
:return: None
"""
self.__running = True
while self.__running:
if self.__offset > len(self.__sequence) - 1:
self.__offset = 0
sys.stdout.write("\b" + self.__sequence[self.__offset])
sys.stdout.flush()
time.sleep(self.__freq)
self.__offset += 1
print("\b" + self.__message)
sys.stdout.flush()
def stop(self, message: str = None):
"""
Stop roller.
:param message: Message for the roller.
:return: None
"""
self.__message = message if message else " "
self.__running = False
self.__offset = 0
# if __name__ == '__main__':
# print("Doing thing:\t", end="")
# sys.stdout.flush()
#
# roller = Roller()
# roller.start()
# time.sleep(5)
# roller.stop("finished")
# time.sleep(1)
# print("OK")
|
import time
import sys
import threading
import typing
class Roller(threading.Thread):
"""
Roller of some fun sequences while waiting.
"""
def __init__(self) -> None:
threading.Thread.__init__(self)
self.__sequence = ['-', '\\', '|', '/',]
self.__freq = .1
self.__offset = 0
self.__running = False
self.__message: typing.Optional[str] = None
def run(self) -> None:
"""
Run roller.
:return: None
"""
self.__running = True
while self.__running:
if self.__offset > len(self.__sequence) - 1:
self.__offset = 0
sys.stdout.write("\b" + self.__sequence[self.__offset])
sys.stdout.flush()
time.sleep(self.__freq)
self.__offset += 1
print("\b" + self.__message)
sys.stdout.flush()
def stop(self, message: typing.Optional[str] = None) -> None:
"""
Stop roller.
:param message: Message for the roller.
:return: None
"""
self.__message = message if message else " "
self.__running = False
self.__offset = 0
# if __name__ == '__main__':
# print("Doing thing:\t", end="")
# sys.stdout.flush()
#
# roller = Roller()
# roller.start()
# time.sleep(5)
# roller.stop("finished")
# time.sleep(1)
# print("OK")
|
Add annotations to the methods
|
Add annotations to the methods
|
Python
|
mit
|
SUSE/smdba,SUSE/smdba
|
import time
import sys
import threading
+ import typing
class Roller(threading.Thread):
"""
Roller of some fun sequences while waiting.
"""
- def __init__(self):
+ def __init__(self) -> None:
threading.Thread.__init__(self)
self.__sequence = ['-', '\\', '|', '/',]
self.__freq = .1
self.__offset = 0
self.__running = False
- self.__message = None
+ self.__message: typing.Optional[str] = None
- def run(self):
+ def run(self) -> None:
"""
Run roller.
:return: None
"""
self.__running = True
while self.__running:
if self.__offset > len(self.__sequence) - 1:
self.__offset = 0
sys.stdout.write("\b" + self.__sequence[self.__offset])
sys.stdout.flush()
time.sleep(self.__freq)
self.__offset += 1
print("\b" + self.__message)
sys.stdout.flush()
- def stop(self, message: str = None):
+ def stop(self, message: typing.Optional[str] = None) -> None:
"""
Stop roller.
:param message: Message for the roller.
:return: None
"""
self.__message = message if message else " "
self.__running = False
self.__offset = 0
# if __name__ == '__main__':
# print("Doing thing:\t", end="")
# sys.stdout.flush()
#
# roller = Roller()
# roller.start()
# time.sleep(5)
# roller.stop("finished")
# time.sleep(1)
# print("OK")
|
Add annotations to the methods
|
## Code Before:
import time
import sys
import threading
class Roller(threading.Thread):
"""
Roller of some fun sequences while waiting.
"""
def __init__(self):
threading.Thread.__init__(self)
self.__sequence = ['-', '\\', '|', '/',]
self.__freq = .1
self.__offset = 0
self.__running = False
self.__message = None
def run(self):
"""
Run roller.
:return: None
"""
self.__running = True
while self.__running:
if self.__offset > len(self.__sequence) - 1:
self.__offset = 0
sys.stdout.write("\b" + self.__sequence[self.__offset])
sys.stdout.flush()
time.sleep(self.__freq)
self.__offset += 1
print("\b" + self.__message)
sys.stdout.flush()
def stop(self, message: str = None):
"""
Stop roller.
:param message: Message for the roller.
:return: None
"""
self.__message = message if message else " "
self.__running = False
self.__offset = 0
# if __name__ == '__main__':
# print("Doing thing:\t", end="")
# sys.stdout.flush()
#
# roller = Roller()
# roller.start()
# time.sleep(5)
# roller.stop("finished")
# time.sleep(1)
# print("OK")
## Instruction:
Add annotations to the methods
## Code After:
import time
import sys
import threading
import typing
class Roller(threading.Thread):
"""
Roller of some fun sequences while waiting.
"""
def __init__(self) -> None:
threading.Thread.__init__(self)
self.__sequence = ['-', '\\', '|', '/',]
self.__freq = .1
self.__offset = 0
self.__running = False
self.__message: typing.Optional[str] = None
def run(self) -> None:
"""
Run roller.
:return: None
"""
self.__running = True
while self.__running:
if self.__offset > len(self.__sequence) - 1:
self.__offset = 0
sys.stdout.write("\b" + self.__sequence[self.__offset])
sys.stdout.flush()
time.sleep(self.__freq)
self.__offset += 1
print("\b" + self.__message)
sys.stdout.flush()
def stop(self, message: typing.Optional[str] = None) -> None:
"""
Stop roller.
:param message: Message for the roller.
:return: None
"""
self.__message = message if message else " "
self.__running = False
self.__offset = 0
# if __name__ == '__main__':
# print("Doing thing:\t", end="")
# sys.stdout.flush()
#
# roller = Roller()
# roller.start()
# time.sleep(5)
# roller.stop("finished")
# time.sleep(1)
# print("OK")
|
// ... existing code ...
import threading
import typing
// ... modified code ...
def __init__(self) -> None:
threading.Thread.__init__(self)
...
self.__running = False
self.__message: typing.Optional[str] = None
def run(self) -> None:
"""
...
def stop(self, message: typing.Optional[str] = None) -> None:
"""
// ... rest of the code ...
|
f566e0e36269ea2cd1e82c6af712097917effd4a
|
dlrn/migrations/versions/2d503b5034b7_rename_artifacts.py
|
dlrn/migrations/versions/2d503b5034b7_rename_artifacts.py
|
from alembic import op
# revision identifiers, used by Alembic.
revision = '2d503b5034b7'
down_revision = '2a0313a8a7d6'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('rpms', new_column_name='artifacts')
def downgrade():
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('artifacts', new_column_name='rpms')
|
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d503b5034b7'
down_revision = '2a0313a8a7d6'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('rpms', existing_type=sa.Text(),
new_column_name='artifacts')
def downgrade():
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('artifacts', existing_type=sa.Text(),
new_column_name='rpms')
|
Fix alembic migration for rpms->artifacts rename
|
Fix alembic migration for rpms->artifacts rename
The migration does not work on MySQL-based engines, because it
requires setting the existing_type parameter [1]. It worked fine
on SQLite, though.
[1] - https://alembic.sqlalchemy.org/en/latest/ops.html#alembic.operations.Operations.alter_column
Change-Id: If0cc05af843e3db5f4b2e501caa8f4f773b24509
|
Python
|
apache-2.0
|
openstack-packages/delorean,openstack-packages/delorean,openstack-packages/DLRN,openstack-packages/DLRN
|
from alembic import op
+ import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d503b5034b7'
down_revision = '2a0313a8a7d6'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("commits") as batch_op:
- batch_op.alter_column('rpms', new_column_name='artifacts')
+ batch_op.alter_column('rpms', existing_type=sa.Text(),
+ new_column_name='artifacts')
def downgrade():
with op.batch_alter_table("commits") as batch_op:
- batch_op.alter_column('artifacts', new_column_name='rpms')
+ batch_op.alter_column('artifacts', existing_type=sa.Text(),
+ new_column_name='rpms')
|
Fix alembic migration for rpms->artifacts rename
|
## Code Before:
from alembic import op
# revision identifiers, used by Alembic.
revision = '2d503b5034b7'
down_revision = '2a0313a8a7d6'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('rpms', new_column_name='artifacts')
def downgrade():
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('artifacts', new_column_name='rpms')
## Instruction:
Fix alembic migration for rpms->artifacts rename
## Code After:
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d503b5034b7'
down_revision = '2a0313a8a7d6'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('rpms', existing_type=sa.Text(),
new_column_name='artifacts')
def downgrade():
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('artifacts', existing_type=sa.Text(),
new_column_name='rpms')
|
// ... existing code ...
from alembic import op
import sqlalchemy as sa
// ... modified code ...
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('rpms', existing_type=sa.Text(),
new_column_name='artifacts')
...
with op.batch_alter_table("commits") as batch_op:
batch_op.alter_column('artifacts', existing_type=sa.Text(),
new_column_name='rpms')
// ... rest of the code ...
|
cca6a727063c63d78d61ee81c892811238139462
|
lame_test.py
|
lame_test.py
|
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
for attr in dir(api):
if attr.startswith("_"): continue
if attr in exclude: continue
f = getattr(api, attr)
print attr
try:
f()
except TypeError:
f("query")
|
import datetime
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
dates = (datetime.datetime.now().year, datetime.datetime.now().date().isocalendar()[1])
args_map = {
'announcements_by_week': dates,
'menu_by_week': dates,
'notes_by_week': dates,
'course': ('CS', '486'),
'course_examschedule': ('CS', '486'),
'course_prerequistes': ('CS', '486'),
'course_schedule': ('CS', '486'),
'course_by_building_room': ('MC', '2038'),
'term_course_schedule': ('1141', 'CS', '486'),
'term_subject_schedule': ('1141', 'CS'),
}
for attr in dir(api):
if attr.startswith("_"): continue
if attr in exclude: continue
f = getattr(api, attr)
print(attr)
try:
f()
except TypeError:
try:
args = ("query",)
if attr in args_map:
args = args_map[attr]
f(*args)
except Exception as e:
print(e.message)
except Exception as e:
print(e.message)
|
Update lame test to test on multiple parameters.
|
Update lame test to test on multiple parameters.
|
Python
|
mit
|
albertoconnor/uwaterlooapi
|
+ import datetime
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
+
+ dates = (datetime.datetime.now().year, datetime.datetime.now().date().isocalendar()[1])
+
+
+ args_map = {
+ 'announcements_by_week': dates,
+ 'menu_by_week': dates,
+ 'notes_by_week': dates,
+ 'course': ('CS', '486'),
+ 'course_examschedule': ('CS', '486'),
+ 'course_prerequistes': ('CS', '486'),
+ 'course_schedule': ('CS', '486'),
+ 'course_by_building_room': ('MC', '2038'),
+ 'term_course_schedule': ('1141', 'CS', '486'),
+ 'term_subject_schedule': ('1141', 'CS'),
+ }
+
for attr in dir(api):
if attr.startswith("_"): continue
if attr in exclude: continue
f = getattr(api, attr)
- print attr
+ print(attr)
try:
f()
except TypeError:
- f("query")
+ try:
+ args = ("query",)
+ if attr in args_map:
+ args = args_map[attr]
+ f(*args)
+ except Exception as e:
+ print(e.message)
+ except Exception as e:
+ print(e.message)
|
Update lame test to test on multiple parameters.
|
## Code Before:
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
for attr in dir(api):
if attr.startswith("_"): continue
if attr in exclude: continue
f = getattr(api, attr)
print attr
try:
f()
except TypeError:
f("query")
## Instruction:
Update lame test to test on multiple parameters.
## Code After:
import datetime
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
dates = (datetime.datetime.now().year, datetime.datetime.now().date().isocalendar()[1])
args_map = {
'announcements_by_week': dates,
'menu_by_week': dates,
'notes_by_week': dates,
'course': ('CS', '486'),
'course_examschedule': ('CS', '486'),
'course_prerequistes': ('CS', '486'),
'course_schedule': ('CS', '486'),
'course_by_building_room': ('MC', '2038'),
'term_course_schedule': ('1141', 'CS', '486'),
'term_subject_schedule': ('1141', 'CS'),
}
for attr in dir(api):
if attr.startswith("_"): continue
if attr in exclude: continue
f = getattr(api, attr)
print(attr)
try:
f()
except TypeError:
try:
args = ("query",)
if attr in args_map:
args = args_map[attr]
f(*args)
except Exception as e:
print(e.message)
except Exception as e:
print(e.message)
|
# ... existing code ...
import datetime
# ... modified code ...
dates = (datetime.datetime.now().year, datetime.datetime.now().date().isocalendar()[1])
args_map = {
'announcements_by_week': dates,
'menu_by_week': dates,
'notes_by_week': dates,
'course': ('CS', '486'),
'course_examschedule': ('CS', '486'),
'course_prerequistes': ('CS', '486'),
'course_schedule': ('CS', '486'),
'course_by_building_room': ('MC', '2038'),
'term_course_schedule': ('1141', 'CS', '486'),
'term_subject_schedule': ('1141', 'CS'),
}
for attr in dir(api):
...
f = getattr(api, attr)
print(attr)
try:
...
except TypeError:
try:
args = ("query",)
if attr in args_map:
args = args_map[attr]
f(*args)
except Exception as e:
print(e.message)
except Exception as e:
print(e.message)
# ... rest of the code ...
|
e79c90db5dcda56ff9b2b154659984db9c6f7663
|
src/main.py
|
src/main.py
|
import pygame
from scenes import director
from scenes import intro_scene
pygame.init()
def main():
game_director = director.Director()
scene = intro_scene.IntroScene(game_director)
game_director.change_scene(scene)
game_director.loop()
if __name__ == '__main__':
pygame.init()
main()
|
import pygame
from scenes import director
from scenes import intro_scene
from game_logic import settings
pygame.init()
def main():
initial_settings = settings.Settings(
trials=1000, player='O', oponent='Computer')
game_director = director.Director()
scene = intro_scene.IntroScene(game_director)
game_director.change_scene(scene, initial_settings)
game_director.loop()
if __name__ == '__main__':
pygame.init()
main()
|
Create initial config when starting game
|
Create initial config when starting game
|
Python
|
mit
|
juangallostra/TicTacToe
|
import pygame
from scenes import director
from scenes import intro_scene
+ from game_logic import settings
pygame.init()
def main():
+ initial_settings = settings.Settings(
+ trials=1000, player='O', oponent='Computer')
game_director = director.Director()
scene = intro_scene.IntroScene(game_director)
- game_director.change_scene(scene)
+ game_director.change_scene(scene, initial_settings)
game_director.loop()
if __name__ == '__main__':
pygame.init()
main()
|
Create initial config when starting game
|
## Code Before:
import pygame
from scenes import director
from scenes import intro_scene
pygame.init()
def main():
game_director = director.Director()
scene = intro_scene.IntroScene(game_director)
game_director.change_scene(scene)
game_director.loop()
if __name__ == '__main__':
pygame.init()
main()
## Instruction:
Create initial config when starting game
## Code After:
import pygame
from scenes import director
from scenes import intro_scene
from game_logic import settings
pygame.init()
def main():
initial_settings = settings.Settings(
trials=1000, player='O', oponent='Computer')
game_director = director.Director()
scene = intro_scene.IntroScene(game_director)
game_director.change_scene(scene, initial_settings)
game_director.loop()
if __name__ == '__main__':
pygame.init()
main()
|
# ... existing code ...
from scenes import intro_scene
from game_logic import settings
# ... modified code ...
def main():
initial_settings = settings.Settings(
trials=1000, player='O', oponent='Computer')
game_director = director.Director()
...
scene = intro_scene.IntroScene(game_director)
game_director.change_scene(scene, initial_settings)
game_director.loop()
# ... rest of the code ...
|
f8a209e7b0cca0fb6cd7bd49fa4f024c472b4e13
|
zappa/ext/django_zappa.py
|
zappa/ext/django_zappa.py
|
import sys
# add the Lambda root path into the sys.path
sys.path.append('/var/task')
from django.core.handlers.wsgi import WSGIHandler
from django.core.wsgi import get_wsgi_application
import os
def get_django_wsgi(settings_module):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
import django
django.setup()
return get_wsgi_application()
|
import os
import sys
# add the Lambda root path into the sys.path
sys.path.append('/var/task')
def get_django_wsgi(settings_module):
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
import django
if django.VERSION[0] <= 1 and django.VERSION[1] < 7:
# call django.setup only for django <1.7.0
# (because setup already in get_wsgi_application since that)
# https://github.com/django/django/commit/80d74097b4bd7186ad99b6d41d0ed90347a39b21
django.setup()
return get_wsgi_application()
|
Call django.setup() from zappa only for django < 1.7.0
|
Call django.setup() from zappa only for django < 1.7.0
* because since django 1.7 it leads to double initialization, which is problematic on some installations
|
Python
|
mit
|
scoates/Zappa,Miserlou/Zappa,anush0247/Zappa,mathom/Zappa,michi88/Zappa,parroyo/Zappa,anush0247/Zappa,longzhi/Zappa,Miserlou/Zappa,longzhi/Zappa,scoates/Zappa,pjz/Zappa,pjz/Zappa,parroyo/Zappa,mathom/Zappa,michi88/Zappa
|
+ import os
import sys
# add the Lambda root path into the sys.path
sys.path.append('/var/task')
- from django.core.handlers.wsgi import WSGIHandler
- from django.core.wsgi import get_wsgi_application
- import os
def get_django_wsgi(settings_module):
+ from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
import django
+
+ if django.VERSION[0] <= 1 and django.VERSION[1] < 7:
+ # call django.setup only for django <1.7.0
+ # (because setup already in get_wsgi_application since that)
+ # https://github.com/django/django/commit/80d74097b4bd7186ad99b6d41d0ed90347a39b21
- django.setup()
+ django.setup()
return get_wsgi_application()
+
|
Call django.setup() from zappa only for django < 1.7.0
|
## Code Before:
import sys
# add the Lambda root path into the sys.path
sys.path.append('/var/task')
from django.core.handlers.wsgi import WSGIHandler
from django.core.wsgi import get_wsgi_application
import os
def get_django_wsgi(settings_module):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
import django
django.setup()
return get_wsgi_application()
## Instruction:
Call django.setup() from zappa only for django < 1.7.0
## Code After:
import os
import sys
# add the Lambda root path into the sys.path
sys.path.append('/var/task')
def get_django_wsgi(settings_module):
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
import django
if django.VERSION[0] <= 1 and django.VERSION[1] < 7:
# call django.setup only for django <1.7.0
# (because setup already in get_wsgi_application since that)
# https://github.com/django/django/commit/80d74097b4bd7186ad99b6d41d0ed90347a39b21
django.setup()
return get_wsgi_application()
|
# ... existing code ...
import os
import sys
# ... modified code ...
...
def get_django_wsgi(settings_module):
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
...
import django
if django.VERSION[0] <= 1 and django.VERSION[1] < 7:
# call django.setup only for django <1.7.0
# (because setup already in get_wsgi_application since that)
# https://github.com/django/django/commit/80d74097b4bd7186ad99b6d41d0ed90347a39b21
django.setup()
# ... rest of the code ...
|
d3992b1677a5186b8b4072c9fdf50e4cb44dc5ef
|
base_accounts/models.py
|
base_accounts/models.py
|
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
class BaseUser(AbstractUser):
slug = models.SlugField(_('slug'), max_length=255)
name = models.CharField(_('name'), max_length=255, blank=True)
first_login = models.BooleanField(_('first login'), default=True)
image = models.ImageField(_('image'), blank=True, null=True, upload_to="images/avatars/%Y/%m/%d", max_length=255)
class Meta:
abstract = True
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.username)
if not self.name.strip():
self.name = "%s %s" % (self.first_name, self.last_name)
super(BaseUser, self).save(*args, **kwargs)
def get_display_name(self):
return self.name or self.username
|
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
class BaseUser(AbstractUser):
slug = models.SlugField(_('slug'), max_length=255)
name = models.CharField(_('name'), max_length=255, blank=True)
first_login = models.BooleanField(_('first login'), default=True)
image = models.ImageField(_('image'), blank=True, null=True, upload_to="images/avatars/%Y/%m/%d", max_length=255)
class Meta:
abstract = True
def save(self, *args, **kwargs):
# Create slug from username. Altough field is not unique at database
# level, it will be as long as username stays unique as well.
if not self.id:
self.slug = slugify(self.username)
# Assign username as name if empty
if not self.name.strip():
if not self.first_name:
self.first_name = self.username
name = "%s %s" % (self.first_name, self.last_name)
self.name = name.strip()
super(BaseUser, self).save(*args, **kwargs)
def get_display_name(self):
return self.name or self.username
|
Fix name field for empty values
|
Fix name field for empty values
|
Python
|
bsd-3-clause
|
Nomadblue/django-nomad-base-accounts,Nomadblue/django-nomad-base-accounts
|
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
class BaseUser(AbstractUser):
slug = models.SlugField(_('slug'), max_length=255)
name = models.CharField(_('name'), max_length=255, blank=True)
first_login = models.BooleanField(_('first login'), default=True)
image = models.ImageField(_('image'), blank=True, null=True, upload_to="images/avatars/%Y/%m/%d", max_length=255)
class Meta:
abstract = True
def save(self, *args, **kwargs):
+
+ # Create slug from username. Altough field is not unique at database
+ # level, it will be as long as username stays unique as well.
if not self.id:
self.slug = slugify(self.username)
+
+ # Assign username as name if empty
if not self.name.strip():
+ if not self.first_name:
+ self.first_name = self.username
- self.name = "%s %s" % (self.first_name, self.last_name)
+ name = "%s %s" % (self.first_name, self.last_name)
+ self.name = name.strip()
+
super(BaseUser, self).save(*args, **kwargs)
def get_display_name(self):
return self.name or self.username
|
Fix name field for empty values
|
## Code Before:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
class BaseUser(AbstractUser):
slug = models.SlugField(_('slug'), max_length=255)
name = models.CharField(_('name'), max_length=255, blank=True)
first_login = models.BooleanField(_('first login'), default=True)
image = models.ImageField(_('image'), blank=True, null=True, upload_to="images/avatars/%Y/%m/%d", max_length=255)
class Meta:
abstract = True
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.username)
if not self.name.strip():
self.name = "%s %s" % (self.first_name, self.last_name)
super(BaseUser, self).save(*args, **kwargs)
def get_display_name(self):
return self.name or self.username
## Instruction:
Fix name field for empty values
## Code After:
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
class BaseUser(AbstractUser):
slug = models.SlugField(_('slug'), max_length=255)
name = models.CharField(_('name'), max_length=255, blank=True)
first_login = models.BooleanField(_('first login'), default=True)
image = models.ImageField(_('image'), blank=True, null=True, upload_to="images/avatars/%Y/%m/%d", max_length=255)
class Meta:
abstract = True
def save(self, *args, **kwargs):
# Create slug from username. Altough field is not unique at database
# level, it will be as long as username stays unique as well.
if not self.id:
self.slug = slugify(self.username)
# Assign username as name if empty
if not self.name.strip():
if not self.first_name:
self.first_name = self.username
name = "%s %s" % (self.first_name, self.last_name)
self.name = name.strip()
super(BaseUser, self).save(*args, **kwargs)
def get_display_name(self):
return self.name or self.username
|
# ... existing code ...
def save(self, *args, **kwargs):
# Create slug from username. Altough field is not unique at database
# level, it will be as long as username stays unique as well.
if not self.id:
# ... modified code ...
self.slug = slugify(self.username)
# Assign username as name if empty
if not self.name.strip():
if not self.first_name:
self.first_name = self.username
name = "%s %s" % (self.first_name, self.last_name)
self.name = name.strip()
super(BaseUser, self).save(*args, **kwargs)
# ... rest of the code ...
|
4ce7f8ce338c84b44e7ad16475ff68bc0fad970e
|
dddp/accounts/tests.py
|
dddp/accounts/tests.py
|
"""Django DDP Accounts test suite."""
from __future__ import unicode_literals
import sys
from dddp import tests
class AccountsTestCase(tests.DDPServerTestCase):
# gevent-websocket doesn't work with Python 3 yet
@tests.expected_failure_if(sys.version_info.major == 3)
def test_login_no_accounts(self):
sockjs = self.server.sockjs('/sockjs/1/a/websocket')
resp = sockjs.websocket.recv()
self.assertEqual(resp, 'o')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'server_id': '0'},
],
)
sockjs.connect('1', 'pre2', 'pre1')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'msg': 'connected', 'session': msgs[0]['session']},
],
)
id_ = sockjs.call(
'login', {'user': '[email protected]', 'password': 'foo'},
)
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{
'msg': 'result', 'id': id_,
'error': {
'error': 403, 'reason': 'Authentication failed.',
},
},
],
)
sockjs.close()
|
"""Django DDP Accounts test suite."""
from __future__ import unicode_literals
import sys
from dddp import tests
# gevent-websocket doesn't work with Python 3 yet
@tests.expected_failure_if(sys.version_info.major == 3)
class AccountsTestCase(tests.DDPServerTestCase):
def test_login_no_accounts(self):
sockjs = self.server.sockjs('/sockjs/1/a/websocket')
resp = sockjs.websocket.recv()
self.assertEqual(resp, 'o')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'server_id': '0'},
],
)
sockjs.connect('1', 'pre2', 'pre1')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'msg': 'connected', 'session': msgs[0]['session']},
],
)
id_ = sockjs.call(
'login', {'user': '[email protected]', 'password': 'foo'},
)
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{
'msg': 'result', 'id': id_,
'error': {
'error': 403, 'reason': 'Authentication failed.',
},
},
],
)
sockjs.close()
|
Move expected test failure to TestCase class.
|
Move expected test failure to TestCase class.
|
Python
|
mit
|
commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp
|
"""Django DDP Accounts test suite."""
from __future__ import unicode_literals
import sys
from dddp import tests
+ # gevent-websocket doesn't work with Python 3 yet
+ @tests.expected_failure_if(sys.version_info.major == 3)
class AccountsTestCase(tests.DDPServerTestCase):
- # gevent-websocket doesn't work with Python 3 yet
- @tests.expected_failure_if(sys.version_info.major == 3)
def test_login_no_accounts(self):
sockjs = self.server.sockjs('/sockjs/1/a/websocket')
resp = sockjs.websocket.recv()
self.assertEqual(resp, 'o')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'server_id': '0'},
],
)
sockjs.connect('1', 'pre2', 'pre1')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'msg': 'connected', 'session': msgs[0]['session']},
],
)
id_ = sockjs.call(
'login', {'user': '[email protected]', 'password': 'foo'},
)
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{
'msg': 'result', 'id': id_,
'error': {
'error': 403, 'reason': 'Authentication failed.',
},
},
],
)
sockjs.close()
|
Move expected test failure to TestCase class.
|
## Code Before:
"""Django DDP Accounts test suite."""
from __future__ import unicode_literals
import sys
from dddp import tests
class AccountsTestCase(tests.DDPServerTestCase):
# gevent-websocket doesn't work with Python 3 yet
@tests.expected_failure_if(sys.version_info.major == 3)
def test_login_no_accounts(self):
sockjs = self.server.sockjs('/sockjs/1/a/websocket')
resp = sockjs.websocket.recv()
self.assertEqual(resp, 'o')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'server_id': '0'},
],
)
sockjs.connect('1', 'pre2', 'pre1')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'msg': 'connected', 'session': msgs[0]['session']},
],
)
id_ = sockjs.call(
'login', {'user': '[email protected]', 'password': 'foo'},
)
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{
'msg': 'result', 'id': id_,
'error': {
'error': 403, 'reason': 'Authentication failed.',
},
},
],
)
sockjs.close()
## Instruction:
Move expected test failure to TestCase class.
## Code After:
"""Django DDP Accounts test suite."""
from __future__ import unicode_literals
import sys
from dddp import tests
# gevent-websocket doesn't work with Python 3 yet
@tests.expected_failure_if(sys.version_info.major == 3)
class AccountsTestCase(tests.DDPServerTestCase):
def test_login_no_accounts(self):
sockjs = self.server.sockjs('/sockjs/1/a/websocket')
resp = sockjs.websocket.recv()
self.assertEqual(resp, 'o')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'server_id': '0'},
],
)
sockjs.connect('1', 'pre2', 'pre1')
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{'msg': 'connected', 'session': msgs[0]['session']},
],
)
id_ = sockjs.call(
'login', {'user': '[email protected]', 'password': 'foo'},
)
msgs = sockjs.recv()
self.assertEqual(
msgs, [
{
'msg': 'result', 'id': id_,
'error': {
'error': 403, 'reason': 'Authentication failed.',
},
},
],
)
sockjs.close()
|
...
# gevent-websocket doesn't work with Python 3 yet
@tests.expected_failure_if(sys.version_info.major == 3)
class AccountsTestCase(tests.DDPServerTestCase):
...
def test_login_no_accounts(self):
...
|
efd1841fb904e30ac0b87b7c7d019f2745452cb2
|
test_output.py
|
test_output.py
|
import unittest
from conftest import BaseTest
class TestSafariRS(BaseTest):
def test_urls_all_flag_is_deprecated(self):
result = self.run_safari_rs('urls-all')
self.assertIn('deprecated', result.stderr)
def test_list_tabs_flag_is_not_deprecated(self):
result = self.run_safari_rs('list-tabs')
self.assertNotIn('deprecated', result.stderr)
def test_no_extra_whitespace_on_tidy_url(self):
result = self.run_safari_rs('tidy-url', 'https://github.com/alexwlchan/safari.rs/issues')
assert result.rc == 0
assert result.stderr == ''
assert result.stdout.strip() == result.stdout
if __name__ == '__main__':
unittest.main()
|
import unittest
from conftest import BaseTest
class TestSafariRS(BaseTest):
def test_urls_all_flag_is_deprecated(self):
result = self.run_safari_rs('urls-all')
self.assertIn('deprecated', result.stderr)
def test_list_tabs_flag_is_not_deprecated(self):
result = self.run_safari_rs('list-tabs')
self.assertNotIn('deprecated', result.stderr)
def test_no_extra_whitespace_on_tidy_url(self):
result = self.run_safari_rs('tidy-url', 'https://github.com/alexwlchan/safari.rs/issues')
assert result.rc == 0
assert result.stderr == ''
assert result.stdout.strip() == result.stdout
def _assert_resolve_tco(self, url, expected):
result = self.run_safari_rs('resolve', url)
assert result.rc == 0
assert result.stderr == ''
assert result.stdout == expected
def test_resolve_single_redirect(self):
self._assert_resolve_tco('https://t.co/2pciHpqpwC', 'https://donmelton.com/2013/06/04/remembering-penny/')
def test_resolve_multiple_redirect(self):
self._assert_resolve_tco('https://t.co/oSJaiNlIP6', 'https://bitly.com/blog/backlinking-strategy/')
def test_resolve_no_redirect(self):
self._assert_resolve_tco('https://example.org/', 'https://example.org/')
if __name__ == '__main__':
unittest.main()
|
Add some tests for the URL resolver
|
Add some tests for the URL resolver
|
Python
|
mit
|
alexwlchan/safari.rs,alexwlchan/safari.rs
|
import unittest
from conftest import BaseTest
class TestSafariRS(BaseTest):
def test_urls_all_flag_is_deprecated(self):
result = self.run_safari_rs('urls-all')
self.assertIn('deprecated', result.stderr)
def test_list_tabs_flag_is_not_deprecated(self):
result = self.run_safari_rs('list-tabs')
self.assertNotIn('deprecated', result.stderr)
def test_no_extra_whitespace_on_tidy_url(self):
result = self.run_safari_rs('tidy-url', 'https://github.com/alexwlchan/safari.rs/issues')
assert result.rc == 0
assert result.stderr == ''
assert result.stdout.strip() == result.stdout
+ def _assert_resolve_tco(self, url, expected):
+ result = self.run_safari_rs('resolve', url)
+ assert result.rc == 0
+ assert result.stderr == ''
+ assert result.stdout == expected
+
+ def test_resolve_single_redirect(self):
+ self._assert_resolve_tco('https://t.co/2pciHpqpwC', 'https://donmelton.com/2013/06/04/remembering-penny/')
+
+ def test_resolve_multiple_redirect(self):
+ self._assert_resolve_tco('https://t.co/oSJaiNlIP6', 'https://bitly.com/blog/backlinking-strategy/')
+
+ def test_resolve_no_redirect(self):
+ self._assert_resolve_tco('https://example.org/', 'https://example.org/')
+
if __name__ == '__main__':
unittest.main()
|
Add some tests for the URL resolver
|
## Code Before:
import unittest
from conftest import BaseTest
class TestSafariRS(BaseTest):
def test_urls_all_flag_is_deprecated(self):
result = self.run_safari_rs('urls-all')
self.assertIn('deprecated', result.stderr)
def test_list_tabs_flag_is_not_deprecated(self):
result = self.run_safari_rs('list-tabs')
self.assertNotIn('deprecated', result.stderr)
def test_no_extra_whitespace_on_tidy_url(self):
result = self.run_safari_rs('tidy-url', 'https://github.com/alexwlchan/safari.rs/issues')
assert result.rc == 0
assert result.stderr == ''
assert result.stdout.strip() == result.stdout
if __name__ == '__main__':
unittest.main()
## Instruction:
Add some tests for the URL resolver
## Code After:
import unittest
from conftest import BaseTest
class TestSafariRS(BaseTest):
def test_urls_all_flag_is_deprecated(self):
result = self.run_safari_rs('urls-all')
self.assertIn('deprecated', result.stderr)
def test_list_tabs_flag_is_not_deprecated(self):
result = self.run_safari_rs('list-tabs')
self.assertNotIn('deprecated', result.stderr)
def test_no_extra_whitespace_on_tidy_url(self):
result = self.run_safari_rs('tidy-url', 'https://github.com/alexwlchan/safari.rs/issues')
assert result.rc == 0
assert result.stderr == ''
assert result.stdout.strip() == result.stdout
def _assert_resolve_tco(self, url, expected):
result = self.run_safari_rs('resolve', url)
assert result.rc == 0
assert result.stderr == ''
assert result.stdout == expected
def test_resolve_single_redirect(self):
self._assert_resolve_tco('https://t.co/2pciHpqpwC', 'https://donmelton.com/2013/06/04/remembering-penny/')
def test_resolve_multiple_redirect(self):
self._assert_resolve_tco('https://t.co/oSJaiNlIP6', 'https://bitly.com/blog/backlinking-strategy/')
def test_resolve_no_redirect(self):
self._assert_resolve_tco('https://example.org/', 'https://example.org/')
if __name__ == '__main__':
unittest.main()
|
# ... existing code ...
def _assert_resolve_tco(self, url, expected):
result = self.run_safari_rs('resolve', url)
assert result.rc == 0
assert result.stderr == ''
assert result.stdout == expected
def test_resolve_single_redirect(self):
self._assert_resolve_tco('https://t.co/2pciHpqpwC', 'https://donmelton.com/2013/06/04/remembering-penny/')
def test_resolve_multiple_redirect(self):
self._assert_resolve_tco('https://t.co/oSJaiNlIP6', 'https://bitly.com/blog/backlinking-strategy/')
def test_resolve_no_redirect(self):
self._assert_resolve_tco('https://example.org/', 'https://example.org/')
# ... rest of the code ...
|
725b3a9db33c90187b913123deefeb180c7fee4c
|
client/app.py
|
client/app.py
|
import argparse
from server import *
from commandRunner import *
class App:
def __init__(self, baseurl, clientid):
self.server = Server(baseurl, clientid)
def run(self):
runner = CommandRunner()
command = self.server.get()
while command is not None:
response = runner.run(command)
self.server.send(response)
command = self.server.get()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument("--baseurl", required=True)
parser.add_argument("--clientid", required=True)
return parser.parse_args()
if __name__ == '__main__':
args = parseCommandLine()
app = App(args.baseurl, args.clientid);
app.run()
|
import argparse
from server import *
from commandRunner import *
class App:
server = None
runner = None
def __init__(self, baseurl, clientid):
self.server = Server(baseurl, clientid)
self.runner = CommandRunner()
def run(self):
command = self.server.get()
while command is not None:
response = self.runner.run(command)
self.server.send(response)
command = self.server.get()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument("--baseurl", required=True)
parser.add_argument("--clientid", required=True)
return parser.parse_args()
if __name__ == '__main__':
args = parseCommandLine()
app = App(args.baseurl, args.clientid);
app.run()
|
Add DI to App object
|
Add DI to App object
|
Python
|
mit
|
CaminsTECH/owncloud-test
|
import argparse
from server import *
from commandRunner import *
class App:
+ server = None
+ runner = None
+
def __init__(self, baseurl, clientid):
self.server = Server(baseurl, clientid)
-
+ self.runner = CommandRunner()
+
- def run(self):
+ def run(self):
- runner = CommandRunner()
command = self.server.get()
while command is not None:
- response = runner.run(command)
+ response = self.runner.run(command)
self.server.send(response)
command = self.server.get()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument("--baseurl", required=True)
parser.add_argument("--clientid", required=True)
return parser.parse_args()
if __name__ == '__main__':
args = parseCommandLine()
app = App(args.baseurl, args.clientid);
app.run()
|
Add DI to App object
|
## Code Before:
import argparse
from server import *
from commandRunner import *
class App:
def __init__(self, baseurl, clientid):
self.server = Server(baseurl, clientid)
def run(self):
runner = CommandRunner()
command = self.server.get()
while command is not None:
response = runner.run(command)
self.server.send(response)
command = self.server.get()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument("--baseurl", required=True)
parser.add_argument("--clientid", required=True)
return parser.parse_args()
if __name__ == '__main__':
args = parseCommandLine()
app = App(args.baseurl, args.clientid);
app.run()
## Instruction:
Add DI to App object
## Code After:
import argparse
from server import *
from commandRunner import *
class App:
server = None
runner = None
def __init__(self, baseurl, clientid):
self.server = Server(baseurl, clientid)
self.runner = CommandRunner()
def run(self):
command = self.server.get()
while command is not None:
response = self.runner.run(command)
self.server.send(response)
command = self.server.get()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument("--baseurl", required=True)
parser.add_argument("--clientid", required=True)
return parser.parse_args()
if __name__ == '__main__':
args = parseCommandLine()
app = App(args.baseurl, args.clientid);
app.run()
|
...
class App:
server = None
runner = None
def __init__(self, baseurl, clientid):
...
self.server = Server(baseurl, clientid)
self.runner = CommandRunner()
def run(self):
command = self.server.get()
...
while command is not None:
response = self.runner.run(command)
self.server.send(response)
...
|
6fc9032bc372aad7b9c1217b44ff081ac9108af2
|
manoseimas/common/tests/utils/test_words.py
|
manoseimas/common/tests/utils/test_words.py
|
from __future__ import unicode_literals
import unittest
from manoseimas.scrapy import textutils
class WordCountTest(unittest.TestCase):
def test_get_word_count(self):
word_count = textutils.get_word_count('Žodžiai, lietuviškai.')
self.assertEqual(word_count, 2)
def test_get_words(self):
words = textutils.get_words('Žodžiai, lietuviškai.')
self.assertEqual(words, ['Žodžiai', 'lietuviškai'])
|
from __future__ import unicode_literals
import unittest
from manoseimas.common.utils import words
class WordCountTest(unittest.TestCase):
def test_get_word_count(self):
word_count = words.get_word_count('Žodžiai, lietuviškai.')
self.assertEqual(word_count, 2)
def test_get_words(self):
words_list = words.get_words('Žodžiai, lietuviškai.')
self.assertEqual(words_list, ['Žodžiai', 'lietuviškai'])
|
Fix word_count test import paths.
|
Fix word_count test import paths.
|
Python
|
agpl-3.0
|
ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt,ManoSeimas/manoseimas.lt
|
from __future__ import unicode_literals
import unittest
- from manoseimas.scrapy import textutils
+ from manoseimas.common.utils import words
class WordCountTest(unittest.TestCase):
def test_get_word_count(self):
- word_count = textutils.get_word_count('Žodžiai, lietuviškai.')
+ word_count = words.get_word_count('Žodžiai, lietuviškai.')
self.assertEqual(word_count, 2)
def test_get_words(self):
- words = textutils.get_words('Žodžiai, lietuviškai.')
+ words_list = words.get_words('Žodžiai, lietuviškai.')
- self.assertEqual(words, ['Žodžiai', 'lietuviškai'])
+ self.assertEqual(words_list, ['Žodžiai', 'lietuviškai'])
|
Fix word_count test import paths.
|
## Code Before:
from __future__ import unicode_literals
import unittest
from manoseimas.scrapy import textutils
class WordCountTest(unittest.TestCase):
def test_get_word_count(self):
word_count = textutils.get_word_count('Žodžiai, lietuviškai.')
self.assertEqual(word_count, 2)
def test_get_words(self):
words = textutils.get_words('Žodžiai, lietuviškai.')
self.assertEqual(words, ['Žodžiai', 'lietuviškai'])
## Instruction:
Fix word_count test import paths.
## Code After:
from __future__ import unicode_literals
import unittest
from manoseimas.common.utils import words
class WordCountTest(unittest.TestCase):
def test_get_word_count(self):
word_count = words.get_word_count('Žodžiai, lietuviškai.')
self.assertEqual(word_count, 2)
def test_get_words(self):
words_list = words.get_words('Žodžiai, lietuviškai.')
self.assertEqual(words_list, ['Žodžiai', 'lietuviškai'])
|
...
from manoseimas.common.utils import words
...
def test_get_word_count(self):
word_count = words.get_word_count('Žodžiai, lietuviškai.')
self.assertEqual(word_count, 2)
...
def test_get_words(self):
words_list = words.get_words('Žodžiai, lietuviškai.')
self.assertEqual(words_list, ['Žodžiai', 'lietuviškai'])
...
|
a7be90536618ac52c91f599bb167e05f831cddfb
|
mangopaysdk/entities/transaction.py
|
mangopaysdk/entities/transaction.py
|
from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
|
from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
self.ResultMessage = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
|
Add possibilty to get ResultMessage
|
Add possibilty to get ResultMessage
|
Python
|
mit
|
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
|
from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
+ self.ResultMessage = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
+
|
Add possibilty to get ResultMessage
|
## Code Before:
from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
## Instruction:
Add possibilty to get ResultMessage
## Code After:
from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
self.ResultMessage = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
|
# ... existing code ...
self.ResultCode = None
self.ResultMessage = None
# timestamp
# ... rest of the code ...
|
2c204e02607e75d0cfb696a1dfbaa1b7997fbb55
|
sections/transportation/ferrys.py
|
sections/transportation/ferrys.py
|
PATH = 'ferry_paths.json'
def has_required_data(data_dir):
return False
# def obtain_data(data_dir):
# with open(join(data_dir, PATH), 'w') as fh:
# json.dump(get_paths(['Railways']).tolist(), fh)
|
import requests
from ..image_provider import ImageProvider
PATH = 'ferry_paths.json'
BASE = 'http://journeyplanner.silverrailtech.com/JourneyPlannerService/V2'
DATASET = 'PerthRestricted'
class FerryImageProvider(ImageProvider):
def has_required_data(self):
return self.data_dir_exists(PATH)
def obtain_data(self):
url = BASE + "/rest/DataSets/{dataset}/RouteMap".format_map(locals())
api_key = "eac7a147-0831-4fcf-8fa8-a5e8ffcfa039"
routeTimetableGroupUid = 'PerthRestricted:3'
r = requests.get(
url,
params={
'ApiKey': api_key,
'Route': routeTimetableGroupUid,
'MappingDataRequired': True,
'transactionId': 0,
'format': 'json'
}
)
data = r.json()
return self.save_json(
PATH,
[
[
tuple(map(float, point.split(',')))
for point in path['Polyline'].split(';')
]
for path in data['MapSegments']
]
)
|
Work on ferry routes display
|
Work on ferry routes display
Will either need to pull data from google, or aggregate if we want to do
all those in australia
|
Python
|
mit
|
Mause/statistical_atlas_of_au
|
+ import requests
+
+ from ..image_provider import ImageProvider
PATH = 'ferry_paths.json'
+ BASE = 'http://journeyplanner.silverrailtech.com/JourneyPlannerService/V2'
+ DATASET = 'PerthRestricted'
+ class FerryImageProvider(ImageProvider):
- def has_required_data(data_dir):
+ def has_required_data(self):
- return False
+ return self.data_dir_exists(PATH)
+ def obtain_data(self):
+ url = BASE + "/rest/DataSets/{dataset}/RouteMap".format_map(locals())
- # def obtain_data(data_dir):
- # with open(join(data_dir, PATH), 'w') as fh:
- # json.dump(get_paths(['Railways']).tolist(), fh)
+ api_key = "eac7a147-0831-4fcf-8fa8-a5e8ffcfa039"
+
+ routeTimetableGroupUid = 'PerthRestricted:3'
+ r = requests.get(
+ url,
+ params={
+ 'ApiKey': api_key,
+ 'Route': routeTimetableGroupUid,
+ 'MappingDataRequired': True,
+ 'transactionId': 0,
+ 'format': 'json'
+ }
+ )
+ data = r.json()
+
+ return self.save_json(
+ PATH,
+ [
+ [
+ tuple(map(float, point.split(',')))
+ for point in path['Polyline'].split(';')
+ ]
+ for path in data['MapSegments']
+ ]
+ )
+
|
Work on ferry routes display
|
## Code Before:
PATH = 'ferry_paths.json'
def has_required_data(data_dir):
return False
# def obtain_data(data_dir):
# with open(join(data_dir, PATH), 'w') as fh:
# json.dump(get_paths(['Railways']).tolist(), fh)
## Instruction:
Work on ferry routes display
## Code After:
import requests
from ..image_provider import ImageProvider
PATH = 'ferry_paths.json'
BASE = 'http://journeyplanner.silverrailtech.com/JourneyPlannerService/V2'
DATASET = 'PerthRestricted'
class FerryImageProvider(ImageProvider):
def has_required_data(self):
return self.data_dir_exists(PATH)
def obtain_data(self):
url = BASE + "/rest/DataSets/{dataset}/RouteMap".format_map(locals())
api_key = "eac7a147-0831-4fcf-8fa8-a5e8ffcfa039"
routeTimetableGroupUid = 'PerthRestricted:3'
r = requests.get(
url,
params={
'ApiKey': api_key,
'Route': routeTimetableGroupUid,
'MappingDataRequired': True,
'transactionId': 0,
'format': 'json'
}
)
data = r.json()
return self.save_json(
PATH,
[
[
tuple(map(float, point.split(',')))
for point in path['Polyline'].split(';')
]
for path in data['MapSegments']
]
)
|
// ... existing code ...
import requests
from ..image_provider import ImageProvider
// ... modified code ...
PATH = 'ferry_paths.json'
BASE = 'http://journeyplanner.silverrailtech.com/JourneyPlannerService/V2'
DATASET = 'PerthRestricted'
...
class FerryImageProvider(ImageProvider):
def has_required_data(self):
return self.data_dir_exists(PATH)
def obtain_data(self):
url = BASE + "/rest/DataSets/{dataset}/RouteMap".format_map(locals())
api_key = "eac7a147-0831-4fcf-8fa8-a5e8ffcfa039"
routeTimetableGroupUid = 'PerthRestricted:3'
r = requests.get(
url,
params={
'ApiKey': api_key,
'Route': routeTimetableGroupUid,
'MappingDataRequired': True,
'transactionId': 0,
'format': 'json'
}
)
data = r.json()
return self.save_json(
PATH,
[
[
tuple(map(float, point.split(',')))
for point in path['Polyline'].split(';')
]
for path in data['MapSegments']
]
)
// ... rest of the code ...
|
c5f153ce69819acdc8f83704daa919fb0cc0b02b
|
bookmarks/default_settings.py
|
bookmarks/default_settings.py
|
import pkg_resources # part of setuptools
USER_AGENT_NAME = 'bookmarks'
VERSION_NUMBER = pkg_resources.require('bookmarks')[0].version
SECRET_KEY = 'development key'
DATABASE_USERNAME = 'bookmarks'
DATABASE_PASSWORD = ''
DATABASE_HOST = 'localhost'
DATABASE_NAME = 'bookmarks'
|
import pkg_resources # part of setuptools
USER_AGENT_NAME = 'bookmarks'
VERSION_NUMBER = pkg_resources.require('bookmarks')[0].version
SECRET_KEY = 'development key'
DATABASE_USERNAME = 'bookmarks'
DATABASE_PASSWORD = ''
DATABASE_HOST = 'localhost'
DATABASE_NAME = 'bookmarks'
TEST_DATABASE_NAME = 'bookmarks_test'
|
Add default test database name to default settings
|
Add default test database name to default settings
|
Python
|
apache-2.0
|
byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks
|
import pkg_resources # part of setuptools
USER_AGENT_NAME = 'bookmarks'
VERSION_NUMBER = pkg_resources.require('bookmarks')[0].version
SECRET_KEY = 'development key'
DATABASE_USERNAME = 'bookmarks'
DATABASE_PASSWORD = ''
DATABASE_HOST = 'localhost'
DATABASE_NAME = 'bookmarks'
+ TEST_DATABASE_NAME = 'bookmarks_test'
|
Add default test database name to default settings
|
## Code Before:
import pkg_resources # part of setuptools
USER_AGENT_NAME = 'bookmarks'
VERSION_NUMBER = pkg_resources.require('bookmarks')[0].version
SECRET_KEY = 'development key'
DATABASE_USERNAME = 'bookmarks'
DATABASE_PASSWORD = ''
DATABASE_HOST = 'localhost'
DATABASE_NAME = 'bookmarks'
## Instruction:
Add default test database name to default settings
## Code After:
import pkg_resources # part of setuptools
USER_AGENT_NAME = 'bookmarks'
VERSION_NUMBER = pkg_resources.require('bookmarks')[0].version
SECRET_KEY = 'development key'
DATABASE_USERNAME = 'bookmarks'
DATABASE_PASSWORD = ''
DATABASE_HOST = 'localhost'
DATABASE_NAME = 'bookmarks'
TEST_DATABASE_NAME = 'bookmarks_test'
|
...
DATABASE_NAME = 'bookmarks'
TEST_DATABASE_NAME = 'bookmarks_test'
...
|
831e09baadf3e7c426bc5558c04dae234b2902d2
|
account_companyweb/tests/__init__.py
|
account_companyweb/tests/__init__.py
|
from . import test_companyweb
|
from . import test_companyweb
checks = [
test_companyweb,
]
|
Add checks on init file
|
[ADD] Add checks on init file
|
Python
|
agpl-3.0
|
QANSEE/l10n-belgium,Niboo/l10n-belgium,QANSEE/l10n-belgium,Noviat/l10n-belgium,acsone/l10n-belgium,akretion/l10n-belgium,Noviat/l10n-belgium,Niboo/l10n-belgium,acsone/l10n-belgium,akretion/l10n-belgium,yvaucher/l10n-belgium
|
from . import test_companyweb
+ checks = [
+ test_companyweb,
+ ]
+
|
Add checks on init file
|
## Code Before:
from . import test_companyweb
## Instruction:
Add checks on init file
## Code After:
from . import test_companyweb
checks = [
test_companyweb,
]
|
# ... existing code ...
from . import test_companyweb
checks = [
test_companyweb,
]
# ... rest of the code ...
|
35d84021736f5509dc37f12ca92a05693cff5d47
|
twython/helpers.py
|
twython/helpers.py
|
from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
elif isinstance(v, basestring):
params[k] = v
else:
continue
return params, files
|
from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
elif isinstance(v, basestring) or isinstance(v, int):
params[k] = v
else:
continue
return params, files
|
Include ints in params too
|
Include ints in params too
Oops ;P
|
Python
|
mit
|
vivek8943/twython,ping/twython,akarambir/twython,Fueled/twython,fibears/twython,Hasimir/twython,Devyani-Divs/twython,Oire/twython,joebos/twython,ryanmcgrath/twython
|
from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
- elif isinstance(v, basestring):
+ elif isinstance(v, basestring) or isinstance(v, int):
params[k] = v
else:
continue
return params, files
|
Include ints in params too
|
## Code Before:
from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
elif isinstance(v, basestring):
params[k] = v
else:
continue
return params, files
## Instruction:
Include ints in params too
## Code After:
from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
elif isinstance(v, basestring) or isinstance(v, int):
params[k] = v
else:
continue
return params, files
|
# ... existing code ...
params[k] = 'false'
elif isinstance(v, basestring) or isinstance(v, int):
params[k] = v
# ... rest of the code ...
|
c140c1a6d32c2caaf9f0e5a87efd219b9573608a
|
shub/tool.py
|
shub/tool.py
|
import click, importlib
from shub.utils import missing_modules
def missingmod_cmd(modules):
modlist = ", ".join(modules)
@click.command(help="*DISABLED* - requires %s" % modlist)
@click.pass_context
def cmd(ctx):
click.echo("Error: '%s' command requires %s" % (ctx.info_name, modlist))
ctx.exit(1)
return cmd
@click.group(help="Scrapinghub command-line client")
def cli():
pass
module_deps = {
"deploy": ["scrapy", "setuptools"],
"login": [],
}
for command, modules in module_deps.iteritems():
m = missing_modules(*modules)
if m:
cli.add_command(missingmod_cmd(m), command)
else:
module_path = "shub." + command
command_module = importlib.import_module(module_path)
cli.add_command(command_module.cli, command)
|
import click, importlib
from shub.utils import missing_modules
def missingmod_cmd(modules):
modlist = ", ".join(modules)
@click.command(help="*DISABLED* - requires %s" % modlist)
@click.pass_context
def cmd(ctx):
click.echo("Error: '%s' command requires %s" % (ctx.info_name, modlist))
ctx.exit(1)
return cmd
@click.group(help="Scrapinghub command-line client")
def cli():
pass
module_deps = {
"deploy": ["scrapy", "setuptools"],
"login": [],
}
for command, modules in module_deps.iteritems():
m = missing_modules(*modules)
if m:
cli.add_command(missingmod_cmd(m), command)
else:
module_path = "shub." + command
command_module = importlib.import_module(module_path)
command_name = command.replace('_', '-') # easier to type
cli.add_command(command_module.cli, command)
|
Use hifens instead of underscore for command names
|
Use hifens instead of underscore for command names
|
Python
|
bsd-3-clause
|
scrapinghub/shub
|
import click, importlib
from shub.utils import missing_modules
def missingmod_cmd(modules):
modlist = ", ".join(modules)
@click.command(help="*DISABLED* - requires %s" % modlist)
@click.pass_context
def cmd(ctx):
click.echo("Error: '%s' command requires %s" % (ctx.info_name, modlist))
ctx.exit(1)
return cmd
@click.group(help="Scrapinghub command-line client")
def cli():
pass
module_deps = {
"deploy": ["scrapy", "setuptools"],
"login": [],
}
for command, modules in module_deps.iteritems():
m = missing_modules(*modules)
if m:
cli.add_command(missingmod_cmd(m), command)
else:
module_path = "shub." + command
command_module = importlib.import_module(module_path)
+ command_name = command.replace('_', '-') # easier to type
cli.add_command(command_module.cli, command)
|
Use hifens instead of underscore for command names
|
## Code Before:
import click, importlib
from shub.utils import missing_modules
def missingmod_cmd(modules):
modlist = ", ".join(modules)
@click.command(help="*DISABLED* - requires %s" % modlist)
@click.pass_context
def cmd(ctx):
click.echo("Error: '%s' command requires %s" % (ctx.info_name, modlist))
ctx.exit(1)
return cmd
@click.group(help="Scrapinghub command-line client")
def cli():
pass
module_deps = {
"deploy": ["scrapy", "setuptools"],
"login": [],
}
for command, modules in module_deps.iteritems():
m = missing_modules(*modules)
if m:
cli.add_command(missingmod_cmd(m), command)
else:
module_path = "shub." + command
command_module = importlib.import_module(module_path)
cli.add_command(command_module.cli, command)
## Instruction:
Use hifens instead of underscore for command names
## Code After:
import click, importlib
from shub.utils import missing_modules
def missingmod_cmd(modules):
modlist = ", ".join(modules)
@click.command(help="*DISABLED* - requires %s" % modlist)
@click.pass_context
def cmd(ctx):
click.echo("Error: '%s' command requires %s" % (ctx.info_name, modlist))
ctx.exit(1)
return cmd
@click.group(help="Scrapinghub command-line client")
def cli():
pass
module_deps = {
"deploy": ["scrapy", "setuptools"],
"login": [],
}
for command, modules in module_deps.iteritems():
m = missing_modules(*modules)
if m:
cli.add_command(missingmod_cmd(m), command)
else:
module_path = "shub." + command
command_module = importlib.import_module(module_path)
command_name = command.replace('_', '-') # easier to type
cli.add_command(command_module.cli, command)
|
// ... existing code ...
command_module = importlib.import_module(module_path)
command_name = command.replace('_', '-') # easier to type
cli.add_command(command_module.cli, command)
// ... rest of the code ...
|
2205ea40f64b09f611b7f6cb4c9716d8e29136d4
|
grammpy/Rule.py
|
grammpy/Rule.py
|
class Rule:
pass
|
from grammpy import EPSILON
class Rule:
right = [EPSILON]
left = [EPSILON]
rule = ([EPSILON], [EPSILON])
rules = [([EPSILON], [EPSILON])]
def is_regular(self):
return False
def is_contextfree(self):
return False
def is_context(self):
return False
def is_unrestricted(self):
return False
|
Add base interface for rule
|
Add base interface for rule
|
Python
|
mit
|
PatrikValkovic/grammpy
|
+
+ from grammpy import EPSILON
class Rule:
- pass
+ right = [EPSILON]
+ left = [EPSILON]
+ rule = ([EPSILON], [EPSILON])
+ rules = [([EPSILON], [EPSILON])]
+ def is_regular(self):
+ return False
+
+ def is_contextfree(self):
+ return False
+
+ def is_context(self):
+ return False
+
+ def is_unrestricted(self):
+ return False
+
|
Add base interface for rule
|
## Code Before:
class Rule:
pass
## Instruction:
Add base interface for rule
## Code After:
from grammpy import EPSILON
class Rule:
right = [EPSILON]
left = [EPSILON]
rule = ([EPSILON], [EPSILON])
rules = [([EPSILON], [EPSILON])]
def is_regular(self):
return False
def is_contextfree(self):
return False
def is_context(self):
return False
def is_unrestricted(self):
return False
|
// ... existing code ...
from grammpy import EPSILON
// ... modified code ...
class Rule:
right = [EPSILON]
left = [EPSILON]
rule = ([EPSILON], [EPSILON])
rules = [([EPSILON], [EPSILON])]
def is_regular(self):
return False
def is_contextfree(self):
return False
def is_context(self):
return False
def is_unrestricted(self):
return False
// ... rest of the code ...
|
0b13092a7854fe2d967d057221420a57b7a37b16
|
linter.py
|
linter.py
|
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
npm_name = 'stylint'
syntax = ('stylus', 'vue')
selectors = {'vue': 'source.stylus.embedded.html'}
cmd = 'stylint @ *'
executable = 'stylint'
version_requirement = '>= 1.5.0'
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
npm_name = 'stylint'
syntax = ('stylus', 'vue')
selectors = {'vue': 'source.stylus.embedded.html'}
cmd = 'stylint @ *'
executable = 'stylint'
version_requirement = '>= 1.5.0'
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
Change module docstring to make Travis CI build pass
|
Change module docstring to make Travis CI build pass
|
Python
|
mit
|
jackbrewer/SublimeLinter-contrib-stylint
|
- """This module exports the Stylint plugin class."""
+ """Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
npm_name = 'stylint'
syntax = ('stylus', 'vue')
selectors = {'vue': 'source.stylus.embedded.html'}
cmd = 'stylint @ *'
executable = 'stylint'
version_requirement = '>= 1.5.0'
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
Change module docstring to make Travis CI build pass
|
## Code Before:
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
npm_name = 'stylint'
syntax = ('stylus', 'vue')
selectors = {'vue': 'source.stylus.embedded.html'}
cmd = 'stylint @ *'
executable = 'stylint'
version_requirement = '>= 1.5.0'
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
## Instruction:
Change module docstring to make Travis CI build pass
## Code After:
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
npm_name = 'stylint'
syntax = ('stylus', 'vue')
selectors = {'vue': 'source.stylus.embedded.html'}
cmd = 'stylint @ *'
executable = 'stylint'
version_requirement = '>= 1.5.0'
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
...
"""Exports the Stylint plugin class."""
...
|
a3c4f151a9a44aae3528492d4a00a1815c52cda6
|
website_membership_contact_visibility/models/res_partner.py
|
website_membership_contact_visibility/models/res_partner.py
|
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
string='Visible In The Website',
copy=False,
default=True)
|
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
string='Visible Contact Info On The Website',
copy=False,
default=True)
|
Change the label of "website_membership_published" into "Visible Contact Info On The Website"
|
Change the label of "website_membership_published" into "Visible Contact Info On The Website"
|
Python
|
agpl-3.0
|
open-synergy/vertical-association
|
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
- string='Visible In The Website',
+ string='Visible Contact Info On The Website',
copy=False,
default=True)
|
Change the label of "website_membership_published" into "Visible Contact Info On The Website"
|
## Code Before:
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
string='Visible In The Website',
copy=False,
default=True)
## Instruction:
Change the label of "website_membership_published" into "Visible Contact Info On The Website"
## Code After:
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
string='Visible Contact Info On The Website',
copy=False,
default=True)
|
// ... existing code ...
website_membership_published = fields.Boolean(
string='Visible Contact Info On The Website',
copy=False,
// ... rest of the code ...
|
90f2c22a9243855546c8689c5773be837e05aa47
|
core/views.py
|
core/views.py
|
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from django.template import RequestContext
from core.mixins import SubdomainContextMixin, PaginatorMixin
from core.models import Infopage
from core.context_processors import subdomains_context, categories_context
class RyndaCreateView(SubdomainContextMixin, CreateView):
pass
class RyndaDetailView(SubdomainContextMixin, DetailView):
pass
class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ):
pass
def show_page(request, slug):
page = get_object_or_404(Infopage, slug=slug)
return render_to_response('infopage/show_page.html',
{'title': page.title, 'text': page.text, },
context_instance=RequestContext(request,
processors=[subdomains_context, categories_context])
)
|
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from django.template import RequestContext
from core.mixins import SubdomainContextMixin, PaginatorMixin
from core.models import Infopage
from core.context_processors import subdomains_context, categories_context
class RyndaCreateView(SubdomainContextMixin, CreateView):
pass
class RyndaDetailView(SubdomainContextMixin, DetailView):
pass
class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ):
paginator_url = None
def get_paginator_url(self):
if self.paginator_url is None:
raise Exception(
"You MUST define paginator_url or overwrite get_paginator_url()")
return self.paginator_url
def get_context_data(self, **kwargs):
context = super(RyndaListView, self).get_context_data(**kwargs)
context['paginator_url'] = self.get_paginator_url()
sc = self.paginator(context['paginator'].num_pages, page=context['page_obj'].number)
context['paginator_line'] = sc
return context
def show_page(request, slug):
page = get_object_or_404(Infopage, slug=slug)
return render_to_response('infopage/show_page.html',
{'title': page.title, 'text': page.text, },
context_instance=RequestContext(request,
processors=[subdomains_context, categories_context])
)
|
Move paginator settings to base list view
|
Move paginator settings to base list view
|
Python
|
mit
|
sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa
|
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from django.template import RequestContext
from core.mixins import SubdomainContextMixin, PaginatorMixin
from core.models import Infopage
from core.context_processors import subdomains_context, categories_context
class RyndaCreateView(SubdomainContextMixin, CreateView):
pass
class RyndaDetailView(SubdomainContextMixin, DetailView):
pass
class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ):
- pass
+ paginator_url = None
+
+ def get_paginator_url(self):
+ if self.paginator_url is None:
+ raise Exception(
+ "You MUST define paginator_url or overwrite get_paginator_url()")
+ return self.paginator_url
+
+ def get_context_data(self, **kwargs):
+ context = super(RyndaListView, self).get_context_data(**kwargs)
+ context['paginator_url'] = self.get_paginator_url()
+ sc = self.paginator(context['paginator'].num_pages, page=context['page_obj'].number)
+ context['paginator_line'] = sc
+ return context
def show_page(request, slug):
page = get_object_or_404(Infopage, slug=slug)
return render_to_response('infopage/show_page.html',
{'title': page.title, 'text': page.text, },
context_instance=RequestContext(request,
processors=[subdomains_context, categories_context])
)
|
Move paginator settings to base list view
|
## Code Before:
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from django.template import RequestContext
from core.mixins import SubdomainContextMixin, PaginatorMixin
from core.models import Infopage
from core.context_processors import subdomains_context, categories_context
class RyndaCreateView(SubdomainContextMixin, CreateView):
pass
class RyndaDetailView(SubdomainContextMixin, DetailView):
pass
class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ):
pass
def show_page(request, slug):
page = get_object_or_404(Infopage, slug=slug)
return render_to_response('infopage/show_page.html',
{'title': page.title, 'text': page.text, },
context_instance=RequestContext(request,
processors=[subdomains_context, categories_context])
)
## Instruction:
Move paginator settings to base list view
## Code After:
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from django.template import RequestContext
from core.mixins import SubdomainContextMixin, PaginatorMixin
from core.models import Infopage
from core.context_processors import subdomains_context, categories_context
class RyndaCreateView(SubdomainContextMixin, CreateView):
pass
class RyndaDetailView(SubdomainContextMixin, DetailView):
pass
class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ):
paginator_url = None
def get_paginator_url(self):
if self.paginator_url is None:
raise Exception(
"You MUST define paginator_url or overwrite get_paginator_url()")
return self.paginator_url
def get_context_data(self, **kwargs):
context = super(RyndaListView, self).get_context_data(**kwargs)
context['paginator_url'] = self.get_paginator_url()
sc = self.paginator(context['paginator'].num_pages, page=context['page_obj'].number)
context['paginator_line'] = sc
return context
def show_page(request, slug):
page = get_object_or_404(Infopage, slug=slug)
return render_to_response('infopage/show_page.html',
{'title': page.title, 'text': page.text, },
context_instance=RequestContext(request,
processors=[subdomains_context, categories_context])
)
|
...
class RyndaListView(SubdomainContextMixin, PaginatorMixin, ListView ):
paginator_url = None
def get_paginator_url(self):
if self.paginator_url is None:
raise Exception(
"You MUST define paginator_url or overwrite get_paginator_url()")
return self.paginator_url
def get_context_data(self, **kwargs):
context = super(RyndaListView, self).get_context_data(**kwargs)
context['paginator_url'] = self.get_paginator_url()
sc = self.paginator(context['paginator'].num_pages, page=context['page_obj'].number)
context['paginator_line'] = sc
return context
...
|
29b26aa8b44ea5820cfcd20e324d2c3631338228
|
portal/models/research_protocol.py
|
portal/models/research_protocol.py
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
rp = ResearchProtocol.query.filter_by(name=data['name']).first()
if not rp:
rp = cls(data['name'])
return rp
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
Implement common pattern from_json calls update_from_json
|
Implement common pattern from_json calls update_from_json
|
Python
|
bsd-3-clause
|
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
- rp = ResearchProtocol.query.filter_by(name=data['name']).first()
- if not rp:
- rp = cls(data['name'])
+ instance = cls(data['name'])
+ return instance.update_from_json(data)
+
+ def update_from_json(self, data):
+ self.name = data['name']
+ if 'created_at' in data:
+ self.created_at = data['created_at']
- return rp
+ return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
Implement common pattern from_json calls update_from_json
|
## Code Before:
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
rp = ResearchProtocol.query.filter_by(name=data['name']).first()
if not rp:
rp = cls(data['name'])
return rp
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
## Instruction:
Implement common pattern from_json calls update_from_json
## Code After:
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
# ... existing code ...
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
# ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.