commit
stringlengths 40
40
| old_file
stringlengths 4
106
| new_file
stringlengths 4
106
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
2.95k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 7
43k
| ndiff
stringlengths 52
3.31k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| diff
stringlengths 49
3.61k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2c7907c6516ded896000dec610bde09f7721915d
|
ckanext/datasetversions/logic/action/create.py
|
ckanext/datasetversions/logic/action/create.py
|
import ckan.logic as logic
from ckan.logic.action.get import package_show as ckan_package_show
from ckan.plugins import toolkit
from ckanext.datasetversions.helpers import get_context
def dataset_version_create(context, data_dict):
id = data_dict.get('id')
parent_name = data_dict.get('base_name')
owner_org = data_dict.get('owner_org')
parent_dict = {
'name': parent_name,
'__parent': True,
}
if owner_org:
parent_dict['owner_org'] = owner_org
parent_dict['private'] = True
else:
parent_dict['private'] = False
parent = _get_or_create_parent_dataset(
context,
parent_dict
)
toolkit.get_action('package_relationship_create')(
get_context(context), {
'subject': id,
'object': parent['id'],
'type': 'child_of',
}
)
def _get_or_create_parent_dataset(context, data_dict):
try:
dataset = ckan_package_show(
get_context(context), {'id': data_dict['name']})
except (logic.NotFound):
dataset = toolkit.get_action('package_create')(
get_context(context), data_dict)
return dataset
|
import ckan.logic as logic
from ckan.logic.action.get import package_show as ckan_package_show
from ckan.plugins import toolkit
from ckanext.datasetversions.helpers import get_context
def dataset_version_create(context, data_dict):
id = data_dict.get('id')
parent_name = data_dict.get('base_name')
owner_org = data_dict.get('owner_org')
parent_dict = {
'name': parent_name,
'type': data_dict.get('type', 'dataset'),
'__parent': True,
}
if owner_org:
parent_dict['owner_org'] = owner_org
parent_dict['private'] = True
else:
parent_dict['private'] = False
parent = _get_or_create_parent_dataset(
context,
parent_dict
)
toolkit.get_action('package_relationship_create')(
get_context(context), {
'subject': id,
'object': parent['id'],
'type': 'child_of',
}
)
def _get_or_create_parent_dataset(context, data_dict):
try:
dataset = ckan_package_show(
get_context(context), {'id': data_dict['name']})
except (logic.NotFound):
dataset = toolkit.get_action('package_create')(
get_context(context), data_dict)
return dataset
|
Create a parent with the same dataset type
|
Create a parent with the same dataset type
|
Python
|
agpl-3.0
|
aptivate/ckanext-datasetversions,aptivate/ckanext-datasetversions,aptivate/ckanext-datasetversions
|
import ckan.logic as logic
from ckan.logic.action.get import package_show as ckan_package_show
from ckan.plugins import toolkit
from ckanext.datasetversions.helpers import get_context
def dataset_version_create(context, data_dict):
id = data_dict.get('id')
parent_name = data_dict.get('base_name')
owner_org = data_dict.get('owner_org')
parent_dict = {
'name': parent_name,
+ 'type': data_dict.get('type', 'dataset'),
'__parent': True,
}
if owner_org:
parent_dict['owner_org'] = owner_org
parent_dict['private'] = True
else:
parent_dict['private'] = False
parent = _get_or_create_parent_dataset(
context,
parent_dict
)
toolkit.get_action('package_relationship_create')(
get_context(context), {
'subject': id,
'object': parent['id'],
'type': 'child_of',
}
)
def _get_or_create_parent_dataset(context, data_dict):
try:
dataset = ckan_package_show(
get_context(context), {'id': data_dict['name']})
except (logic.NotFound):
dataset = toolkit.get_action('package_create')(
get_context(context), data_dict)
return dataset
|
Create a parent with the same dataset type
|
## Code Before:
import ckan.logic as logic
from ckan.logic.action.get import package_show as ckan_package_show
from ckan.plugins import toolkit
from ckanext.datasetversions.helpers import get_context
def dataset_version_create(context, data_dict):
id = data_dict.get('id')
parent_name = data_dict.get('base_name')
owner_org = data_dict.get('owner_org')
parent_dict = {
'name': parent_name,
'__parent': True,
}
if owner_org:
parent_dict['owner_org'] = owner_org
parent_dict['private'] = True
else:
parent_dict['private'] = False
parent = _get_or_create_parent_dataset(
context,
parent_dict
)
toolkit.get_action('package_relationship_create')(
get_context(context), {
'subject': id,
'object': parent['id'],
'type': 'child_of',
}
)
def _get_or_create_parent_dataset(context, data_dict):
try:
dataset = ckan_package_show(
get_context(context), {'id': data_dict['name']})
except (logic.NotFound):
dataset = toolkit.get_action('package_create')(
get_context(context), data_dict)
return dataset
## Instruction:
Create a parent with the same dataset type
## Code After:
import ckan.logic as logic
from ckan.logic.action.get import package_show as ckan_package_show
from ckan.plugins import toolkit
from ckanext.datasetversions.helpers import get_context
def dataset_version_create(context, data_dict):
id = data_dict.get('id')
parent_name = data_dict.get('base_name')
owner_org = data_dict.get('owner_org')
parent_dict = {
'name': parent_name,
'type': data_dict.get('type', 'dataset'),
'__parent': True,
}
if owner_org:
parent_dict['owner_org'] = owner_org
parent_dict['private'] = True
else:
parent_dict['private'] = False
parent = _get_or_create_parent_dataset(
context,
parent_dict
)
toolkit.get_action('package_relationship_create')(
get_context(context), {
'subject': id,
'object': parent['id'],
'type': 'child_of',
}
)
def _get_or_create_parent_dataset(context, data_dict):
try:
dataset = ckan_package_show(
get_context(context), {'id': data_dict['name']})
except (logic.NotFound):
dataset = toolkit.get_action('package_create')(
get_context(context), data_dict)
return dataset
|
import ckan.logic as logic
from ckan.logic.action.get import package_show as ckan_package_show
from ckan.plugins import toolkit
from ckanext.datasetversions.helpers import get_context
def dataset_version_create(context, data_dict):
id = data_dict.get('id')
parent_name = data_dict.get('base_name')
owner_org = data_dict.get('owner_org')
parent_dict = {
'name': parent_name,
+ 'type': data_dict.get('type', 'dataset'),
'__parent': True,
}
if owner_org:
parent_dict['owner_org'] = owner_org
parent_dict['private'] = True
else:
parent_dict['private'] = False
parent = _get_or_create_parent_dataset(
context,
parent_dict
)
toolkit.get_action('package_relationship_create')(
get_context(context), {
'subject': id,
'object': parent['id'],
'type': 'child_of',
}
)
def _get_or_create_parent_dataset(context, data_dict):
try:
dataset = ckan_package_show(
get_context(context), {'id': data_dict['name']})
except (logic.NotFound):
dataset = toolkit.get_action('package_create')(
get_context(context), data_dict)
return dataset
|
b18c0f6b732b5adc42f123d83886d260c8278ad5
|
tests/test_slackelot.py
|
tests/test_slackelot.py
|
import pytest
import mock
from slackelot.slackelot import SlackNotificationError, send_message
def test_send_message_success():
"""Returns True if response.status_code == 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
webhook = 'https://hooks.slack.com/services/'
assert send_message('foo', webhook) == True
def test_send_message_raises_error_bad_request():
"""Raises SlackNotificationError if response.status_code not 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://hooks.slack.com/services/'
send_message('foo', webhook)
assert 'Slack notification failed' in str(error.value)
def test_send_message_raises_error_bad_webhook():
"""Raises SlackNotificationError if webhook_url malformed"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://notthehookwerelookingfor.com'
send_message('foo', webhook)
assert 'webhook_url is not in the correct format' in str(error.value)
|
import pytest
try:
from unittest import mock
except ImportError:
import mock
from slackelot import SlackNotificationError, send_message
def test_send_message_success():
"""Returns True if response.status_code == 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
webhook = 'https://hooks.slack.com/services/'
assert send_message('foo', webhook) == True
def test_send_message_raises_error_bad_request():
"""Raises SlackNotificationError if response.status_code not 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://hooks.slack.com/services/'
send_message('foo', webhook)
assert 'Slack notification failed' in str(error.value)
def test_send_message_raises_error_bad_webhook():
"""Raises SlackNotificationError if webhook_url malformed"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://notthehookwerelookingfor.com'
send_message('foo', webhook)
assert 'webhook_url is not in the correct format' in str(error.value)
|
Refactor imports to be less verbose
|
Refactor imports to be less verbose
|
Python
|
mit
|
Chris-Graffagnino/slackelot
|
import pytest
- import mock
+ try:
+ from unittest import mock
+ except ImportError:
+ import mock
+
- from slackelot.slackelot import SlackNotificationError, send_message
+ from slackelot import SlackNotificationError, send_message
def test_send_message_success():
"""Returns True if response.status_code == 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
webhook = 'https://hooks.slack.com/services/'
assert send_message('foo', webhook) == True
def test_send_message_raises_error_bad_request():
"""Raises SlackNotificationError if response.status_code not 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://hooks.slack.com/services/'
send_message('foo', webhook)
assert 'Slack notification failed' in str(error.value)
def test_send_message_raises_error_bad_webhook():
"""Raises SlackNotificationError if webhook_url malformed"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://notthehookwerelookingfor.com'
send_message('foo', webhook)
assert 'webhook_url is not in the correct format' in str(error.value)
|
Refactor imports to be less verbose
|
## Code Before:
import pytest
import mock
from slackelot.slackelot import SlackNotificationError, send_message
def test_send_message_success():
"""Returns True if response.status_code == 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
webhook = 'https://hooks.slack.com/services/'
assert send_message('foo', webhook) == True
def test_send_message_raises_error_bad_request():
"""Raises SlackNotificationError if response.status_code not 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://hooks.slack.com/services/'
send_message('foo', webhook)
assert 'Slack notification failed' in str(error.value)
def test_send_message_raises_error_bad_webhook():
"""Raises SlackNotificationError if webhook_url malformed"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://notthehookwerelookingfor.com'
send_message('foo', webhook)
assert 'webhook_url is not in the correct format' in str(error.value)
## Instruction:
Refactor imports to be less verbose
## Code After:
import pytest
try:
from unittest import mock
except ImportError:
import mock
from slackelot import SlackNotificationError, send_message
def test_send_message_success():
"""Returns True if response.status_code == 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
webhook = 'https://hooks.slack.com/services/'
assert send_message('foo', webhook) == True
def test_send_message_raises_error_bad_request():
"""Raises SlackNotificationError if response.status_code not 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://hooks.slack.com/services/'
send_message('foo', webhook)
assert 'Slack notification failed' in str(error.value)
def test_send_message_raises_error_bad_webhook():
"""Raises SlackNotificationError if webhook_url malformed"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://notthehookwerelookingfor.com'
send_message('foo', webhook)
assert 'webhook_url is not in the correct format' in str(error.value)
|
import pytest
- import mock
+ try:
+ from unittest import mock
+ except ImportError:
+ import mock
+
- from slackelot.slackelot import SlackNotificationError, send_message
? ----------
+ from slackelot import SlackNotificationError, send_message
def test_send_message_success():
"""Returns True if response.status_code == 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
webhook = 'https://hooks.slack.com/services/'
assert send_message('foo', webhook) == True
def test_send_message_raises_error_bad_request():
"""Raises SlackNotificationError if response.status_code not 200"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 400})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://hooks.slack.com/services/'
send_message('foo', webhook)
assert 'Slack notification failed' in str(error.value)
def test_send_message_raises_error_bad_webhook():
"""Raises SlackNotificationError if webhook_url malformed"""
with mock.patch('slackelot.slackelot.requests.post', return_value=mock.Mock(**{'status_code': 200})) as mock_response:
with pytest.raises(SlackNotificationError) as error:
webhook = 'https://notthehookwerelookingfor.com'
send_message('foo', webhook)
assert 'webhook_url is not in the correct format' in str(error.value)
|
a9755fc4b30629ea2c9db51aa6d4218f99fcabc3
|
frigg/deployments/migrations/0004_auto_20150725_1456.py
|
frigg/deployments/migrations/0004_auto_20150725_1456.py
|
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deployments', '0003_prdeployment_start_time'),
]
operations = [
migrations.AlterField(
model_name='prdeployment',
name='image',
field=models.CharField(default='frigg/frigg-test-base', max_length=255),
),
]
|
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deployments', '0003_prdeployment_start_time'),
]
operations = [
migrations.AlterField(
model_name='prdeployment',
name='image',
field=models.CharField(default=settings.FRIGG_PREVIEW_IMAGE, max_length=255),
),
]
|
Set FRIGG_PREVIEW_IMAGE in db migrations
|
Set FRIGG_PREVIEW_IMAGE in db migrations
|
Python
|
mit
|
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
|
from __future__ import unicode_literals
+ from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deployments', '0003_prdeployment_start_time'),
]
operations = [
migrations.AlterField(
model_name='prdeployment',
name='image',
- field=models.CharField(default='frigg/frigg-test-base', max_length=255),
+ field=models.CharField(default=settings.FRIGG_PREVIEW_IMAGE, max_length=255),
),
]
|
Set FRIGG_PREVIEW_IMAGE in db migrations
|
## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deployments', '0003_prdeployment_start_time'),
]
operations = [
migrations.AlterField(
model_name='prdeployment',
name='image',
field=models.CharField(default='frigg/frigg-test-base', max_length=255),
),
]
## Instruction:
Set FRIGG_PREVIEW_IMAGE in db migrations
## Code After:
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deployments', '0003_prdeployment_start_time'),
]
operations = [
migrations.AlterField(
model_name='prdeployment',
name='image',
field=models.CharField(default=settings.FRIGG_PREVIEW_IMAGE, max_length=255),
),
]
|
from __future__ import unicode_literals
+ from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deployments', '0003_prdeployment_start_time'),
]
operations = [
migrations.AlterField(
model_name='prdeployment',
name='image',
- field=models.CharField(default='frigg/frigg-test-base', max_length=255),
+ field=models.CharField(default=settings.FRIGG_PREVIEW_IMAGE, max_length=255),
),
]
|
cd374366dc6d49cc543a037fba8398e5b724c382
|
tabula/util.py
|
tabula/util.py
|
import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
textwrap.indent(java_version().strip(), " "),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
|
import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
|
Remove textwrap because python 2.7 lacks indent() function
|
Remove textwrap because python 2.7 lacks indent() function
|
Python
|
mit
|
chezou/tabula-py
|
import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
- import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
- {}
+ {}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
- textwrap.indent(java_version().strip(), " "),
+ java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
|
Remove textwrap because python 2.7 lacks indent() function
|
## Code Before:
import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
textwrap.indent(java_version().strip(), " "),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
## Instruction:
Remove textwrap because python 2.7 lacks indent() function
## Code After:
import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
from .__version__ import __version__
print("""Python version:
{}
Java version:
{}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
|
import warnings
import platform
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
def newFunc(*args, **kwargs):
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
newFunc.__name__ = func.__name__
newFunc.__doc__ = func.__doc__
newFunc.__dict__.update(func.__dict__)
return newFunc
def deprecated_option(option):
warnings.warn("Call to deprecated option {}.".format(option),
category=DeprecationWarning, stacklevel=2)
def java_version():
import subprocess
try:
res = subprocess.check_output(["java", "-version"], stderr=subprocess.STDOUT)
res = res.decode()
except subprocess.CalledProcessError as e:
res = "`java -version` faild. `java` command is not found from this Python process. Please ensure to set PATH for `java`"
return res
def environment_info():
import sys
import distro
- import textwrap
from .__version__ import __version__
print("""Python version:
{}
Java version:
- {}
+ {}
tabula-py version: {}
platform: {}
uname:
{}
linux_distribution: {}
mac_ver: {}
""".format(
sys.version,
- textwrap.indent(java_version().strip(), " "),
+ java_version().strip(),
__version__,
platform.platform(),
str(platform.uname()),
distro.linux_distribution(),
platform.mac_ver(),
))
|
d96e52c346314622afc904a2917416028c6784e3
|
swampdragon_live/models.py
|
swampdragon_live/models.py
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
'instance_pk': instance.pk})
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
'instance_pk': instance.pk})
|
Fix initial migration until ContentType is available
|
Fix initial migration until ContentType is available
|
Python
|
mit
|
mback2k/swampdragon-live,mback2k/swampdragon-live
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
+ if ContentType.objects.exists():
- instance_type = ContentType.objects.get_for_model(instance.__class__)
+ instance_type = ContentType.objects.get_for_model(instance.__class__)
- push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
+ push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
- 'instance_pk': instance.pk})
+ 'instance_pk': instance.pk})
|
Fix initial migration until ContentType is available
|
## Code Before:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
'instance_pk': instance.pk})
## Instruction:
Fix initial migration until ContentType is available
## Code After:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
if ContentType.objects.exists():
instance_type = ContentType.objects.get_for_model(instance.__class__)
push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
'instance_pk': instance.pk})
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
from .tasks import push_new_content
@receiver(post_save)
def post_save_handler(sender, instance, **kwargs):
+ if ContentType.objects.exists():
- instance_type = ContentType.objects.get_for_model(instance.__class__)
+ instance_type = ContentType.objects.get_for_model(instance.__class__)
? ++++
- push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
+ push_new_content.apply_async(countdown=1, kwargs={'instance_type_pk': instance_type.pk,
? ++++
- 'instance_pk': instance.pk})
+ 'instance_pk': instance.pk})
? ++++
|
fd3ee57a352fd815d2746f3a72196ac62fdceb5c
|
src/integrationtest/python/shutdown_daemon_tests.py
|
src/integrationtest/python/shutdown_daemon_tests.py
|
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
self.pid_file = os.path.join(self.temp_dir, 'succubus.pid')
os.environ['PID_FILE'] = self.pid_file
def tearDown(self):
#shutil.rmtree(self.temp_dir)
print(self.temp_dir)
def test_daemon_start_status_stop(self):
daemon = "./src/integrationtest/python/shutdown_daemon.py"
subprocess.check_call([daemon, "start"])
time.sleep(0.3)
subprocess.check_call([daemon, "status"])
subprocess.check_call([daemon, "stop"])
success_file = os.path.join(self.temp_dir, "success")
self.assertTrue(os.path.exists(success_file))
if __name__ == "__main__":
unittest2.main()
|
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
self.pid_file = os.path.join(self.temp_dir, 'succubus.pid')
os.environ['PID_FILE'] = self.pid_file
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_daemon_start_status_stop(self):
daemon = "./src/integrationtest/python/shutdown_daemon.py"
subprocess.check_call([daemon, "start"])
time.sleep(0.3)
subprocess.check_call([daemon, "status"])
subprocess.check_call([daemon, "stop"])
success_file = os.path.join(self.temp_dir, "success")
self.assertTrue(os.path.exists(success_file))
if __name__ == "__main__":
unittest2.main()
|
Revert debugging changes: clean up tempfiles
|
Revert debugging changes: clean up tempfiles
|
Python
|
apache-2.0
|
ImmobilienScout24/succubus
|
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
self.pid_file = os.path.join(self.temp_dir, 'succubus.pid')
os.environ['PID_FILE'] = self.pid_file
def tearDown(self):
- #shutil.rmtree(self.temp_dir)
+ shutil.rmtree(self.temp_dir)
- print(self.temp_dir)
def test_daemon_start_status_stop(self):
daemon = "./src/integrationtest/python/shutdown_daemon.py"
subprocess.check_call([daemon, "start"])
time.sleep(0.3)
subprocess.check_call([daemon, "status"])
subprocess.check_call([daemon, "stop"])
success_file = os.path.join(self.temp_dir, "success")
self.assertTrue(os.path.exists(success_file))
if __name__ == "__main__":
unittest2.main()
|
Revert debugging changes: clean up tempfiles
|
## Code Before:
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
self.pid_file = os.path.join(self.temp_dir, 'succubus.pid')
os.environ['PID_FILE'] = self.pid_file
def tearDown(self):
#shutil.rmtree(self.temp_dir)
print(self.temp_dir)
def test_daemon_start_status_stop(self):
daemon = "./src/integrationtest/python/shutdown_daemon.py"
subprocess.check_call([daemon, "start"])
time.sleep(0.3)
subprocess.check_call([daemon, "status"])
subprocess.check_call([daemon, "stop"])
success_file = os.path.join(self.temp_dir, "success")
self.assertTrue(os.path.exists(success_file))
if __name__ == "__main__":
unittest2.main()
## Instruction:
Revert debugging changes: clean up tempfiles
## Code After:
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
self.pid_file = os.path.join(self.temp_dir, 'succubus.pid')
os.environ['PID_FILE'] = self.pid_file
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_daemon_start_status_stop(self):
daemon = "./src/integrationtest/python/shutdown_daemon.py"
subprocess.check_call([daemon, "start"])
time.sleep(0.3)
subprocess.check_call([daemon, "status"])
subprocess.check_call([daemon, "stop"])
success_file = os.path.join(self.temp_dir, "success")
self.assertTrue(os.path.exists(success_file))
if __name__ == "__main__":
unittest2.main()
|
from __future__ import print_function, absolute_import, division
import os
import shutil
import subprocess
import tempfile
import time
import unittest2
class ShutdownDaemonTests(unittest2.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="succubus-test")
self.pid_file = os.path.join(self.temp_dir, 'succubus.pid')
os.environ['PID_FILE'] = self.pid_file
def tearDown(self):
- #shutil.rmtree(self.temp_dir)
? -
+ shutil.rmtree(self.temp_dir)
- print(self.temp_dir)
def test_daemon_start_status_stop(self):
daemon = "./src/integrationtest/python/shutdown_daemon.py"
subprocess.check_call([daemon, "start"])
time.sleep(0.3)
subprocess.check_call([daemon, "status"])
subprocess.check_call([daemon, "stop"])
success_file = os.path.join(self.temp_dir, "success")
self.assertTrue(os.path.exists(success_file))
if __name__ == "__main__":
unittest2.main()
|
9560ccf476a887c20b2373eca52f38f186b6ed58
|
conanfile.py
|
conanfile.py
|
from conans import ConanFile, CMake
class NostalgiaConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable", "qt/5.14.1@bincrafters/stable", "sqlite3/3.31.0", "libiconv/1.16"
generators = "cmake", "cmake_find_package", "cmake_paths"
#default_options = {
# "sdl2:nas": False
#}
def requirements(self):
pass
|
from conans import ConanFile, CMake
class NostalgiaConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable"
generators = "cmake", "cmake_find_package", "cmake_paths"
#default_options = {
# "sdl2:nas": False
#}
|
Remove conan Qt, as it is currently being ignored
|
[nostalgia] Remove conan Qt, as it is currently being ignored
|
Python
|
mpl-2.0
|
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
|
from conans import ConanFile, CMake
class NostalgiaConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
- requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable", "qt/5.14.1@bincrafters/stable", "sqlite3/3.31.0", "libiconv/1.16"
+ requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable"
generators = "cmake", "cmake_find_package", "cmake_paths"
#default_options = {
# "sdl2:nas": False
#}
- def requirements(self):
- pass
-
|
Remove conan Qt, as it is currently being ignored
|
## Code Before:
from conans import ConanFile, CMake
class NostalgiaConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable", "qt/5.14.1@bincrafters/stable", "sqlite3/3.31.0", "libiconv/1.16"
generators = "cmake", "cmake_find_package", "cmake_paths"
#default_options = {
# "sdl2:nas": False
#}
def requirements(self):
pass
## Instruction:
Remove conan Qt, as it is currently being ignored
## Code After:
from conans import ConanFile, CMake
class NostalgiaConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable"
generators = "cmake", "cmake_find_package", "cmake_paths"
#default_options = {
# "sdl2:nas": False
#}
|
from conans import ConanFile, CMake
class NostalgiaConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
- requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable", "qt/5.14.1@bincrafters/stable", "sqlite3/3.31.0", "libiconv/1.16"
+ requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable"
generators = "cmake", "cmake_find_package", "cmake_paths"
#default_options = {
# "sdl2:nas": False
#}
-
- def requirements(self):
- pass
|
800706f5835293ee20dd9505d1d11c28eb38bbb2
|
tests/shipane_sdk/matchers/dataframe_matchers.py
|
tests/shipane_sdk/matchers/dataframe_matchers.py
|
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum [{0}]'.format(self._column))
def has_column(column):
return HasColumn(column)
class HasColumnMatches(BaseMatcher):
def __init__(self, column_pattern):
self._column_pattern = re.compile(column_pattern)
def _matches(self, df):
return df.filter(regex=self._column_pattern).columns.size > 0
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum matches [{0}]'.format(self._column_pattern))
def has_column_matches(column_pattern):
return HasColumnMatches(column_pattern)
class HasRow(BaseMatcher):
def __init__(self, row):
self._row = row
def _matches(self, df):
return self._row in df.index
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have row [%s]'.format(self._row))
def has_row(row):
return HasRow(row)
|
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum [{0}]'.format(self._column))
def has_column(column):
return HasColumn(column)
class HasColumnMatches(BaseMatcher):
def __init__(self, column_pattern):
self._column_pattern = re.compile(column_pattern)
def _matches(self, df):
return len(list(filter(self._column_pattern.match, df.columns.values))) > 0
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum matches [{0}]'.format(self._column_pattern))
def has_column_matches(column_pattern):
return HasColumnMatches(column_pattern)
class HasRow(BaseMatcher):
def __init__(self, row):
self._row = row
def _matches(self, df):
return self._row in df.index
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have row [%s]'.format(self._row))
def has_row(row):
return HasRow(row)
|
Fix HasColumn matcher for dataframe with duplicated columns
|
Fix HasColumn matcher for dataframe with duplicated columns
|
Python
|
mit
|
sinall/ShiPanE-Python-SDK,sinall/ShiPanE-Python-SDK
|
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum [{0}]'.format(self._column))
def has_column(column):
return HasColumn(column)
class HasColumnMatches(BaseMatcher):
def __init__(self, column_pattern):
self._column_pattern = re.compile(column_pattern)
def _matches(self, df):
- return df.filter(regex=self._column_pattern).columns.size > 0
+ return len(list(filter(self._column_pattern.match, df.columns.values))) > 0
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum matches [{0}]'.format(self._column_pattern))
def has_column_matches(column_pattern):
return HasColumnMatches(column_pattern)
class HasRow(BaseMatcher):
def __init__(self, row):
self._row = row
def _matches(self, df):
return self._row in df.index
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have row [%s]'.format(self._row))
def has_row(row):
return HasRow(row)
|
Fix HasColumn matcher for dataframe with duplicated columns
|
## Code Before:
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum [{0}]'.format(self._column))
def has_column(column):
return HasColumn(column)
class HasColumnMatches(BaseMatcher):
def __init__(self, column_pattern):
self._column_pattern = re.compile(column_pattern)
def _matches(self, df):
return df.filter(regex=self._column_pattern).columns.size > 0
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum matches [{0}]'.format(self._column_pattern))
def has_column_matches(column_pattern):
return HasColumnMatches(column_pattern)
class HasRow(BaseMatcher):
def __init__(self, row):
self._row = row
def _matches(self, df):
return self._row in df.index
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have row [%s]'.format(self._row))
def has_row(row):
return HasRow(row)
## Instruction:
Fix HasColumn matcher for dataframe with duplicated columns
## Code After:
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum [{0}]'.format(self._column))
def has_column(column):
return HasColumn(column)
class HasColumnMatches(BaseMatcher):
def __init__(self, column_pattern):
self._column_pattern = re.compile(column_pattern)
def _matches(self, df):
return len(list(filter(self._column_pattern.match, df.columns.values))) > 0
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum matches [{0}]'.format(self._column_pattern))
def has_column_matches(column_pattern):
return HasColumnMatches(column_pattern)
class HasRow(BaseMatcher):
def __init__(self, row):
self._row = row
def _matches(self, df):
return self._row in df.index
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have row [%s]'.format(self._row))
def has_row(row):
return HasRow(row)
|
import re
from hamcrest.core.base_matcher import BaseMatcher
class HasColumn(BaseMatcher):
def __init__(self, column):
self._column = column
def _matches(self, df):
return self._column in df.columns
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum [{0}]'.format(self._column))
def has_column(column):
return HasColumn(column)
class HasColumnMatches(BaseMatcher):
def __init__(self, column_pattern):
self._column_pattern = re.compile(column_pattern)
def _matches(self, df):
- return df.filter(regex=self._column_pattern).columns.size > 0
+ return len(list(filter(self._column_pattern.match, df.columns.values))) > 0
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have colum matches [{0}]'.format(self._column_pattern))
def has_column_matches(column_pattern):
return HasColumnMatches(column_pattern)
class HasRow(BaseMatcher):
def __init__(self, row):
self._row = row
def _matches(self, df):
return self._row in df.index
def describe_to(self, description):
description.append_text(u'Dataframe doesn\'t have row [%s]'.format(self._row))
def has_row(row):
return HasRow(row)
|
17015ecf48ec37909de6de2c299454fc89b592e9
|
tests/test_gmaps.py
|
tests/test_gmaps.py
|
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
|
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
def test_url_dict_no_zoom(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78)))
|
Add failing test for URL without zoom
|
Add failing test for URL without zoom
|
Python
|
mit
|
bfontaine/jinja2_maps
|
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
+ def test_url_dict_no_zoom(self):
+ url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z"
+ self.assertEquals(url,
+ gmaps_url(dict(latitude=12.34, longitude=56.78)))
+
|
Add failing test for URL without zoom
|
## Code Before:
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
## Instruction:
Add failing test for URL without zoom
## Code After:
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
def test_url_dict_no_zoom(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78)))
|
from base import TestCase
from jinja2_maps.gmaps import gmaps_url
class TestGmaps(TestCase):
def test_url_dict(self):
url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,42z"
self.assertEquals(url,
gmaps_url(dict(latitude=12.34, longitude=56.78), zoom=42))
+ def test_url_dict_no_zoom(self):
+ url = "https://www.google.com/maps/place/12.34,56.78/@12.34,56.78,16z"
+ self.assertEquals(url,
+ gmaps_url(dict(latitude=12.34, longitude=56.78)))
+
|
9ee301c525600cfeb8b8ca3d59f75ff9b7823008
|
test/buildbot/buildbot_config/master/schedulers.py
|
test/buildbot/buildbot_config/master/schedulers.py
|
from buildbot.changes.filter import ChangeFilter
from buildbot.schedulers.basic import SingleBranchScheduler
def get_schedulers():
# Run the unit tests for master
master_unit = SingleBranchScheduler(name="full",
change_filter=ChangeFilter(branch="master"),
treeStableTimer=60,
builderNames=["vagrant-master-unit"])
return [master_unit]
|
from buildbot.changes.filter import ChangeFilter
from buildbot.schedulers.basic import (
Dependent,
SingleBranchScheduler)
def get_schedulers():
# Run the unit tests for master
master_unit = SingleBranchScheduler(name="master-unit",
change_filter=ChangeFilter(branch="master"),
treeStableTimer=60,
builderNames=["vagrant-master-unit"])
master_acceptance = Dependent(name="master-acceptance",
upstream=master_unit,
builderNames=["vagrant-master-acceptance"])
return [master_unit, master_acceptance]
|
Make the acceptance tests dependent on the unit tests passing
|
Buildbot: Make the acceptance tests dependent on the unit tests passing
|
Python
|
mit
|
zsjohny/vagrant,bheuvel/vagrant,lonniev/vagrant,dharmab/vagrant,petems/vagrant,tjanez/vagrant,senglin/vagrant,benh57/vagrant,lonniev/vagrant,tomfanning/vagrant,cgvarela/vagrant,gpkfr/vagrant,krig/vagrant,philoserf/vagrant,philwrenn/vagrant,modulexcite/vagrant,tschortsch/vagrant,bmhatfield/vagrant,mitchellh/vagrant,tbarrongh/vagrant,apertoso/vagrant,marxarelli/vagrant,chrisroberts/vagrant,doy/vagrant,otagi/vagrant,gitebra/vagrant,mpoeter/vagrant,invernizzi-at-google/vagrant,bshurts/vagrant,mkuzmin/vagrant,chrisvire/vagrant,jfchevrette/vagrant,kalabiyau/vagrant,juiceinc/vagrant,dustymabe/vagrant,gpkfr/vagrant,tjanez/vagrant,fnewberg/vagrant,mpoeter/vagrant,muhanadra/vagrant,jberends/vagrant,mkuzmin/vagrant,wkolean/vagrant,mitchellh/vagrant,bmhatfield/vagrant,stephancom/vagrant,kamazee/vagrant,ferventcoder/vagrant,myrjola/vagrant,darkn3rd/vagrant,tknerr/vagrant,sideci-sample/sideci-sample-vagrant,kamigerami/vagrant,johntron/vagrant,krig/vagrant,Endika/vagrant,gpkfr/vagrant,crashlytics/vagrant,patrys/vagrant,sferik/vagrant,Endika/vagrant,sax/vagrant,jhoblitt/vagrant,tschortsch/vagrant,legal90/vagrant,h4ck3rm1k3/vagrant,teotihuacanada/vagrant,pwnall/vagrant,samphippen/vagrant,PatrickLang/vagrant,senglin/vagrant,mwrock/vagrant,blueyed/vagrant,janek-warchol/vagrant,jmanero/vagrant,Avira/vagrant,loren-osborn/vagrant,carlosefr/vagrant,h4ck3rm1k3/vagrant,genome21/vagrant,mkuzmin/vagrant,signed8bit/vagrant,aaam/vagrant,jean/vagrant,miguel250/vagrant,webcoyote/vagrant,tknerr/vagrant,blueyed/vagrant,kalabiyau/vagrant,theist/vagrant,shtouff/vagrant,invernizzi-at-google/vagrant,dharmab/vagrant,bshurts/vagrant,mwrock/vagrant,tschortsch/vagrant,bdwyertech/vagrant,wangfakang/vagrant,juiceinc/vagrant,channui/vagrant,dustymabe/vagrant,sax/vagrant,webcoyote/vagrant,philoserf/vagrant,bryson/vagrant,tbriggs-curse/vagrant,PatOShea/vagrant,ArloL/vagrant,doy/vagrant,mwrock/vagrant,Chhed13/vagrant,zsjohny/vagrant,vamegh/vagrant,sni/vagrant,taliesins/vagrant,iNecas/vagrant,ferventcoder/vagrant,tbriggs-curse/vagrant,muhanadra/vagrant,taliesins/vagrant,stephancom/vagrant,kalabiyau/vagrant,Chhunlong/vagrant,tbarrongh/vagrant,loren-osborn/vagrant,apertoso/vagrant,jhoblitt/vagrant,tbarrongh/vagrant,genome21/vagrant,channui/vagrant,krig/vagrant,gbarberi/vagrant,janek-warchol/vagrant,genome21/vagrant,chrisvire/vagrant,bdwyertech/vagrant,jean/vagrant,bdwyertech/vagrant,crashlytics/vagrant,blueyed/vagrant,Ninir/vagrant,myrjola/vagrant,cgvarela/vagrant,webcoyote/vagrant,jtopper/vagrant,gajdaw/vagrant,pwnall/vagrant,ArloL/vagrant,wkolean/vagrant,jean/vagrant,stephancom/vagrant,gitebra/vagrant,p0deje/vagrant,Avira/vagrant,nickryand/vagrant,evverx/vagrant,jmanero/vagrant,janek-warchol/vagrant,tomfanning/vagrant,evverx/vagrant,jean/vagrant,benizi/vagrant,Ninir/vagrant,obnoxxx/vagrant,tbriggs-curse/vagrant,miguel250/vagrant,mitchellh/vagrant,mwarren/vagrant,h4ck3rm1k3/vagrant,benh57/vagrant,jfchevrette/vagrant,teotihuacanada/vagrant,bdwyertech/vagrant,Chhed13/vagrant,doy/vagrant,otagi/vagrant,wangfakang/vagrant,shtouff/vagrant,sideci-sample/sideci-sample-vagrant,marxarelli/vagrant,mwarren/vagrant,sferik/vagrant,sferik/vagrant,bheuvel/vagrant,marxarelli/vagrant,lukebakken/vagrant,darkn3rd/vagrant,carlosefr/vagrant,sax/vagrant,fnewberg/vagrant,signed8bit/vagrant,johntron/vagrant,glensc/vagrant,dhoer/vagrant,Sgoettschkes/vagrant,carlosefr/vagrant,kamigerami/vagrant,p0deje/vagrant,samphippen/vagrant,dustymabe/vagrant,MiLk/vagrant,ferventcoder/vagrant,Sgoettschkes/vagrant,Endika/vagrant,bmhatfield/vagrant,gitebra/vagrant,janek-warchol/vagrant,aaam/vagrant,obnoxxx/vagrant,miguel250/vagrant,nickryand/vagrant,gajdaw/vagrant,lukebakken/vagrant,tknerr/vagrant,iNecas/vagrant,dhoer/vagrant,legal90/vagrant,jberends/vagrant,mitchellh/vagrant,mephaust/vagrant,h4ck3rm1k3/vagrant,tomfanning/vagrant,chrisroberts/vagrant,Avira/vagrant,benh57/vagrant,bheuvel/vagrant,miguel250/vagrant,vamegh/vagrant,apertoso/vagrant,modulexcite/vagrant,iNecas/vagrant,jtopper/vagrant,taliesins/vagrant,juiceinc/vagrant,wangfakang/vagrant,marxarelli/vagrant,webcoyote/vagrant,bshurts/vagrant,sni/vagrant,denisbr/vagrant,jfchevrette/vagrant,PatOShea/vagrant,jberends/vagrant,patrys/vagrant,teotihuacanada/vagrant,Chhunlong/vagrant,lonniev/vagrant,patrys/vagrant,wkolean/vagrant,fnewberg/vagrant,ianmiell/vagrant,philwrenn/vagrant,philwrenn/vagrant,jberends/vagrant,glensc/vagrant,jhoblitt/vagrant,cgvarela/vagrant,gbarberi/vagrant,philoserf/vagrant,chrisroberts/vagrant,dharmab/vagrant,loren-osborn/vagrant,tschortsch/vagrant,mwarren/vagrant,mwrock/vagrant,darkn3rd/vagrant,sni/vagrant,ianmiell/vagrant,senglin/vagrant,theist/vagrant,senglin/vagrant,evverx/vagrant,denisbr/vagrant,bheuvel/vagrant,myrjola/vagrant,fnewberg/vagrant,tbarrongh/vagrant,jmanero/vagrant,obnoxxx/vagrant,genome21/vagrant,ianmiell/vagrant,jkburges/vagrant,MiLk/vagrant,carlosefr/vagrant,mpoeter/vagrant,otagi/vagrant,aneeshusa/vagrant,stephancom/vagrant,jtopper/vagrant,msabramo/vagrant,jkburges/vagrant,chrisroberts/vagrant,cgvarela/vagrant,blueyed/vagrant,lukebakken/vagrant,legal90/vagrant,benizi/vagrant,juiceinc/vagrant,nickryand/vagrant,kamazee/vagrant,nickryand/vagrant,msabramo/vagrant,samphippen/vagrant,bryson/vagrant,invernizzi-at-google/vagrant,mkuzmin/vagrant,lukebakken/vagrant,mwarren/vagrant,TheBigBear/vagrant,Chhed13/vagrant,Chhed13/vagrant,gitebra/vagrant,benh57/vagrant,justincampbell/vagrant,ianmiell/vagrant,PatrickLang/vagrant,TheBigBear/vagrant,signed8bit/vagrant,jtopper/vagrant,shtouff/vagrant,theist/vagrant,tjanez/vagrant,Avira/vagrant,aneeshusa/vagrant,clinstid/vagrant,tjanez/vagrant,Chhunlong/vagrant,crashlytics/vagrant,MiLk/vagrant,bryson/vagrant,justincampbell/vagrant,rivy/vagrant,denisbr/vagrant,sni/vagrant,taliesins/vagrant,zsjohny/vagrant,ferventcoder/vagrant,msabramo/vagrant,muhanadra/vagrant,kalabiyau/vagrant,doy/vagrant,legal90/vagrant,BlakeMesdag/vagrant,apertoso/vagrant,PatOShea/vagrant,jfchevrette/vagrant,theist/vagrant,johntron/vagrant,chrisvire/vagrant,justincampbell/vagrant,vamegh/vagrant,rivy/vagrant,aaam/vagrant,aneeshusa/vagrant,kamazee/vagrant,dhoer/vagrant,mpoeter/vagrant,petems/vagrant,invernizzi-at-google/vagrant,TheBigBear/vagrant,TheBigBear/vagrant,gbarberi/vagrant,petems/vagrant,clinstid/vagrant,clinstid/vagrant,Chhunlong/vagrant,myrjola/vagrant,darkn3rd/vagrant,pwnall/vagrant,kamigerami/vagrant,jhoblitt/vagrant,sax/vagrant,wkolean/vagrant,lonniev/vagrant,otagi/vagrant,PatrickLang/vagrant,p0deje/vagrant,samphippen/vagrant,kamazee/vagrant,benizi/vagrant,philwrenn/vagrant,tbriggs-curse/vagrant,zsjohny/vagrant,modulexcite/vagrant,teotihuacanada/vagrant,petems/vagrant,tknerr/vagrant,aaam/vagrant,rivy/vagrant,signed8bit/vagrant,jkburges/vagrant,Endika/vagrant,channui/vagrant,modulexcite/vagrant,vamegh/vagrant,muhanadra/vagrant,rivy/vagrant,denisbr/vagrant,justincampbell/vagrant,msabramo/vagrant,philoserf/vagrant,loren-osborn/vagrant,sideci-sample/sideci-sample-vagrant,jkburges/vagrant,ArloL/vagrant,BlakeMesdag/vagrant,mephaust/vagrant,krig/vagrant,tomfanning/vagrant,jmanero/vagrant,PatOShea/vagrant,crashlytics/vagrant,BlakeMesdag/vagrant,gbarberi/vagrant,gajdaw/vagrant,mephaust/vagrant,aneeshusa/vagrant,shtouff/vagrant,ArloL/vagrant,bryson/vagrant,pwnall/vagrant,dustymabe/vagrant,chrisvire/vagrant,Sgoettschkes/vagrant,gpkfr/vagrant,kamigerami/vagrant,johntron/vagrant,wangfakang/vagrant,PatrickLang/vagrant,benizi/vagrant,mephaust/vagrant,Ninir/vagrant,dharmab/vagrant,dhoer/vagrant,Sgoettschkes/vagrant,bshurts/vagrant,patrys/vagrant
|
from buildbot.changes.filter import ChangeFilter
- from buildbot.schedulers.basic import SingleBranchScheduler
+ from buildbot.schedulers.basic import (
+ Dependent,
+ SingleBranchScheduler)
def get_schedulers():
# Run the unit tests for master
- master_unit = SingleBranchScheduler(name="full",
+ master_unit = SingleBranchScheduler(name="master-unit",
change_filter=ChangeFilter(branch="master"),
treeStableTimer=60,
builderNames=["vagrant-master-unit"])
- return [master_unit]
+ master_acceptance = Dependent(name="master-acceptance",
+ upstream=master_unit,
+ builderNames=["vagrant-master-acceptance"])
+ return [master_unit, master_acceptance]
+
|
Make the acceptance tests dependent on the unit tests passing
|
## Code Before:
from buildbot.changes.filter import ChangeFilter
from buildbot.schedulers.basic import SingleBranchScheduler
def get_schedulers():
# Run the unit tests for master
master_unit = SingleBranchScheduler(name="full",
change_filter=ChangeFilter(branch="master"),
treeStableTimer=60,
builderNames=["vagrant-master-unit"])
return [master_unit]
## Instruction:
Make the acceptance tests dependent on the unit tests passing
## Code After:
from buildbot.changes.filter import ChangeFilter
from buildbot.schedulers.basic import (
Dependent,
SingleBranchScheduler)
def get_schedulers():
# Run the unit tests for master
master_unit = SingleBranchScheduler(name="master-unit",
change_filter=ChangeFilter(branch="master"),
treeStableTimer=60,
builderNames=["vagrant-master-unit"])
master_acceptance = Dependent(name="master-acceptance",
upstream=master_unit,
builderNames=["vagrant-master-acceptance"])
return [master_unit, master_acceptance]
|
from buildbot.changes.filter import ChangeFilter
- from buildbot.schedulers.basic import SingleBranchScheduler
? ^^^^^^^^^^^^^^^^^^^^^
+ from buildbot.schedulers.basic import (
? ^
+ Dependent,
+ SingleBranchScheduler)
def get_schedulers():
# Run the unit tests for master
- master_unit = SingleBranchScheduler(name="full",
? ^ ^^
+ master_unit = SingleBranchScheduler(name="master-unit",
? ^^^^^^^ ^^^
change_filter=ChangeFilter(branch="master"),
treeStableTimer=60,
builderNames=["vagrant-master-unit"])
- return [master_unit]
+ master_acceptance = Dependent(name="master-acceptance",
+ upstream=master_unit,
+ builderNames=["vagrant-master-acceptance"])
+
+ return [master_unit, master_acceptance]
|
ab0141d4ea11e20482bb1ae9d5642ed0e6fc3fac
|
saleor/product/utils.py
|
saleor/product/utils.py
|
from django.core.exceptions import ObjectDoesNotExist
def get_attributes_display(variant, attributes):
display = {}
for attribute in attributes:
value = variant.get_attribute(attribute.pk)
if value:
try:
choice = attribute.values.get(pk=value)
except ObjectDoesNotExist:
pass
except ValueError:
display[attribute.pk] = value
else:
display[attribute.pk] = choice
return display
|
def get_attributes_display(variant, attributes):
display = {}
for attribute in attributes:
value = variant.get_attribute(attribute.pk)
if value:
choices = attribute.values.all()
if choices:
for choice in attribute.values.all():
if choice.pk == value:
display[attribute.pk] = choice
break
else:
display[attribute.pk] = value
return display
|
Reduce number of queries of getting attributes display
|
Reduce number of queries of getting attributes display
|
Python
|
bsd-3-clause
|
UITools/saleor,laosunhust/saleor,avorio/saleor,tfroehlich82/saleor,Drekscott/Motlaesaleor,arth-co/saleor,car3oon/saleor,rchav/vinerack,itbabu/saleor,spartonia/saleor,arth-co/saleor,HyperManTT/ECommerceSaleor,car3oon/saleor,taedori81/saleor,Drekscott/Motlaesaleor,josesanch/saleor,maferelo/saleor,taedori81/saleor,HyperManTT/ECommerceSaleor,jreigel/saleor,dashmug/saleor,UITools/saleor,laosunhust/saleor,paweltin/saleor,taedori81/saleor,mociepka/saleor,mociepka/saleor,jreigel/saleor,dashmug/saleor,tfroehlich82/saleor,paweltin/saleor,KenMutemi/saleor,maferelo/saleor,spartonia/saleor,taedori81/saleor,jreigel/saleor,avorio/saleor,avorio/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,Drekscott/Motlaesaleor,car3oon/saleor,itbabu/saleor,arth-co/saleor,rodrigozn/CW-Shop,UITools/saleor,mociepka/saleor,KenMutemi/saleor,KenMutemi/saleor,UITools/saleor,rchav/vinerack,laosunhust/saleor,spartonia/saleor,rodrigozn/CW-Shop,josesanch/saleor,tfroehlich82/saleor,dashmug/saleor,rchav/vinerack,avorio/saleor,josesanch/saleor,arth-co/saleor,paweltin/saleor,Drekscott/Motlaesaleor,spartonia/saleor,rodrigozn/CW-Shop,laosunhust/saleor,UITools/saleor,maferelo/saleor,paweltin/saleor
|
- from django.core.exceptions import ObjectDoesNotExist
-
-
def get_attributes_display(variant, attributes):
display = {}
for attribute in attributes:
value = variant.get_attribute(attribute.pk)
if value:
- try:
- choice = attribute.values.get(pk=value)
+ choices = attribute.values.all()
- except ObjectDoesNotExist:
- pass
- except ValueError:
+ if choices:
+ for choice in attribute.values.all():
+ if choice.pk == value:
+ display[attribute.pk] = choice
+ break
+ else:
display[attribute.pk] = value
- else:
- display[attribute.pk] = choice
return display
|
Reduce number of queries of getting attributes display
|
## Code Before:
from django.core.exceptions import ObjectDoesNotExist
def get_attributes_display(variant, attributes):
display = {}
for attribute in attributes:
value = variant.get_attribute(attribute.pk)
if value:
try:
choice = attribute.values.get(pk=value)
except ObjectDoesNotExist:
pass
except ValueError:
display[attribute.pk] = value
else:
display[attribute.pk] = choice
return display
## Instruction:
Reduce number of queries of getting attributes display
## Code After:
def get_attributes_display(variant, attributes):
display = {}
for attribute in attributes:
value = variant.get_attribute(attribute.pk)
if value:
choices = attribute.values.all()
if choices:
for choice in attribute.values.all():
if choice.pk == value:
display[attribute.pk] = choice
break
else:
display[attribute.pk] = value
return display
|
- from django.core.exceptions import ObjectDoesNotExist
-
-
def get_attributes_display(variant, attributes):
display = {}
for attribute in attributes:
value = variant.get_attribute(attribute.pk)
if value:
- try:
- choice = attribute.values.get(pk=value)
? ---- -------- ^^
+ choices = attribute.values.all()
? + ^^
- except ObjectDoesNotExist:
- pass
- except ValueError:
+ if choices:
+ for choice in attribute.values.all():
+ if choice.pk == value:
+ display[attribute.pk] = choice
+ break
+ else:
display[attribute.pk] = value
- else:
- display[attribute.pk] = choice
return display
|
cddb0309eaa0c31569f791b8b9f2c8666b65b8b4
|
openrcv/test/test_models.py
|
openrcv/test/test_models.py
|
from openrcv.models import ContestInfo
from openrcv.utiltest.helpers import UnitCase
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
from textwrap import dedent
from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
from openrcv.utils import StringInfo
from openrcv.utiltest.helpers import UnitCase
class BallotsResourceTest(UnitCase):
def test(self):
ballots = [1, 3, 2]
ballot_resource = BallotsResource(ballots)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, [1, 3, 2])
class BallotStreamResourceTest(UnitCase):
def test(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
ballot_resource = BallotStreamResource(ballot_info)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2\n', '3 1\n'])
def test_parse_default(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
parse = lambda line: line.strip()
ballot_resource = BallotStreamResource(ballot_info, parse=parse)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2', '3 1'])
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
Add tests for ballots resource classes.
|
Add tests for ballots resource classes.
|
Python
|
mit
|
cjerdonek/open-rcv,cjerdonek/open-rcv
|
+ from textwrap import dedent
+
+ from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
- from openrcv.models import ContestInfo
+ from openrcv.utils import StringInfo
from openrcv.utiltest.helpers import UnitCase
+
+
+ class BallotsResourceTest(UnitCase):
+
+ def test(self):
+ ballots = [1, 3, 2]
+ ballot_resource = BallotsResource(ballots)
+ with ballot_resource() as ballots:
+ ballots = list(ballots)
+ self.assertEqual(ballots, [1, 3, 2])
+
+
+ class BallotStreamResourceTest(UnitCase):
+
+ def test(self):
+ ballot_info = StringInfo("2 1 2\n3 1\n")
+ ballot_resource = BallotStreamResource(ballot_info)
+ with ballot_resource() as ballots:
+ ballots = list(ballots)
+ self.assertEqual(ballots, ['2 1 2\n', '3 1\n'])
+
+ def test_parse_default(self):
+ ballot_info = StringInfo("2 1 2\n3 1\n")
+ parse = lambda line: line.strip()
+ ballot_resource = BallotStreamResource(ballot_info, parse=parse)
+ with ballot_resource() as ballots:
+ ballots = list(ballots)
+ self.assertEqual(ballots, ['2 1 2', '3 1'])
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
Add tests for ballots resource classes.
|
## Code Before:
from openrcv.models import ContestInfo
from openrcv.utiltest.helpers import UnitCase
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
## Instruction:
Add tests for ballots resource classes.
## Code After:
from textwrap import dedent
from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
from openrcv.utils import StringInfo
from openrcv.utiltest.helpers import UnitCase
class BallotsResourceTest(UnitCase):
def test(self):
ballots = [1, 3, 2]
ballot_resource = BallotsResource(ballots)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, [1, 3, 2])
class BallotStreamResourceTest(UnitCase):
def test(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
ballot_resource = BallotStreamResource(ballot_info)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2\n', '3 1\n'])
def test_parse_default(self):
ballot_info = StringInfo("2 1 2\n3 1\n")
parse = lambda line: line.strip()
ballot_resource = BallotStreamResource(ballot_info, parse=parse)
with ballot_resource() as ballots:
ballots = list(ballots)
self.assertEqual(ballots, ['2 1 2', '3 1'])
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
+ from textwrap import dedent
+
+ from openrcv.models import BallotsResource, BallotStreamResource, ContestInfo
- from openrcv.models import ContestInfo
? ^^^^ ^^ ^^^^
+ from openrcv.utils import StringInfo
? ^^^ ^^^^ ^
from openrcv.utiltest.helpers import UnitCase
+
+
+ class BallotsResourceTest(UnitCase):
+
+ def test(self):
+ ballots = [1, 3, 2]
+ ballot_resource = BallotsResource(ballots)
+ with ballot_resource() as ballots:
+ ballots = list(ballots)
+ self.assertEqual(ballots, [1, 3, 2])
+
+
+ class BallotStreamResourceTest(UnitCase):
+
+ def test(self):
+ ballot_info = StringInfo("2 1 2\n3 1\n")
+ ballot_resource = BallotStreamResource(ballot_info)
+ with ballot_resource() as ballots:
+ ballots = list(ballots)
+ self.assertEqual(ballots, ['2 1 2\n', '3 1\n'])
+
+ def test_parse_default(self):
+ ballot_info = StringInfo("2 1 2\n3 1\n")
+ parse = lambda line: line.strip()
+ ballot_resource = BallotStreamResource(ballot_info, parse=parse)
+ with ballot_resource() as ballots:
+ ballots = list(ballots)
+ self.assertEqual(ballots, ['2 1 2', '3 1'])
class ContestInfoTest(UnitCase):
def test_get_candidates(self):
contest = ContestInfo()
contest.candidates = ["Alice", "Bob", "Carl"]
self.assertEqual(contest.get_candidates(), range(1, 4))
|
9c786c82671ade46e7af309fd597d5eac93a75b0
|
pycah/db/__init__.py
|
pycah/db/__init__.py
|
import psycopg2
c = psycopg2.connect(user='postgres', password='password')
c.set_session(autocommit=True)
cur = c.cursor()
try:
cur.execute('CREATE DATABASE pycah;')
c.commit()
c.close()
c = psycopg2.connect(database='pycah', user='postgres', password='password')
c.set_session(autocommit=True)
cur = c.cursor()
cur.execute(open('./pycah/db/create_database.sql').read())
c.commit()
c.close()
except psycopg2.ProgrammingError:
c.close()
connection = psycopg2.connect(database='pycah', user='postgres', password='password')
|
import psycopg2
c = psycopg2.connect(user='postgres', password='password', host='127.0.0.1')
c.set_session(autocommit=True)
cur = c.cursor()
try:
cur.execute('CREATE DATABASE pycah;')
c.commit()
c.close()
c = psycopg2.connect(database='pycah', user='postgres', password='password', host='127.0.0.1')
c.set_session(autocommit=True)
cur = c.cursor()
cur.execute(open('./pycah/db/create_database.sql').read())
c.commit()
c.close()
except psycopg2.ProgrammingError:
c.close()
connection = psycopg2.connect(database='pycah', user='postgres', password='password', host='127.0.0.1')
|
Fix database connectivity on Linux.
|
Fix database connectivity on Linux.
|
Python
|
mit
|
nhardy/pyCAH,nhardy/pyCAH,nhardy/pyCAH
|
import psycopg2
- c = psycopg2.connect(user='postgres', password='password')
+ c = psycopg2.connect(user='postgres', password='password', host='127.0.0.1')
c.set_session(autocommit=True)
cur = c.cursor()
try:
cur.execute('CREATE DATABASE pycah;')
c.commit()
c.close()
- c = psycopg2.connect(database='pycah', user='postgres', password='password')
+ c = psycopg2.connect(database='pycah', user='postgres', password='password', host='127.0.0.1')
c.set_session(autocommit=True)
cur = c.cursor()
cur.execute(open('./pycah/db/create_database.sql').read())
c.commit()
c.close()
except psycopg2.ProgrammingError:
c.close()
- connection = psycopg2.connect(database='pycah', user='postgres', password='password')
+ connection = psycopg2.connect(database='pycah', user='postgres', password='password', host='127.0.0.1')
|
Fix database connectivity on Linux.
|
## Code Before:
import psycopg2
c = psycopg2.connect(user='postgres', password='password')
c.set_session(autocommit=True)
cur = c.cursor()
try:
cur.execute('CREATE DATABASE pycah;')
c.commit()
c.close()
c = psycopg2.connect(database='pycah', user='postgres', password='password')
c.set_session(autocommit=True)
cur = c.cursor()
cur.execute(open('./pycah/db/create_database.sql').read())
c.commit()
c.close()
except psycopg2.ProgrammingError:
c.close()
connection = psycopg2.connect(database='pycah', user='postgres', password='password')
## Instruction:
Fix database connectivity on Linux.
## Code After:
import psycopg2
c = psycopg2.connect(user='postgres', password='password', host='127.0.0.1')
c.set_session(autocommit=True)
cur = c.cursor()
try:
cur.execute('CREATE DATABASE pycah;')
c.commit()
c.close()
c = psycopg2.connect(database='pycah', user='postgres', password='password', host='127.0.0.1')
c.set_session(autocommit=True)
cur = c.cursor()
cur.execute(open('./pycah/db/create_database.sql').read())
c.commit()
c.close()
except psycopg2.ProgrammingError:
c.close()
connection = psycopg2.connect(database='pycah', user='postgres', password='password', host='127.0.0.1')
|
import psycopg2
- c = psycopg2.connect(user='postgres', password='password')
+ c = psycopg2.connect(user='postgres', password='password', host='127.0.0.1')
? ++++++++++++++++++
c.set_session(autocommit=True)
cur = c.cursor()
try:
cur.execute('CREATE DATABASE pycah;')
c.commit()
c.close()
- c = psycopg2.connect(database='pycah', user='postgres', password='password')
+ c = psycopg2.connect(database='pycah', user='postgres', password='password', host='127.0.0.1')
? ++++++++++++++++++
c.set_session(autocommit=True)
cur = c.cursor()
cur.execute(open('./pycah/db/create_database.sql').read())
c.commit()
c.close()
except psycopg2.ProgrammingError:
c.close()
- connection = psycopg2.connect(database='pycah', user='postgres', password='password')
+ connection = psycopg2.connect(database='pycah', user='postgres', password='password', host='127.0.0.1')
? ++++++++++++++++++
|
a8bb719061a68b5d322868768203476c4ee1e9b9
|
gnocchi/cli.py
|
gnocchi/cli.py
|
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.connect()
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
Connect to database before upgrading it
|
Connect to database before upgrading it
This change ensure we are connected to the database before
we upgrade it.
Change-Id: Ia0be33892a99897ff294d004f4d935f3753e6200
|
Python
|
apache-2.0
|
idegtiarov/gnocchi-rep,leandroreox/gnocchi,sileht/gnocchi,idegtiarov/gnocchi-rep,gnocchixyz/gnocchi,sileht/gnocchi,idegtiarov/gnocchi-rep,gnocchixyz/gnocchi,leandroreox/gnocchi
|
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
+ indexer.connect()
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
Connect to database before upgrading it
|
## Code Before:
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
## Instruction:
Connect to database before upgrading it
## Code After:
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.connect()
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
from oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
+ indexer.connect()
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
b1b02a65cded26e7b0a6ddf207def5522297f7a7
|
__openerp__.py
|
__openerp__.py
|
{
'name': u"Asset Streamline",
'version': u"0.1",
'author': u"XCG Consulting",
'category': u"Custom Module",
'description': u"""Includes several integrity fixes and optimizations over
the standard module.
""",
'website': u"",
'depends': [
'base',
'account_streamline',
'account_asset',
'oemetasl',
],
'data': [
'data/asset_sequence.xml',
'security/ir.model.access.csv',
'wizard/account_asset_close_view.xml',
'wizard/account_asset_suspend_view.xml',
'wizard/account_asset_change_values_view.xml',
'wizard/account_asset_depreciation_wizard.xml',
'wizard/account_asset_change_duration_view.xml',
'views/account_asset_view.xml',
],
'demo': [
'demo/account_asset_demo.xml'
],
'css': [
'static/src/css/account_asset_streamline.css'
],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
{
'name': u"Asset Streamline",
'version': u"1.0",
'author': u"XCG Consulting",
'category': u"Custom Module",
'description': u"""Includes several integrity fixes and optimizations over
the standard module.
""",
'website': u"",
'depends': [
'base',
'account_streamline',
'analytic_structure'
'account_asset',
'oemetasl',
],
'data': [
'data/asset_sequence.xml',
'security/ir.model.access.csv',
'wizard/account_asset_close_view.xml',
'wizard/account_asset_suspend_view.xml',
'wizard/account_asset_change_values_view.xml',
'wizard/account_asset_depreciation_wizard.xml',
'wizard/account_asset_change_duration_view.xml',
'views/account_asset_view.xml',
],
'demo': [
'demo/account_asset_demo.xml'
],
'css': [
'static/src/css/account_asset_streamline.css'
],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Add dependency for 'analytic_structure' and change version to 1.0
|
Add dependency for 'analytic_structure' and change version to 1.0
|
Python
|
agpl-3.0
|
xcgd/account_asset_streamline
|
{
'name': u"Asset Streamline",
- 'version': u"0.1",
+ 'version': u"1.0",
'author': u"XCG Consulting",
'category': u"Custom Module",
'description': u"""Includes several integrity fixes and optimizations over
the standard module.
""",
'website': u"",
'depends': [
'base',
'account_streamline',
+ 'analytic_structure'
'account_asset',
'oemetasl',
],
'data': [
'data/asset_sequence.xml',
'security/ir.model.access.csv',
'wizard/account_asset_close_view.xml',
'wizard/account_asset_suspend_view.xml',
'wizard/account_asset_change_values_view.xml',
'wizard/account_asset_depreciation_wizard.xml',
'wizard/account_asset_change_duration_view.xml',
'views/account_asset_view.xml',
],
'demo': [
'demo/account_asset_demo.xml'
],
'css': [
'static/src/css/account_asset_streamline.css'
],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Add dependency for 'analytic_structure' and change version to 1.0
|
## Code Before:
{
'name': u"Asset Streamline",
'version': u"0.1",
'author': u"XCG Consulting",
'category': u"Custom Module",
'description': u"""Includes several integrity fixes and optimizations over
the standard module.
""",
'website': u"",
'depends': [
'base',
'account_streamline',
'account_asset',
'oemetasl',
],
'data': [
'data/asset_sequence.xml',
'security/ir.model.access.csv',
'wizard/account_asset_close_view.xml',
'wizard/account_asset_suspend_view.xml',
'wizard/account_asset_change_values_view.xml',
'wizard/account_asset_depreciation_wizard.xml',
'wizard/account_asset_change_duration_view.xml',
'views/account_asset_view.xml',
],
'demo': [
'demo/account_asset_demo.xml'
],
'css': [
'static/src/css/account_asset_streamline.css'
],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
## Instruction:
Add dependency for 'analytic_structure' and change version to 1.0
## Code After:
{
'name': u"Asset Streamline",
'version': u"1.0",
'author': u"XCG Consulting",
'category': u"Custom Module",
'description': u"""Includes several integrity fixes and optimizations over
the standard module.
""",
'website': u"",
'depends': [
'base',
'account_streamline',
'analytic_structure'
'account_asset',
'oemetasl',
],
'data': [
'data/asset_sequence.xml',
'security/ir.model.access.csv',
'wizard/account_asset_close_view.xml',
'wizard/account_asset_suspend_view.xml',
'wizard/account_asset_change_values_view.xml',
'wizard/account_asset_depreciation_wizard.xml',
'wizard/account_asset_change_duration_view.xml',
'views/account_asset_view.xml',
],
'demo': [
'demo/account_asset_demo.xml'
],
'css': [
'static/src/css/account_asset_streamline.css'
],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
{
'name': u"Asset Streamline",
- 'version': u"0.1",
? --
+ 'version': u"1.0",
? ++
'author': u"XCG Consulting",
'category': u"Custom Module",
'description': u"""Includes several integrity fixes and optimizations over
the standard module.
""",
'website': u"",
'depends': [
'base',
'account_streamline',
+ 'analytic_structure'
'account_asset',
'oemetasl',
],
'data': [
'data/asset_sequence.xml',
'security/ir.model.access.csv',
'wizard/account_asset_close_view.xml',
'wizard/account_asset_suspend_view.xml',
'wizard/account_asset_change_values_view.xml',
'wizard/account_asset_depreciation_wizard.xml',
'wizard/account_asset_change_duration_view.xml',
'views/account_asset_view.xml',
],
'demo': [
'demo/account_asset_demo.xml'
],
'css': [
'static/src/css/account_asset_streamline.css'
],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
254ecc95cdd0c2809328634e50882ea42fb32105
|
tests/test_utils.py
|
tests/test_utils.py
|
import pytest
from bonsai.utils import escape_filter_exp
from bonsai.utils import escape_attribute_value
def test_escape_attribute_value():
""" Test escaping special characters in attribute values. """
assert (
escape_attribute_value(" dummy=test,something+somethingelse")
== r"\ dummy\=test\,something\+somethingelse"
)
assert escape_attribute_value("#dummy=test ") == r"\#dummy\=test\ "
assert escape_attribute_value(r"term\0") == r"term\\0"
def test_escape_filter_exp():
""" Test escaping filter expressions. """
assert escape_filter_exp("(parenthesis)") == "\\28parenthesis\\29"
assert escape_filter_exp("cn=*") == "cn=\\2A"
assert escape_filter_exp("\\backslash") == "\\5Cbackslash"
assert escape_filter_exp("term\0") == "term\\0"
|
import pytest
from bonsai.utils import escape_filter_exp
from bonsai.utils import escape_attribute_value
from bonsai.utils import set_connect_async
def test_escape_attribute_value():
""" Test escaping special characters in attribute values. """
assert (
escape_attribute_value(" dummy=test,something+somethingelse")
== r"\ dummy\=test\,something\+somethingelse"
)
assert escape_attribute_value("#dummy=test ") == r"\#dummy\=test\ "
assert escape_attribute_value(r"term\0") == r"term\\0"
def test_escape_filter_exp():
""" Test escaping filter expressions. """
assert escape_filter_exp("(parenthesis)") == "\\28parenthesis\\29"
assert escape_filter_exp("cn=*") == "cn=\\2A"
assert escape_filter_exp("\\backslash") == "\\5Cbackslash"
assert escape_filter_exp("term\0") == "term\\0"
def test_set_async_connect(client):
""" Dummy test for set_connect_async. """
with pytest.raises(TypeError):
set_connect_async("true")
set_connect_async(False)
conn = client.connect()
assert conn is not None
|
Add simple call test for set_connect_async
|
Add simple call test for set_connect_async
|
Python
|
mit
|
Noirello/PyLDAP,Noirello/bonsai,Noirello/PyLDAP,Noirello/PyLDAP,Noirello/bonsai,Noirello/bonsai
|
import pytest
from bonsai.utils import escape_filter_exp
from bonsai.utils import escape_attribute_value
+ from bonsai.utils import set_connect_async
def test_escape_attribute_value():
""" Test escaping special characters in attribute values. """
assert (
escape_attribute_value(" dummy=test,something+somethingelse")
== r"\ dummy\=test\,something\+somethingelse"
)
assert escape_attribute_value("#dummy=test ") == r"\#dummy\=test\ "
assert escape_attribute_value(r"term\0") == r"term\\0"
def test_escape_filter_exp():
""" Test escaping filter expressions. """
assert escape_filter_exp("(parenthesis)") == "\\28parenthesis\\29"
assert escape_filter_exp("cn=*") == "cn=\\2A"
assert escape_filter_exp("\\backslash") == "\\5Cbackslash"
assert escape_filter_exp("term\0") == "term\\0"
+
+ def test_set_async_connect(client):
+ """ Dummy test for set_connect_async. """
+ with pytest.raises(TypeError):
+ set_connect_async("true")
+ set_connect_async(False)
+ conn = client.connect()
+ assert conn is not None
|
Add simple call test for set_connect_async
|
## Code Before:
import pytest
from bonsai.utils import escape_filter_exp
from bonsai.utils import escape_attribute_value
def test_escape_attribute_value():
""" Test escaping special characters in attribute values. """
assert (
escape_attribute_value(" dummy=test,something+somethingelse")
== r"\ dummy\=test\,something\+somethingelse"
)
assert escape_attribute_value("#dummy=test ") == r"\#dummy\=test\ "
assert escape_attribute_value(r"term\0") == r"term\\0"
def test_escape_filter_exp():
""" Test escaping filter expressions. """
assert escape_filter_exp("(parenthesis)") == "\\28parenthesis\\29"
assert escape_filter_exp("cn=*") == "cn=\\2A"
assert escape_filter_exp("\\backslash") == "\\5Cbackslash"
assert escape_filter_exp("term\0") == "term\\0"
## Instruction:
Add simple call test for set_connect_async
## Code After:
import pytest
from bonsai.utils import escape_filter_exp
from bonsai.utils import escape_attribute_value
from bonsai.utils import set_connect_async
def test_escape_attribute_value():
""" Test escaping special characters in attribute values. """
assert (
escape_attribute_value(" dummy=test,something+somethingelse")
== r"\ dummy\=test\,something\+somethingelse"
)
assert escape_attribute_value("#dummy=test ") == r"\#dummy\=test\ "
assert escape_attribute_value(r"term\0") == r"term\\0"
def test_escape_filter_exp():
""" Test escaping filter expressions. """
assert escape_filter_exp("(parenthesis)") == "\\28parenthesis\\29"
assert escape_filter_exp("cn=*") == "cn=\\2A"
assert escape_filter_exp("\\backslash") == "\\5Cbackslash"
assert escape_filter_exp("term\0") == "term\\0"
def test_set_async_connect(client):
""" Dummy test for set_connect_async. """
with pytest.raises(TypeError):
set_connect_async("true")
set_connect_async(False)
conn = client.connect()
assert conn is not None
|
import pytest
from bonsai.utils import escape_filter_exp
from bonsai.utils import escape_attribute_value
+ from bonsai.utils import set_connect_async
def test_escape_attribute_value():
""" Test escaping special characters in attribute values. """
assert (
escape_attribute_value(" dummy=test,something+somethingelse")
== r"\ dummy\=test\,something\+somethingelse"
)
assert escape_attribute_value("#dummy=test ") == r"\#dummy\=test\ "
assert escape_attribute_value(r"term\0") == r"term\\0"
def test_escape_filter_exp():
""" Test escaping filter expressions. """
assert escape_filter_exp("(parenthesis)") == "\\28parenthesis\\29"
assert escape_filter_exp("cn=*") == "cn=\\2A"
assert escape_filter_exp("\\backslash") == "\\5Cbackslash"
assert escape_filter_exp("term\0") == "term\\0"
+
+
+ def test_set_async_connect(client):
+ """ Dummy test for set_connect_async. """
+ with pytest.raises(TypeError):
+ set_connect_async("true")
+ set_connect_async(False)
+ conn = client.connect()
+ assert conn is not None
|
1e8f9a95badc1e2b558bae7570ef9bc23f26a0df
|
pyhaystack/info.py
|
pyhaystack/info.py
|
__author__ = 'Christian Tremblay, @sjlongland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
__version__ = '0.71.1.8.2'
__license__ = 'LGPL'
|
__author__ = 'Christian Tremblay, Stuart J. Longland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
__version__ = '0.72'
__license__ = 'LGPL'
|
Modify version to 0.72 to mark change
|
Modify version to 0.72 to mark change
Signed-off-by: Christian Tremblay <[email protected]>
|
Python
|
apache-2.0
|
ChristianTremblay/pyhaystack,vrtsystems/pyhaystack,ChristianTremblay/pyhaystack
|
- __author__ = 'Christian Tremblay, @sjlongland, @sudo-Whateverman, Igor'
+ __author__ = 'Christian Tremblay, Stuart J. Longland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
- __version__ = '0.71.1.8.2'
+ __version__ = '0.72'
__license__ = 'LGPL'
|
Modify version to 0.72 to mark change
|
## Code Before:
__author__ = 'Christian Tremblay, @sjlongland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
__version__ = '0.71.1.8.2'
__license__ = 'LGPL'
## Instruction:
Modify version to 0.72 to mark change
## Code After:
__author__ = 'Christian Tremblay, Stuart J. Longland, @sudo-Whateverman, Igor'
__author_email__ = '[email protected]'
__version__ = '0.72'
__license__ = 'LGPL'
|
- __author__ = 'Christian Tremblay, @sjlongland, @sudo-Whateverman, Igor'
? ^^^^
+ __author__ = 'Christian Tremblay, Stuart J. Longland, @sudo-Whateverman, Igor'
? ^^^^^^^^^^^
__author_email__ = '[email protected]'
- __version__ = '0.71.1.8.2'
? ------
+ __version__ = '0.72'
__license__ = 'LGPL'
|
ab4333ad10713b0df25e0ff9bb46da3a0749326f
|
analyser/tasks.py
|
analyser/tasks.py
|
import os
import time
import requests
from krunchr.vendors.celery import celery
@celery.task
def get_file(url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
print path
with open(path, 'w') as f:
f.write(response.content)
|
import os
import time
import rethinkdb as r
import requests
from krunchr.vendors.celery import celery, db
@celery.task(bind=True)
def get_file(self, url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
with open(path, 'w') as f:
f.write(response.content)
r.table('jobs').filter({
'task_id': self.request.id
}).update({'state': 'done'}).run(db)
|
Update job state when we finish the task
|
Update job state when we finish the task
|
Python
|
apache-2.0
|
vtemian/kruncher
|
import os
import time
+ import rethinkdb as r
import requests
- from krunchr.vendors.celery import celery
+ from krunchr.vendors.celery import celery, db
- @celery.task
+ @celery.task(bind=True)
- def get_file(url, path):
+ def get_file(self, url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
- print path
with open(path, 'w') as f:
f.write(response.content)
+ r.table('jobs').filter({
+ 'task_id': self.request.id
+ }).update({'state': 'done'}).run(db)
+
|
Update job state when we finish the task
|
## Code Before:
import os
import time
import requests
from krunchr.vendors.celery import celery
@celery.task
def get_file(url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
print path
with open(path, 'w') as f:
f.write(response.content)
## Instruction:
Update job state when we finish the task
## Code After:
import os
import time
import rethinkdb as r
import requests
from krunchr.vendors.celery import celery, db
@celery.task(bind=True)
def get_file(self, url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
with open(path, 'w') as f:
f.write(response.content)
r.table('jobs').filter({
'task_id': self.request.id
}).update({'state': 'done'}).run(db)
|
import os
import time
+ import rethinkdb as r
import requests
- from krunchr.vendors.celery import celery
+ from krunchr.vendors.celery import celery, db
? ++++
- @celery.task
+ @celery.task(bind=True)
- def get_file(url, path):
+ def get_file(self, url, path):
? ++++++
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
- print path
with open(path, 'w') as f:
f.write(response.content)
+
+ r.table('jobs').filter({
+ 'task_id': self.request.id
+ }).update({'state': 'done'}).run(db)
|
5cf0b19d67a667d4e0d48a12f0ee94f3387cfa37
|
tests/test_helpers.py
|
tests/test_helpers.py
|
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
|
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
def test_return_function(self):
fn = helpers.import_function('os.path.join')
self.assertEqual(callable(fn), True)
|
Add test to ensure talons.helpers.import_function returns a callable
|
Add test to ensure talons.helpers.import_function returns a callable
|
Python
|
apache-2.0
|
talons/talons,jaypipes/talons
|
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
+ def test_return_function(self):
+ fn = helpers.import_function('os.path.join')
+ self.assertEqual(callable(fn), True)
+
|
Add test to ensure talons.helpers.import_function returns a callable
|
## Code Before:
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
## Instruction:
Add test to ensure talons.helpers.import_function returns a callable
## Code After:
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
def test_return_function(self):
fn = helpers.import_function('os.path.join')
self.assertEqual(callable(fn), True)
|
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('sys.noexisting')
def test_not_callable(self):
with testtools.ExpectedException(TypeError):
helpers.import_function('sys.stdout')
+
+ def test_return_function(self):
+ fn = helpers.import_function('os.path.join')
+ self.assertEqual(callable(fn), True)
|
1a150cb57171212358b84e351a0c073baa83d9fd
|
Home/xsOros.py
|
Home/xsOros.py
|
def checkio(array):
if array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]:
return array[0][0]
if array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]:
return array[1][1]
if array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]:
return array[2][2]
return "D"
if __name__ == '__main__':
assert checkio([
"X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio([
"OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio([
"OOX",
"XXO",
"OXX"]) == "D", "Draw"
|
def checkio(array):
if (array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]) and array[0][0] != '.':
return array[0][0]
if (array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]) and array[1][1] != '.':
return array[1][1]
if (array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]) and array[2][2] != '.' :
return array[2][2]
return "D"
if __name__ == '__main__':
assert checkio([
"X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio([
"OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio([
"OOX",
"XXO",
"OXX"]) == "D", "Draw"
assert checkio([
"...",
"XXO",
"XXO"
]) == "D", "Draw"
|
Fix the issue on Xs or Os problem.
|
Fix the issue on Xs or Os problem.
|
Python
|
mit
|
edwardzhu/checkio-solution
|
def checkio(array):
- if array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]:
+ if (array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]) and array[0][0] != '.':
return array[0][0]
- if array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]:
+ if (array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]) and array[1][1] != '.':
return array[1][1]
- if array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]:
+ if (array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]) and array[2][2] != '.' :
return array[2][2]
return "D"
if __name__ == '__main__':
assert checkio([
"X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio([
"OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio([
"OOX",
"XXO",
"OXX"]) == "D", "Draw"
+ assert checkio([
+ "...",
+ "XXO",
+ "XXO"
+ ]) == "D", "Draw"
|
Fix the issue on Xs or Os problem.
|
## Code Before:
def checkio(array):
if array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]:
return array[0][0]
if array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]:
return array[1][1]
if array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]:
return array[2][2]
return "D"
if __name__ == '__main__':
assert checkio([
"X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio([
"OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio([
"OOX",
"XXO",
"OXX"]) == "D", "Draw"
## Instruction:
Fix the issue on Xs or Os problem.
## Code After:
def checkio(array):
if (array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]) and array[0][0] != '.':
return array[0][0]
if (array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]) and array[1][1] != '.':
return array[1][1]
if (array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]) and array[2][2] != '.' :
return array[2][2]
return "D"
if __name__ == '__main__':
assert checkio([
"X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio([
"OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio([
"OOX",
"XXO",
"OXX"]) == "D", "Draw"
assert checkio([
"...",
"XXO",
"XXO"
]) == "D", "Draw"
|
def checkio(array):
- if array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]:
+ if (array[0][0] == array[0][1] == array[0][2] or array[0][0] == array[1][0] == array[2][0] or array[0][0] == array[1][1] == array[2][2]) and array[0][0] != '.':
? + ++++++++++++++++++++++++
return array[0][0]
- if array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]:
+ if (array[1][0] == array[1][1] == array[1][2] or array[0][1] == array[1][1] == array[2][1] or array[2][0] == array[1][1] == array[0][2]) and array[1][1] != '.':
? + ++++++++++++++++++++++++
return array[1][1]
- if array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]:
+ if (array[2][0] == array[2][1] == array[2][2] or array[0][2] == array[1][2] == array[2][2]) and array[2][2] != '.' :
? + +++++++++++++++++++++++++
return array[2][2]
return "D"
if __name__ == '__main__':
assert checkio([
"X.O",
"XX.",
"XOO"]) == "X", "Xs wins"
assert checkio([
"OO.",
"XOX",
"XOX"]) == "O", "Os wins"
assert checkio([
"OOX",
"XXO",
"OXX"]) == "D", "Draw"
+ assert checkio([
+ "...",
+ "XXO",
+ "XXO"
+ ]) == "D", "Draw"
|
84f4626a623283c3c4d98d9be0ccd69fe837f772
|
download_data.py
|
download_data.py
|
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
def download_extract(url, into):
fname = download(url, into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/tosato/'
datadir = here('data')
# First, download the Tosato datasets.
download_extract(baseurl + 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
download_extract(baseurl + 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
download_extract(baseurl + 'HIIT6HeadPose.tar.bz2', into=datadir)
download_extract(baseurl + 'HOC.tar.bz2', into=datadir)
download_extract(baseurl + 'HOCoffee.tar.bz2', into=datadir)
download_extract(baseurl + 'IHDPHeadPose.tar.bz2', into=datadir)
download_extract(baseurl + 'QMULPoseHeads.tar.bz2', into=datadir)
|
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
def download_extract(urlbase, name, into):
print("Downloading " + name)
fname = download(os.path.join(urlbase, name), into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/BiternionNets/'
datadir = here('data')
# First, download the Tosato datasets.
download_extract(baseurl, 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
download_extract(baseurl, 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
download_extract(baseurl, 'HIIT6HeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'HOC.tar.bz2', into=datadir)
download_extract(baseurl, 'HOCoffee.tar.bz2', into=datadir)
download_extract(baseurl, 'IHDPHeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'QMULPoseHeads.tar.bz2', into=datadir)
print("Done.")
|
Update download URL and add more output to downloader.
|
Update download URL and add more output to downloader.
|
Python
|
mit
|
lucasb-eyer/BiternionNet
|
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
- def download_extract(url, into):
+ def download_extract(urlbase, name, into):
- fname = download(url, into)
+ print("Downloading " + name)
+ fname = download(os.path.join(urlbase, name), into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
- baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/tosato/'
+ baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/BiternionNets/'
datadir = here('data')
# First, download the Tosato datasets.
- download_extract(baseurl + 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
+ download_extract(baseurl, 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
- download_extract(baseurl + 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
+ download_extract(baseurl, 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
- download_extract(baseurl + 'HIIT6HeadPose.tar.bz2', into=datadir)
+ download_extract(baseurl, 'HIIT6HeadPose.tar.bz2', into=datadir)
- download_extract(baseurl + 'HOC.tar.bz2', into=datadir)
+ download_extract(baseurl, 'HOC.tar.bz2', into=datadir)
- download_extract(baseurl + 'HOCoffee.tar.bz2', into=datadir)
+ download_extract(baseurl, 'HOCoffee.tar.bz2', into=datadir)
- download_extract(baseurl + 'IHDPHeadPose.tar.bz2', into=datadir)
+ download_extract(baseurl, 'IHDPHeadPose.tar.bz2', into=datadir)
- download_extract(baseurl + 'QMULPoseHeads.tar.bz2', into=datadir)
+ download_extract(baseurl, 'QMULPoseHeads.tar.bz2', into=datadir)
+ print("Done.")
+
|
Update download URL and add more output to downloader.
|
## Code Before:
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
def download_extract(url, into):
fname = download(url, into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/tosato/'
datadir = here('data')
# First, download the Tosato datasets.
download_extract(baseurl + 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
download_extract(baseurl + 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
download_extract(baseurl + 'HIIT6HeadPose.tar.bz2', into=datadir)
download_extract(baseurl + 'HOC.tar.bz2', into=datadir)
download_extract(baseurl + 'HOCoffee.tar.bz2', into=datadir)
download_extract(baseurl + 'IHDPHeadPose.tar.bz2', into=datadir)
download_extract(baseurl + 'QMULPoseHeads.tar.bz2', into=datadir)
## Instruction:
Update download URL and add more output to downloader.
## Code After:
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
def download_extract(urlbase, name, into):
print("Downloading " + name)
fname = download(os.path.join(urlbase, name), into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/BiternionNets/'
datadir = here('data')
# First, download the Tosato datasets.
download_extract(baseurl, 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
download_extract(baseurl, 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
download_extract(baseurl, 'HIIT6HeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'HOC.tar.bz2', into=datadir)
download_extract(baseurl, 'HOCoffee.tar.bz2', into=datadir)
download_extract(baseurl, 'IHDPHeadPose.tar.bz2', into=datadir)
download_extract(baseurl, 'QMULPoseHeads.tar.bz2', into=datadir)
print("Done.")
|
from lbtoolbox.download import download
import os
import inspect
import tarfile
def here(f):
me = inspect.getsourcefile(here)
return os.path.join(os.path.dirname(os.path.abspath(me)), f)
- def download_extract(url, into):
+ def download_extract(urlbase, name, into):
? ++++++++++
- fname = download(url, into)
+ print("Downloading " + name)
+ fname = download(os.path.join(urlbase, name), into)
print("Extracting...")
with tarfile.open(fname) as f:
f.extractall(path=into)
if __name__ == '__main__':
- baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/tosato/'
? ---
+ baseurl = 'https://omnomnom.vision.rwth-aachen.de/data/BiternionNets/'
? ++ ++++ ++++
datadir = here('data')
# First, download the Tosato datasets.
- download_extract(baseurl + 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
? ^^
+ download_extract(baseurl, 'CAVIARShoppingCenterFullOccl.tar.bz2', into=datadir)
? ^
- download_extract(baseurl + 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
? ^^
+ download_extract(baseurl, 'CAVIARShoppingCenterFull.tar.bz2', into=datadir)
? ^
- download_extract(baseurl + 'HIIT6HeadPose.tar.bz2', into=datadir)
? ^^
+ download_extract(baseurl, 'HIIT6HeadPose.tar.bz2', into=datadir)
? ^
- download_extract(baseurl + 'HOC.tar.bz2', into=datadir)
? ^^
+ download_extract(baseurl, 'HOC.tar.bz2', into=datadir)
? ^
- download_extract(baseurl + 'HOCoffee.tar.bz2', into=datadir)
? ^^
+ download_extract(baseurl, 'HOCoffee.tar.bz2', into=datadir)
? ^
- download_extract(baseurl + 'IHDPHeadPose.tar.bz2', into=datadir)
? ^^
+ download_extract(baseurl, 'IHDPHeadPose.tar.bz2', into=datadir)
? ^
- download_extract(baseurl + 'QMULPoseHeads.tar.bz2', into=datadir)
? ^^
+ download_extract(baseurl, 'QMULPoseHeads.tar.bz2', into=datadir)
? ^
+
+ print("Done.")
|
cdc5627cfad3b4fb413bed86d76dbe083e6727a7
|
hnotebook/notebooks/admin.py
|
hnotebook/notebooks/admin.py
|
from django.contrib import admin
# Register your models here.
|
from django.contrib import admin
from .models import Notebook
class NotebookAdmin(admin.ModelAdmin):
model = Notebook
admin.site.register(Notebook, NotebookAdmin)
|
Add Admin for Notebook model
|
Add Admin for Notebook model
|
Python
|
mit
|
marcwebbie/hnotebook
|
from django.contrib import admin
- # Register your models here.
+ from .models import Notebook
+ class NotebookAdmin(admin.ModelAdmin):
+ model = Notebook
+
+ admin.site.register(Notebook, NotebookAdmin)
+
|
Add Admin for Notebook model
|
## Code Before:
from django.contrib import admin
# Register your models here.
## Instruction:
Add Admin for Notebook model
## Code After:
from django.contrib import admin
from .models import Notebook
class NotebookAdmin(admin.ModelAdmin):
model = Notebook
admin.site.register(Notebook, NotebookAdmin)
|
from django.contrib import admin
- # Register your models here.
+ from .models import Notebook
+
+ class NotebookAdmin(admin.ModelAdmin):
+ model = Notebook
+
+ admin.site.register(Notebook, NotebookAdmin)
|
d2ac548441523e2ed4d0ac824e5972ae48be3b19
|
packages/Python/lldbsuite/test/lang/swift/closure_shortcuts/TestClosureShortcuts.py
|
packages/Python/lldbsuite/test/lang/swift/closure_shortcuts/TestClosureShortcuts.py
|
import lldbsuite.test.lldbinline as lldbinline
from lldbsuite.test.decorators import *
lldbinline.MakeInlineTest(__file__, globals(),
decorators=[swiftTest,skipUnlessDarwin])
|
import lldbsuite.test.lldbinline as lldbinline
from lldbsuite.test.decorators import *
lldbinline.MakeInlineTest(__file__, globals(),
decorators=[swiftTest])
|
Fix typo and run everywhere.
|
Fix typo and run everywhere.
|
Python
|
apache-2.0
|
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
|
import lldbsuite.test.lldbinline as lldbinline
from lldbsuite.test.decorators import *
lldbinline.MakeInlineTest(__file__, globals(),
- decorators=[swiftTest,skipUnlessDarwin])
+ decorators=[swiftTest])
|
Fix typo and run everywhere.
|
## Code Before:
import lldbsuite.test.lldbinline as lldbinline
from lldbsuite.test.decorators import *
lldbinline.MakeInlineTest(__file__, globals(),
decorators=[swiftTest,skipUnlessDarwin])
## Instruction:
Fix typo and run everywhere.
## Code After:
import lldbsuite.test.lldbinline as lldbinline
from lldbsuite.test.decorators import *
lldbinline.MakeInlineTest(__file__, globals(),
decorators=[swiftTest])
|
import lldbsuite.test.lldbinline as lldbinline
from lldbsuite.test.decorators import *
lldbinline.MakeInlineTest(__file__, globals(),
- decorators=[swiftTest,skipUnlessDarwin])
? -----------------
+ decorators=[swiftTest])
|
50d69badbaeb41736269c99f7b301f09c9b24ecb
|
testing/test_models.py
|
testing/test_models.py
|
from k2catalogue import models
def test_safe_float_good():
assert models.safe_float("2") == 2.0
def test_safe_float_bad():
assert models.safe_float('this is not convertable to a float') is None
|
from k2catalogue import models
def test_safe_float_good():
assert models.safe_float("2") == 2.0
def test_safe_float_bad():
assert models.safe_float('this is not convertable to a float') is None
def test_proposal_printing():
proposal = models.Proposal(proposal_id='abc')
assert repr(proposal) == '<Proposal: abc>'
|
Add test for proposal printing
|
Add test for proposal printing
|
Python
|
mit
|
mindriot101/k2catalogue
|
from k2catalogue import models
def test_safe_float_good():
assert models.safe_float("2") == 2.0
def test_safe_float_bad():
assert models.safe_float('this is not convertable to a float') is None
+ def test_proposal_printing():
+ proposal = models.Proposal(proposal_id='abc')
+ assert repr(proposal) == '<Proposal: abc>'
|
Add test for proposal printing
|
## Code Before:
from k2catalogue import models
def test_safe_float_good():
assert models.safe_float("2") == 2.0
def test_safe_float_bad():
assert models.safe_float('this is not convertable to a float') is None
## Instruction:
Add test for proposal printing
## Code After:
from k2catalogue import models
def test_safe_float_good():
assert models.safe_float("2") == 2.0
def test_safe_float_bad():
assert models.safe_float('this is not convertable to a float') is None
def test_proposal_printing():
proposal = models.Proposal(proposal_id='abc')
assert repr(proposal) == '<Proposal: abc>'
|
from k2catalogue import models
def test_safe_float_good():
assert models.safe_float("2") == 2.0
def test_safe_float_bad():
assert models.safe_float('this is not convertable to a float') is None
+ def test_proposal_printing():
+ proposal = models.Proposal(proposal_id='abc')
+ assert repr(proposal) == '<Proposal: abc>'
|
d0d79ae8073b3d363b3b99e0e42659662b2bf4eb
|
go/conversation/models.py
|
go/conversation/models.py
|
from django.db import models
from go.contacts.models import Contact
class Conversation(models.Model):
"""A conversation with an audience"""
user = models.ForeignKey('auth.User')
subject = models.CharField('Conversation Name', max_length=255)
message = models.TextField('Message')
start_date = models.DateField()
start_time = models.TimeField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
groups = models.ManyToManyField('contacts.ContactGroup')
previewcontacts = models.ManyToManyField('contacts.Contact')
def people(self):
return Contact.objects.filter(groups__in=self.groups.all())
class Meta:
ordering = ['-updated_at']
get_latest_by = 'updated_at'
def __unicode__(self):
return self.subject
|
from django.db import models
from go.contacts.models import Contact
class Conversation(models.Model):
"""A conversation with an audience"""
user = models.ForeignKey('auth.User')
subject = models.CharField('Conversation Name', max_length=255)
message = models.TextField('Message')
start_date = models.DateField()
start_time = models.TimeField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
groups = models.ManyToManyField('contacts.ContactGroup')
previewcontacts = models.ManyToManyField('contacts.Contact')
def people(self):
return Contact.objects.filter(groups__in=self.groups.all())
class Meta:
ordering = ['-updated_at']
get_latest_by = 'updated_at'
def __unicode__(self):
return self.subject
class MessageBatch(models.Model):
"""A set of messages that belong to a conversation.
The full data about messages is stored in the Vumi API
message store. This table is just a link from Vumi Go's
conversations to the Vumi API's batches.
"""
conversation = models.ForeignKey(Conversation)
batch_id = models.CharField(max_length=32) # uuid4 as hex
|
Add link from conversations to message batches.
|
Add link from conversations to message batches.
|
Python
|
bsd-3-clause
|
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
|
from django.db import models
from go.contacts.models import Contact
class Conversation(models.Model):
"""A conversation with an audience"""
user = models.ForeignKey('auth.User')
subject = models.CharField('Conversation Name', max_length=255)
message = models.TextField('Message')
start_date = models.DateField()
start_time = models.TimeField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
groups = models.ManyToManyField('contacts.ContactGroup')
previewcontacts = models.ManyToManyField('contacts.Contact')
def people(self):
return Contact.objects.filter(groups__in=self.groups.all())
class Meta:
ordering = ['-updated_at']
get_latest_by = 'updated_at'
def __unicode__(self):
return self.subject
+
+ class MessageBatch(models.Model):
+ """A set of messages that belong to a conversation.
+
+ The full data about messages is stored in the Vumi API
+ message store. This table is just a link from Vumi Go's
+ conversations to the Vumi API's batches.
+ """
+ conversation = models.ForeignKey(Conversation)
+ batch_id = models.CharField(max_length=32) # uuid4 as hex
+
|
Add link from conversations to message batches.
|
## Code Before:
from django.db import models
from go.contacts.models import Contact
class Conversation(models.Model):
"""A conversation with an audience"""
user = models.ForeignKey('auth.User')
subject = models.CharField('Conversation Name', max_length=255)
message = models.TextField('Message')
start_date = models.DateField()
start_time = models.TimeField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
groups = models.ManyToManyField('contacts.ContactGroup')
previewcontacts = models.ManyToManyField('contacts.Contact')
def people(self):
return Contact.objects.filter(groups__in=self.groups.all())
class Meta:
ordering = ['-updated_at']
get_latest_by = 'updated_at'
def __unicode__(self):
return self.subject
## Instruction:
Add link from conversations to message batches.
## Code After:
from django.db import models
from go.contacts.models import Contact
class Conversation(models.Model):
"""A conversation with an audience"""
user = models.ForeignKey('auth.User')
subject = models.CharField('Conversation Name', max_length=255)
message = models.TextField('Message')
start_date = models.DateField()
start_time = models.TimeField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
groups = models.ManyToManyField('contacts.ContactGroup')
previewcontacts = models.ManyToManyField('contacts.Contact')
def people(self):
return Contact.objects.filter(groups__in=self.groups.all())
class Meta:
ordering = ['-updated_at']
get_latest_by = 'updated_at'
def __unicode__(self):
return self.subject
class MessageBatch(models.Model):
"""A set of messages that belong to a conversation.
The full data about messages is stored in the Vumi API
message store. This table is just a link from Vumi Go's
conversations to the Vumi API's batches.
"""
conversation = models.ForeignKey(Conversation)
batch_id = models.CharField(max_length=32) # uuid4 as hex
|
from django.db import models
from go.contacts.models import Contact
class Conversation(models.Model):
"""A conversation with an audience"""
user = models.ForeignKey('auth.User')
subject = models.CharField('Conversation Name', max_length=255)
message = models.TextField('Message')
start_date = models.DateField()
start_time = models.TimeField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
groups = models.ManyToManyField('contacts.ContactGroup')
previewcontacts = models.ManyToManyField('contacts.Contact')
def people(self):
return Contact.objects.filter(groups__in=self.groups.all())
class Meta:
ordering = ['-updated_at']
get_latest_by = 'updated_at'
def __unicode__(self):
return self.subject
+
+
+ class MessageBatch(models.Model):
+ """A set of messages that belong to a conversation.
+
+ The full data about messages is stored in the Vumi API
+ message store. This table is just a link from Vumi Go's
+ conversations to the Vumi API's batches.
+ """
+ conversation = models.ForeignKey(Conversation)
+ batch_id = models.CharField(max_length=32) # uuid4 as hex
|
7b798d923c5a5af37e9f4c2d92881e907f2c0c74
|
python/testData/inspections/PyUnresolvedReferencesInspection/ignoredUnresolvedReferenceInUnionType.py
|
python/testData/inspections/PyUnresolvedReferencesInspection/ignoredUnresolvedReferenceInUnionType.py
|
class A:
pass
a = A()
print(a.f<caret>oo)
x = A() or None
print(x.foo)
|
class A:
pass
a = A()
print(a.f<caret>oo)
def func(c):
x = A() if c else None
return x.foo
|
Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936
|
Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936
|
Python
|
apache-2.0
|
asedunov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,caot/intellij-community,diorcety/intellij-community,asedunov/intellij-community,supersven/intellij-community,signed/intellij-community,signed/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,caot/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,samthor/intellij-community,asedunov/intellij-community,retomerz/intellij-community,robovm/robovm-studio,robovm/robovm-studio,hurricup/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,semonte/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,signed/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,fitermay/intellij-community,dslomov/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,allotria/intellij-community,ryano144/intellij-community,diorcety/intellij-community,caot/intellij-community,Distrotech/intellij-community,slisson/intellij-community,slisson/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,samthor/intellij-community,allotria/intellij-community,da1z/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,caot/intellij-community,vladmm/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,xfournet/intellij-community,dslomov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,fitermay/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,da1z/intellij-community,tmpgit/intellij-community,da1z/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,semonte/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,izonder/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,da1z/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,adedayo/intellij-community,retomerz/intellij-community,allotria/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,semonte/intellij-community,petteyg/intellij-community,retomerz/intellij-community,robovm/robovm-studio,fnouama/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,da1z/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ryano144/intellij-community,supersven/intellij-community,dslomov/intellij-community,caot/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,izonder/intellij-community,robovm/robovm-studio,ibinti/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,caot/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,semonte/intellij-community,fitermay/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,caot/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,holmes/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,apixandru/intellij-community,fitermay/intellij-community,asedunov/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,semonte/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,retomerz/intellij-community,caot/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,ibinti/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,fnouama/intellij-community,fitermay/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,xfournet/intellij-community,clumsy/intellij-community,diorcety/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,diorcety/intellij-community,izonder/intellij-community,ryano144/intellij-community,holmes/intellij-community,samthor/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,signed/intellij-community,fnouama/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,supersven/intellij-community,youdonghai/intellij-community,signed/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,semonte/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,apixandru/intellij-community,fitermay/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ibinti/intellij-community,fnouama/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,slisson/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,allotria/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ibinti/intellij-community,hurricup/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,signed/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,retomerz/intellij-community,fnouama/intellij-community,samthor/intellij-community,holmes/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,izonder/intellij-community,akosyakov/intellij-community,allotria/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,allotria/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,jagguli/intellij-community,amith01994/intellij-community,signed/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,kool79/intellij-community,semonte/intellij-community,clumsy/intellij-community,slisson/intellij-community,dslomov/intellij-community,vladmm/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,samthor/intellij-community,FHannes/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,xfournet/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,fitermay/intellij-community,apixandru/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,signed/intellij-community,apixandru/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,FHannes/intellij-community,samthor/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,holmes/intellij-community,fnouama/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,hurricup/intellij-community,vladmm/intellij-community,slisson/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,signed/intellij-community,kdwink/intellij-community,jagguli/intellij-community,petteyg/intellij-community,dslomov/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,adedayo/intellij-community,caot/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,FHannes/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,allotria/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,allotria/intellij-community,izonder/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,signed/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,allotria/intellij-community,blademainer/intellij-community,supersven/intellij-community,adedayo/intellij-community,kool79/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ibinti/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,semonte/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,slisson/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,xfournet/intellij-community,vladmm/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,semonte/intellij-community,FHannes/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,apixandru/intellij-community,petteyg/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,samthor/intellij-community,caot/intellij-community,gnuhub/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,da1z/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,allotria/intellij-community,clumsy/intellij-community,hurricup/intellij-community
|
class A:
pass
a = A()
print(a.f<caret>oo)
- x = A() or None
- print(x.foo)
+ def func(c):
+ x = A() if c else None
+ return x.foo
|
Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936
|
## Code Before:
class A:
pass
a = A()
print(a.f<caret>oo)
x = A() or None
print(x.foo)
## Instruction:
Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936
## Code After:
class A:
pass
a = A()
print(a.f<caret>oo)
def func(c):
x = A() if c else None
return x.foo
|
class A:
pass
a = A()
print(a.f<caret>oo)
- x = A() or None
- print(x.foo)
+ def func(c):
+ x = A() if c else None
+ return x.foo
|
bd4e1c3f511ac1163e39d99fdc8e70f261023c44
|
setup/create_player_seasons.py
|
setup/create_player_seasons.py
|
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
players = session.query(Player).all()[:25]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
print(len(plr_seasons))
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
|
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
players = session.query(Player).all()[:]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
|
Update player season retrieval function
|
Update player season retrieval function
|
Python
|
mit
|
leaffan/pynhldb
|
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
- players = session.query(Player).all()[:25]
+ players = session.query(Player).all()[:]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
- print(len(plr_seasons))
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
|
Update player season retrieval function
|
## Code Before:
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
players = session.query(Player).all()[:25]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
print(len(plr_seasons))
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
## Instruction:
Update player season retrieval function
## Code After:
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
players = session.query(Player).all()[:]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
|
import concurrent.futures
from db.common import session_scope
from db.player import Player
from utils.player_data_retriever import PlayerDataRetriever
def create_player_seasons(simulation=False):
data_retriever = PlayerDataRetriever()
with session_scope() as session:
- players = session.query(Player).all()[:25]
? --
+ players = session.query(Player).all()[:]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads:
future_tasks = {
threads.submit(
data_retriever.retrieve_player_seasons,
player.player_id, simulation
): player for player in players
}
for future in concurrent.futures.as_completed(future_tasks):
try:
plr_seasons = future.result()
- print(len(plr_seasons))
except Exception as e:
print("Concurrent task generated an exception: %s" % e)
|
a1d8a81bbd25404b1109688bded9bea923ba6771
|
formly/tests/urls.py
|
formly/tests/urls.py
|
from django.conf.urls import include, url
urlpatterns = [
url(r"^", include("formly.urls", namespace="formly")),
]
|
from django.conf.urls import include, url
from django.views.generic import TemplateView
urlpatterns = [
url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"),
url(r"^", include("formly.urls", namespace="formly")),
]
|
Add "home" url for testing
|
Add "home" url for testing
|
Python
|
bsd-3-clause
|
eldarion/formly,eldarion/formly
|
from django.conf.urls import include, url
+ from django.views.generic import TemplateView
urlpatterns = [
+ url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"),
url(r"^", include("formly.urls", namespace="formly")),
]
|
Add "home" url for testing
|
## Code Before:
from django.conf.urls import include, url
urlpatterns = [
url(r"^", include("formly.urls", namespace="formly")),
]
## Instruction:
Add "home" url for testing
## Code After:
from django.conf.urls import include, url
from django.views.generic import TemplateView
urlpatterns = [
url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"),
url(r"^", include("formly.urls", namespace="formly")),
]
|
from django.conf.urls import include, url
+ from django.views.generic import TemplateView
urlpatterns = [
+ url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"),
url(r"^", include("formly.urls", namespace="formly")),
]
|
41a04ca380dca8d2b358f84bd7982f0ea01ac7f2
|
camoco/Config.py
|
camoco/Config.py
|
import os
import configparser
global cf
cf = configparser.ConfigParser()
cf._interpolation = configparser.ExtendedInterpolation()
cf_file = os.path.expanduser('~/.camoco.conf')
default_config = '''
[options]
basedir = ~/.camoco/
testdir = ~/.camoco/
[logging]
log_level = verbose
[test]
refgen = Zm5bFGS
cob = NewRoot
ontology = ZmIonome
term = Fe57
gene = GRMZM2G000014
'''
# Check to see if
if not os.path.isfile(cf_file):
with open(cf_file, 'w') as CF:
print(default_config,file=CF)
cf.read(os.path.expanduser('~/.camoco.conf'))
|
import os
import configparser
global cf
cf = configparser.ConfigParser()
cf._interpolation = configparser.ExtendedInterpolation()
cf_file = os.path.expanduser('~/.camoco.conf')
default_config = '''
[options]
basedir = ~/.camoco/
testdir = ~/.camoco/
[logging]
log_level = verbose
[test]
force = True
refgen = Zm5bFGS
cob = NewRoot
ontology = ZmIonome
term = Fe57
gene = GRMZM2G000014
'''
# Check to see if
if not os.path.isfile(cf_file):
with open(cf_file, 'w') as CF:
print(default_config,file=CF)
cf.read(os.path.expanduser('~/.camoco.conf'))
|
Add force option for testing.
|
Add force option for testing.
|
Python
|
mit
|
schae234/Camoco,schae234/Camoco
|
import os
import configparser
global cf
cf = configparser.ConfigParser()
cf._interpolation = configparser.ExtendedInterpolation()
cf_file = os.path.expanduser('~/.camoco.conf')
default_config = '''
[options]
basedir = ~/.camoco/
testdir = ~/.camoco/
[logging]
log_level = verbose
[test]
+ force = True
refgen = Zm5bFGS
cob = NewRoot
ontology = ZmIonome
term = Fe57
gene = GRMZM2G000014
'''
# Check to see if
if not os.path.isfile(cf_file):
with open(cf_file, 'w') as CF:
print(default_config,file=CF)
cf.read(os.path.expanduser('~/.camoco.conf'))
|
Add force option for testing.
|
## Code Before:
import os
import configparser
global cf
cf = configparser.ConfigParser()
cf._interpolation = configparser.ExtendedInterpolation()
cf_file = os.path.expanduser('~/.camoco.conf')
default_config = '''
[options]
basedir = ~/.camoco/
testdir = ~/.camoco/
[logging]
log_level = verbose
[test]
refgen = Zm5bFGS
cob = NewRoot
ontology = ZmIonome
term = Fe57
gene = GRMZM2G000014
'''
# Check to see if
if not os.path.isfile(cf_file):
with open(cf_file, 'w') as CF:
print(default_config,file=CF)
cf.read(os.path.expanduser('~/.camoco.conf'))
## Instruction:
Add force option for testing.
## Code After:
import os
import configparser
global cf
cf = configparser.ConfigParser()
cf._interpolation = configparser.ExtendedInterpolation()
cf_file = os.path.expanduser('~/.camoco.conf')
default_config = '''
[options]
basedir = ~/.camoco/
testdir = ~/.camoco/
[logging]
log_level = verbose
[test]
force = True
refgen = Zm5bFGS
cob = NewRoot
ontology = ZmIonome
term = Fe57
gene = GRMZM2G000014
'''
# Check to see if
if not os.path.isfile(cf_file):
with open(cf_file, 'w') as CF:
print(default_config,file=CF)
cf.read(os.path.expanduser('~/.camoco.conf'))
|
import os
import configparser
global cf
cf = configparser.ConfigParser()
cf._interpolation = configparser.ExtendedInterpolation()
cf_file = os.path.expanduser('~/.camoco.conf')
default_config = '''
[options]
basedir = ~/.camoco/
testdir = ~/.camoco/
[logging]
log_level = verbose
[test]
+ force = True
refgen = Zm5bFGS
cob = NewRoot
ontology = ZmIonome
term = Fe57
gene = GRMZM2G000014
'''
# Check to see if
if not os.path.isfile(cf_file):
with open(cf_file, 'w') as CF:
print(default_config,file=CF)
cf.read(os.path.expanduser('~/.camoco.conf'))
|
5864b503bced36d51ab911d5b306284dbc0cdb13
|
rest_framework_simplejwt/settings.py
|
rest_framework_simplejwt/settings.py
|
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'TOKEN_TYPE_CLAIM': 'token_type',
'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(days=1),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=3),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'SECRET_KEY': settings.SECRET_KEY,
# Undocumented settings. Changing these may lead to unexpected behavior.
# Make sure you know what you're doing. These might become part of the
# public API eventually but that would require some adjustments.
'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken',
'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend',
'ALGORITHM': 'HS256',
}
IMPORT_STRING_SETTINGS = (
'AUTH_TOKEN_CLASS',
'TOKEN_BACKEND_CLASS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
|
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'TOKEN_TYPE_CLAIM': 'token_type',
'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'SECRET_KEY': settings.SECRET_KEY,
# Undocumented settings. Changing these may lead to unexpected behavior.
# Make sure you know what you're doing. These might become part of the
# public API eventually but that would require some adjustments.
'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken',
'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend',
'ALGORITHM': 'HS256',
}
IMPORT_STRING_SETTINGS = (
'AUTH_TOKEN_CLASS',
'TOKEN_BACKEND_CLASS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
|
Make sliding token lifetime defaults a bit more conservative
|
Make sliding token lifetime defaults a bit more conservative
|
Python
|
mit
|
davesque/django-rest-framework-simplejwt,davesque/django-rest-framework-simplejwt
|
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'TOKEN_TYPE_CLAIM': 'token_type',
+ 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
- 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
- 'SLIDING_TOKEN_LIFETIME': timedelta(days=1),
+ 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
- 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=3),
+ 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'SECRET_KEY': settings.SECRET_KEY,
# Undocumented settings. Changing these may lead to unexpected behavior.
# Make sure you know what you're doing. These might become part of the
# public API eventually but that would require some adjustments.
'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken',
'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend',
'ALGORITHM': 'HS256',
}
IMPORT_STRING_SETTINGS = (
'AUTH_TOKEN_CLASS',
'TOKEN_BACKEND_CLASS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
|
Make sliding token lifetime defaults a bit more conservative
|
## Code Before:
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'TOKEN_TYPE_CLAIM': 'token_type',
'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(days=1),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=3),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'SECRET_KEY': settings.SECRET_KEY,
# Undocumented settings. Changing these may lead to unexpected behavior.
# Make sure you know what you're doing. These might become part of the
# public API eventually but that would require some adjustments.
'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken',
'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend',
'ALGORITHM': 'HS256',
}
IMPORT_STRING_SETTINGS = (
'AUTH_TOKEN_CLASS',
'TOKEN_BACKEND_CLASS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
## Instruction:
Make sliding token lifetime defaults a bit more conservative
## Code After:
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'TOKEN_TYPE_CLAIM': 'token_type',
'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'SECRET_KEY': settings.SECRET_KEY,
# Undocumented settings. Changing these may lead to unexpected behavior.
# Make sure you know what you're doing. These might become part of the
# public API eventually but that would require some adjustments.
'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken',
'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend',
'ALGORITHM': 'HS256',
}
IMPORT_STRING_SETTINGS = (
'AUTH_TOKEN_CLASS',
'TOKEN_BACKEND_CLASS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
|
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'TOKEN_TYPE_CLAIM': 'token_type',
+ 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
- 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp',
- 'SLIDING_TOKEN_LIFETIME': timedelta(days=1),
? ^^^ ^
+ 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
? ^^^^^^ ^
- 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=3),
? ^
+ 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
? ^
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'SECRET_KEY': settings.SECRET_KEY,
# Undocumented settings. Changing these may lead to unexpected behavior.
# Make sure you know what you're doing. These might become part of the
# public API eventually but that would require some adjustments.
'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken',
'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend',
'ALGORITHM': 'HS256',
}
IMPORT_STRING_SETTINGS = (
'AUTH_TOKEN_CLASS',
'TOKEN_BACKEND_CLASS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
|
4761d359a28630d0fe378d50e52aad66e88d3a36
|
DeepFried2/utils.py
|
DeepFried2/utils.py
|
import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where):
params, _ = module.parameters()
_np.savez_compressed(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
|
import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where, compress=False):
params, _ = module.parameters()
savefn = _np.savez_compressed if compress else _np.savez
savefn(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
|
Make the compression optional, as it slows down.
|
Make the compression optional, as it slows down.
|
Python
|
mit
|
elPistolero/DeepFried2,lucasb-eyer/DeepFried2,Pandoro/DeepFried2,yobibyte/DeepFried2
|
import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
- def save_params(module, where):
+ def save_params(module, where, compress=False):
params, _ = module.parameters()
+
+ savefn = _np.savez_compressed if compress else _np.savez
- _np.savez_compressed(where, params=[p.get_value() for p in params])
+ savefn(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
|
Make the compression optional, as it slows down.
|
## Code Before:
import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where):
params, _ = module.parameters()
_np.savez_compressed(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
## Instruction:
Make the compression optional, as it slows down.
## Code After:
import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
def save_params(module, where, compress=False):
params, _ = module.parameters()
savefn = _np.savez_compressed if compress else _np.savez
savefn(where, params=[p.get_value() for p in params])
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
|
import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param = _th.shared(val, name=name)
grad_name = 'grad_' + name if name is not None else None
grad_param = _th.shared(_np.zeros_like(val), name=grad_name)
return param, grad_param
def create_param_state_as(other, initial_value=0, prefix='state_for_'):
return _th.shared(other.get_value()*0 + initial_value,
broadcastable=other.broadcastable,
name=prefix + str(other.name)
)
def count_params(module):
params, _ = module.parameters()
return sum(p.get_value().size for p in params)
- def save_params(module, where):
+ def save_params(module, where, compress=False):
? ++++++++++++++++
params, _ = module.parameters()
+
+ savefn = _np.savez_compressed if compress else _np.savez
- _np.savez_compressed(where, params=[p.get_value() for p in params])
? ---- ^^^^^^^^^^^^
+ savefn(where, params=[p.get_value() for p in params])
? ^^
def load_params(module, fromwhere):
params, _ = module.parameters()
with _np.load(fromwhere) as f:
for p, v in zip(params, f['params']):
p.set_value(v)
|
06d9171b2244e4dd9d5e1883101d7ec3e05be4b2
|
bitfield/apps.py
|
bitfield/apps.py
|
from django.apps import AppConfig
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
|
import django
from django.apps import AppConfig
django.setup()
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
|
Add django.setup to the AppConfig
|
Add django.setup to the AppConfig
|
Python
|
apache-2.0
|
Elec/django-bitfield,disqus/django-bitfield,joshowen/django-bitfield
|
+ import django
from django.apps import AppConfig
+
+
+ django.setup()
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
|
Add django.setup to the AppConfig
|
## Code Before:
from django.apps import AppConfig
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
## Instruction:
Add django.setup to the AppConfig
## Code After:
import django
from django.apps import AppConfig
django.setup()
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
|
+ import django
from django.apps import AppConfig
+
+
+ django.setup()
class BitFieldAppConfig(AppConfig):
name = 'bitfield'
verbose_name = "Bit Field"
|
66fe6f98c079490d2d5de4c161da1d8b3801cda4
|
monasca_persister/conf/influxdb.py
|
monasca_persister/conf/influxdb.py
|
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
cfg.IPOpt('ip_address',
help='ip address to influxdb'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
|
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
cfg.HostAddressOpt('ip_address',
help='Valid IP address or hostname '
'to InfluxDB instance'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
|
Allow hostnames to be used as ip_address
|
Allow hostnames to be used as ip_address
Previously introduced change for monasca-persister
had enforced the IPAddress as the only type one can
configure influxdb.ip_address property with.
Following change makes it possible to use also hostname.
Using IPAdress is still possible.
Change-Id: Ib0d7f19b3ac2dcb7c84923872d94f180cda58b2b
|
Python
|
apache-2.0
|
stackforge/monasca-persister,openstack/monasca-persister,stackforge/monasca-persister,stackforge/monasca-persister,openstack/monasca-persister,openstack/monasca-persister
|
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
- cfg.IPOpt('ip_address',
+ cfg.HostAddressOpt('ip_address',
- help='ip address to influxdb'),
+ help='Valid IP address or hostname '
+ 'to InfluxDB instance'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
|
Allow hostnames to be used as ip_address
|
## Code Before:
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
cfg.IPOpt('ip_address',
help='ip address to influxdb'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
## Instruction:
Allow hostnames to be used as ip_address
## Code After:
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
cfg.HostAddressOpt('ip_address',
help='Valid IP address or hostname '
'to InfluxDB instance'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
|
from oslo_config import cfg
influxdb_opts = [
cfg.StrOpt('database_name',
help='database name where metrics are stored',
default='mon'),
- cfg.IPOpt('ip_address',
? ^^
+ cfg.HostAddressOpt('ip_address',
? ^^^^^^^^^^^
- help='ip address to influxdb'),
+ help='Valid IP address or hostname '
+ 'to InfluxDB instance'),
cfg.PortOpt('port',
help='port to influxdb',
default=8086),
cfg.StrOpt('user',
help='influxdb user ',
default='mon_persister'),
cfg.StrOpt('password',
secret=True,
help='influxdb password')]
influxdb_group = cfg.OptGroup(name='influxdb',
title='influxdb')
def register_opts(conf):
conf.register_group(influxdb_group)
conf.register_opts(influxdb_opts, influxdb_group)
def list_opts():
return influxdb_group, influxdb_opts
|
b8cf6f096e14ee7311c18117d57f98b1745b8105
|
pyuvdata/__init__.py
|
pyuvdata/__init__.py
|
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
__version__ = version.version
|
from __future__ import absolute_import, division, print_function
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
__version__ = version.version
|
Move warning filter above other imports in init
|
Move warning filter above other imports in init
|
Python
|
bsd-2-clause
|
HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata
|
from __future__ import absolute_import, division, print_function
+
+ # Filter annoying Cython warnings that serve no good purpose. see numpy#432
+ import warnings
+ warnings.filterwarnings("ignore", message="numpy.dtype size changed")
+ warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
- # Filter annoying Cython warnings that serve no good purpose. see numpy#432
- import warnings
- warnings.filterwarnings("ignore", message="numpy.dtype size changed")
- warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
-
__version__ = version.version
|
Move warning filter above other imports in init
|
## Code Before:
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
__version__ = version.version
## Instruction:
Move warning filter above other imports in init
## Code After:
from __future__ import absolute_import, division, print_function
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
__version__ = version.version
|
from __future__ import absolute_import, division, print_function
+
+ # Filter annoying Cython warnings that serve no good purpose. see numpy#432
+ import warnings
+ warnings.filterwarnings("ignore", message="numpy.dtype size changed")
+ warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
- # Filter annoying Cython warnings that serve no good purpose. see numpy#432
- import warnings
- warnings.filterwarnings("ignore", message="numpy.dtype size changed")
- warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
-
__version__ = version.version
|
3d1cef9e56d7fac8a1b89861b7443e4ca660e4a8
|
nova/ipv6/api.py
|
nova/ipv6/api.py
|
from nova import flags
from nova import utils
FLAGS = flags.FLAGS
flags.DEFINE_string('ipv6_backend',
'rfc2462',
'Backend to use for IPv6 generation')
def reset_backend():
global IMPL
IMPL = utils.LazyPluggable(FLAGS['ipv6_backend'],
rfc2462='nova.ipv6.rfc2462',
account_identifier='nova.ipv6.account_identifier')
def to_global(prefix, mac, project_id):
return IMPL.to_global(prefix, mac, project_id)
def to_mac(ipv6_address):
return IMPL.to_mac(ipv6_address)
reset_backend()
|
from nova import flags
from nova import utils
FLAGS = flags.FLAGS
flags.DEFINE_string('ipv6_backend',
'rfc2462',
'Backend to use for IPv6 generation')
def reset_backend():
global IMPL
IMPL = utils.LazyPluggable(FLAGS['ipv6_backend'],
rfc2462='nova.ipv6.rfc2462',
account_identifier='nova.ipv6.account_identifier')
def to_global(prefix, mac, project_id):
return IMPL.to_global(prefix, mac, project_id)
def to_mac(ipv6_address):
return IMPL.to_mac(ipv6_address)
reset_backend()
|
Reduce indentation to avoid PEP8 failures
|
Reduce indentation to avoid PEP8 failures
|
Python
|
apache-2.0
|
vmturbo/nova,fnordahl/nova,cloudbau/nova,CEG-FYP-OpenStack/scheduler,vladikr/nova_drafts,yrobla/nova,bigswitch/nova,eharney/nova,KarimAllah/nova,Stavitsky/nova,TwinkleChawla/nova,zzicewind/nova,klmitch/nova,rickerc/nova_audit,belmiromoreira/nova,cloudbase/nova-virtualbox,luogangyi/bcec-nova,Yusuke1987/openstack_template,eneabio/nova,SUSE-Cloud/nova,nikesh-mahalka/nova,fajoy/nova,petrutlucian94/nova_dev,gooddata/openstack-nova,NewpTone/stacklab-nova,Juniper/nova,NoBodyCam/TftpPxeBootBareMetal,sebrandon1/nova,shail2810/nova,usc-isi/extra-specs,orbitfp7/nova,usc-isi/nova,yatinkumbhare/openstack-nova,spring-week-topos/nova-week,yrobla/nova,usc-isi/nova,joker946/nova,usc-isi/extra-specs,apporc/nova,tanglei528/nova,klmitch/nova,cernops/nova,varunarya10/nova_test_latest,salv-orlando/MyRepo,blueboxgroup/nova,BeyondTheClouds/nova,watonyweng/nova,akash1808/nova_test_latest,angdraug/nova,dims/nova,sebrandon1/nova,sridevikoushik31/nova,bgxavier/nova,superstack/nova,ntt-sic/nova,gspilio/nova,NewpTone/stacklab-nova,viggates/nova,adelina-t/nova,maheshp/novatest,varunarya10/nova_test_latest,CiscoSystems/nova,orbitfp7/nova,fajoy/nova,usc-isi/nova,silenceli/nova,psiwczak/openstack,akash1808/nova,mgagne/nova,fnordahl/nova,luogangyi/bcec-nova,NoBodyCam/TftpPxeBootBareMetal,redhat-openstack/nova,NeCTAR-RC/nova,cloudbase/nova,virtualopensystems/nova,mikalstill/nova,cloudbase/nova,CEG-FYP-OpenStack/scheduler,scripnichenko/nova,superstack/nova,DirectXMan12/nova-hacking,edulramirez/nova,houshengbo/nova_vmware_compute_driver,Yuriy-Leonov/nova,Stavitsky/nova,usc-isi/extra-specs,double12gzh/nova,eneabio/nova,plumgrid/plumgrid-nova,imsplitbit/nova,mmnelemane/nova,zhimin711/nova,eonpatapon/nova,ted-gould/nova,aristanetworks/arista-ovs-nova,akash1808/nova_test_latest,aristanetworks/arista-ovs-nova,sileht/deb-openstack-nova,yatinkumbhare/openstack-nova,TieWei/nova,raildo/nova,shootstar/novatest,KarimAllah/nova,Metaswitch/calico-nova,maheshp/novatest,jianghuaw/nova,josephsuh/extra-specs,adelina-t/nova,Juniper/nova,yosshy/nova,whitepages/nova,affo/nova,yrobla/nova,silenceli/nova,bigswitch/nova,whitepages/nova,tudorvio/nova,openstack/nova,phenoxim/nova,CloudServer/nova,joker946/nova,mikalstill/nova,maoy/zknova,bgxavier/nova,citrix-openstack-build/nova,aristanetworks/arista-ovs-nova,dims/nova,gooddata/openstack-nova,devendermishrajio/nova_test_latest,thomasem/nova,NewpTone/stacklab-nova,qwefi/nova,dstroppa/openstack-smartos-nova-grizzly,MountainWei/nova,eayunstack/nova,maoy/zknova,zzicewind/nova,rajalokan/nova,CCI-MOC/nova,mahak/nova,Yusuke1987/openstack_template,saleemjaveds/https-github.com-openstack-nova,kimjaejoong/nova,cloudbase/nova-virtualbox,zhimin711/nova,Juniper/nova,Tehsmash/nova,Francis-Liu/animated-broccoli,phenoxim/nova,JioCloud/nova_test_latest,rahulunair/nova,citrix-openstack-build/nova,badock/nova,petrutlucian94/nova,Triv90/Nova,JianyuWang/nova,sridevikoushik31/nova,apporc/nova,dawnpower/nova,psiwczak/openstack,JioCloud/nova,rajalokan/nova,hanlind/nova,DirectXMan12/nova-hacking,vladikr/nova_drafts,tangfeixiong/nova,eonpatapon/nova,mahak/nova,sileht/deb-openstack-nova,JioCloud/nova_test_latest,leilihh/nova,alexandrucoman/vbox-nova-driver,savi-dev/nova,barnsnake351/nova,jeffrey4l/nova,gspilio/nova,Triv90/Nova,viggates/nova,j-carpentier/nova,klmitch/nova,mikalstill/nova,thomasem/nova,cyx1231st/nova,scripnichenko/nova,josephsuh/extra-specs,sileht/deb-openstack-nova,MountainWei/nova,CCI-MOC/nova,badock/nova,imsplitbit/nova,Metaswitch/calico-nova,leilihh/novaha,russellb/nova,klmitch/nova,shootstar/novatest,JioCloud/nova,rajalokan/nova,ted-gould/nova,BeyondTheClouds/nova,kimjaejoong/nova,rajalokan/nova,rrader/nova-docker-plugin,psiwczak/openstack,CiscoSystems/nova,bclau/nova,watonyweng/nova,maoy/zknova,alvarolopez/nova,devoid/nova,cernops/nova,qwefi/nova,josephsuh/extra-specs,rahulunair/nova,tanglei528/nova,ruslanloman/nova,eneabio/nova,nikesh-mahalka/nova,SUSE-Cloud/nova,vmturbo/nova,jeffrey4l/nova,takeshineshiro/nova,salv-orlando/MyRepo,paulmathews/nova,tianweizhang/nova,dawnpower/nova,devoid/nova,houshengbo/nova_vmware_compute_driver,NoBodyCam/TftpPxeBootBareMetal,jianghuaw/nova,tealover/nova,superstack/nova,rrader/nova-docker-plugin,KarimAllah/nova,felixma/nova,russellb/nova,NeCTAR-RC/nova,berrange/nova,maelnor/nova,mmnelemane/nova,j-carpentier/nova,eharney/nova,sacharya/nova,alvarolopez/nova,LoHChina/nova,spring-week-topos/nova-week,tealover/nova,virtualopensystems/nova,berrange/nova,edulramirez/nova,russellb/nova,plumgrid/plumgrid-nova,raildo/nova,petrutlucian94/nova_dev,projectcalico/calico-nova,ewindisch/nova,vmturbo/nova,DirectXMan12/nova-hacking,felixma/nova,gspilio/nova,double12gzh/nova,devendermishrajio/nova,jianghuaw/nova,Brocade-OpenSource/OpenStack-DNRM-Nova,sebrandon1/nova,akash1808/nova,saleemjaveds/https-github.com-openstack-nova,cloudbau/nova,blueboxgroup/nova,maelnor/nova,rickerc/nova_audit,CloudServer/nova,tangfeixiong/nova,eayunstack/nova,mgagne/nova,Yuriy-Leonov/nova,shahar-stratoscale/nova,hanlind/nova,TieWei/nova,rahulunair/nova,dstroppa/openstack-smartos-nova-grizzly,alaski/nova,mandeepdhami/nova,Juniper/nova,angdraug/nova,jianghuaw/nova,LoHChina/nova,sridevikoushik31/nova,paulmathews/nova,sridevikoushik31/openstack,iuliat/nova,cloudbase/nova,paulmathews/nova,belmiromoreira/nova,JianyuWang/nova,OpenAcademy-OpenStack/nova-scheduler,Francis-Liu/animated-broccoli,bclau/nova,fajoy/nova,openstack/nova,ntt-sic/nova,ewindisch/nova,leilihh/nova,petrutlucian94/nova,sacharya/nova,sridevikoushik31/nova,openstack/nova,redhat-openstack/nova,OpenAcademy-OpenStack/nova-scheduler,devendermishrajio/nova,savi-dev/nova,TwinkleChawla/nova,sridevikoushik31/openstack,sridevikoushik31/openstack,barnsnake351/nova,alaski/nova,BeyondTheClouds/nova,cernops/nova,isyippee/nova,zaina/nova,noironetworks/nova,Triv90/Nova,zaina/nova,tianweizhang/nova,shail2810/nova,mandeepdhami/nova,yosshy/nova,noironetworks/nova,vmturbo/nova,leilihh/novaha,projectcalico/calico-nova,maheshp/novatest,houshengbo/nova_vmware_compute_driver,hanlind/nova,iuliat/nova,devendermishrajio/nova_test_latest,alexandrucoman/vbox-nova-driver,isyippee/nova,takeshineshiro/nova,dstroppa/openstack-smartos-nova-grizzly,tudorvio/nova,salv-orlando/MyRepo,mahak/nova,gooddata/openstack-nova,Tehsmash/nova,ruslanloman/nova,affo/nova,savi-dev/nova,shahar-stratoscale/nova,cyx1231st/nova,gooddata/openstack-nova,Brocade-OpenSource/OpenStack-DNRM-Nova
|
from nova import flags
from nova import utils
FLAGS = flags.FLAGS
flags.DEFINE_string('ipv6_backend',
'rfc2462',
'Backend to use for IPv6 generation')
def reset_backend():
global IMPL
IMPL = utils.LazyPluggable(FLAGS['ipv6_backend'],
- rfc2462='nova.ipv6.rfc2462',
+ rfc2462='nova.ipv6.rfc2462',
- account_identifier='nova.ipv6.account_identifier')
+ account_identifier='nova.ipv6.account_identifier')
def to_global(prefix, mac, project_id):
return IMPL.to_global(prefix, mac, project_id)
def to_mac(ipv6_address):
return IMPL.to_mac(ipv6_address)
reset_backend()
|
Reduce indentation to avoid PEP8 failures
|
## Code Before:
from nova import flags
from nova import utils
FLAGS = flags.FLAGS
flags.DEFINE_string('ipv6_backend',
'rfc2462',
'Backend to use for IPv6 generation')
def reset_backend():
global IMPL
IMPL = utils.LazyPluggable(FLAGS['ipv6_backend'],
rfc2462='nova.ipv6.rfc2462',
account_identifier='nova.ipv6.account_identifier')
def to_global(prefix, mac, project_id):
return IMPL.to_global(prefix, mac, project_id)
def to_mac(ipv6_address):
return IMPL.to_mac(ipv6_address)
reset_backend()
## Instruction:
Reduce indentation to avoid PEP8 failures
## Code After:
from nova import flags
from nova import utils
FLAGS = flags.FLAGS
flags.DEFINE_string('ipv6_backend',
'rfc2462',
'Backend to use for IPv6 generation')
def reset_backend():
global IMPL
IMPL = utils.LazyPluggable(FLAGS['ipv6_backend'],
rfc2462='nova.ipv6.rfc2462',
account_identifier='nova.ipv6.account_identifier')
def to_global(prefix, mac, project_id):
return IMPL.to_global(prefix, mac, project_id)
def to_mac(ipv6_address):
return IMPL.to_mac(ipv6_address)
reset_backend()
|
from nova import flags
from nova import utils
FLAGS = flags.FLAGS
flags.DEFINE_string('ipv6_backend',
'rfc2462',
'Backend to use for IPv6 generation')
def reset_backend():
global IMPL
IMPL = utils.LazyPluggable(FLAGS['ipv6_backend'],
- rfc2462='nova.ipv6.rfc2462',
? ---------------
+ rfc2462='nova.ipv6.rfc2462',
- account_identifier='nova.ipv6.account_identifier')
? ---------------
+ account_identifier='nova.ipv6.account_identifier')
def to_global(prefix, mac, project_id):
return IMPL.to_global(prefix, mac, project_id)
def to_mac(ipv6_address):
return IMPL.to_mac(ipv6_address)
reset_backend()
|
9fba9934c9b47881ee468f295a3710f2c184fab1
|
tendrl/node_agent/__init__.py
|
tendrl/node_agent/__init__.py
|
try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.objects.node_context import NodeContext
from tendrl.node_agent.objects.detected_cluster import DetectedCluster
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.objects.tendrl_context import TendrlContext
from tendrl.node_agent.objects.service import Service
from tendrl.node_agent.objects.cpu import Cpu
from tendrl.node_agent.objects.disk import Disk
from tendrl.node_agent.objects.file import File
from tendrl.node_agent.objects.memory import Memory
from tendrl.node_agent.objects.node import Node
from tendrl.node_agent.objects.os import Os
from tendrl.node_agent.objects.package import Package
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.flows.import_cluster import ImportCluster
class NodeAgentNS(CommonNS):
def __init__(self):
# Create the "tendrl_ns.node_agent" namespace
self.to_str = "tendrl.node_agent"
self.type = 'node'
super(NodeAgentNS, self).__init__()
import __builtin__
__builtin__.tendrl_ns = NodeAgentNS()
|
try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.objects.node_context import NodeContext
from tendrl.node_agent.objects.detected_cluster import DetectedCluster
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.objects.tendrl_context import TendrlContext
from tendrl.node_agent.objects.service import Service
from tendrl.node_agent.objects.cpu import Cpu
from tendrl.node_agent.objects.disk import Disk
from tendrl.node_agent.objects.file import File
from tendrl.node_agent.objects.memory import Memory
from tendrl.node_agent.objects.node import Node
from tendrl.node_agent.objects.os import Os
from tendrl.node_agent.objects.package import Package
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.flows.import_cluster import ImportCluster
class NodeAgentNS(CommonNS):
def __init__(self):
# Create the "tendrl_ns.node_agent" namespace
self.to_str = "tendrl.node_agent"
self.type = 'node'
super(NodeAgentNS, self).__init__()
NodeAgentNS()
|
Fix greenlet and essential objects startup order
|
Fix greenlet and essential objects startup order
|
Python
|
lgpl-2.1
|
Tendrl/node_agent,Tendrl/node-agent,r0h4n/node-agent,Tendrl/node_agent,Tendrl/node-agent,Tendrl/node-agent,r0h4n/node-agent,r0h4n/node-agent
|
try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.objects.node_context import NodeContext
from tendrl.node_agent.objects.detected_cluster import DetectedCluster
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.objects.tendrl_context import TendrlContext
from tendrl.node_agent.objects.service import Service
from tendrl.node_agent.objects.cpu import Cpu
from tendrl.node_agent.objects.disk import Disk
from tendrl.node_agent.objects.file import File
from tendrl.node_agent.objects.memory import Memory
from tendrl.node_agent.objects.node import Node
from tendrl.node_agent.objects.os import Os
from tendrl.node_agent.objects.package import Package
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.flows.import_cluster import ImportCluster
class NodeAgentNS(CommonNS):
def __init__(self):
# Create the "tendrl_ns.node_agent" namespace
self.to_str = "tendrl.node_agent"
self.type = 'node'
super(NodeAgentNS, self).__init__()
+ NodeAgentNS()
- import __builtin__
- __builtin__.tendrl_ns = NodeAgentNS()
|
Fix greenlet and essential objects startup order
|
## Code Before:
try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.objects.node_context import NodeContext
from tendrl.node_agent.objects.detected_cluster import DetectedCluster
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.objects.tendrl_context import TendrlContext
from tendrl.node_agent.objects.service import Service
from tendrl.node_agent.objects.cpu import Cpu
from tendrl.node_agent.objects.disk import Disk
from tendrl.node_agent.objects.file import File
from tendrl.node_agent.objects.memory import Memory
from tendrl.node_agent.objects.node import Node
from tendrl.node_agent.objects.os import Os
from tendrl.node_agent.objects.package import Package
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.flows.import_cluster import ImportCluster
class NodeAgentNS(CommonNS):
def __init__(self):
# Create the "tendrl_ns.node_agent" namespace
self.to_str = "tendrl.node_agent"
self.type = 'node'
super(NodeAgentNS, self).__init__()
import __builtin__
__builtin__.tendrl_ns = NodeAgentNS()
## Instruction:
Fix greenlet and essential objects startup order
## Code After:
try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.objects.node_context import NodeContext
from tendrl.node_agent.objects.detected_cluster import DetectedCluster
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.objects.tendrl_context import TendrlContext
from tendrl.node_agent.objects.service import Service
from tendrl.node_agent.objects.cpu import Cpu
from tendrl.node_agent.objects.disk import Disk
from tendrl.node_agent.objects.file import File
from tendrl.node_agent.objects.memory import Memory
from tendrl.node_agent.objects.node import Node
from tendrl.node_agent.objects.os import Os
from tendrl.node_agent.objects.package import Package
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.flows.import_cluster import ImportCluster
class NodeAgentNS(CommonNS):
def __init__(self):
# Create the "tendrl_ns.node_agent" namespace
self.to_str = "tendrl.node_agent"
self.type = 'node'
super(NodeAgentNS, self).__init__()
NodeAgentNS()
|
try:
from gevent import monkey
except ImportError:
pass
else:
monkey.patch_all()
from tendrl.commons import CommonNS
from tendrl.node_agent.objects.definition import Definition
from tendrl.node_agent.objects.config import Config
from tendrl.node_agent.objects.node_context import NodeContext
from tendrl.node_agent.objects.detected_cluster import DetectedCluster
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.objects.tendrl_context import TendrlContext
from tendrl.node_agent.objects.service import Service
from tendrl.node_agent.objects.cpu import Cpu
from tendrl.node_agent.objects.disk import Disk
from tendrl.node_agent.objects.file import File
from tendrl.node_agent.objects.memory import Memory
from tendrl.node_agent.objects.node import Node
from tendrl.node_agent.objects.os import Os
from tendrl.node_agent.objects.package import Package
from tendrl.node_agent.objects.platform import Platform
from tendrl.node_agent.flows.import_cluster import ImportCluster
class NodeAgentNS(CommonNS):
def __init__(self):
# Create the "tendrl_ns.node_agent" namespace
self.to_str = "tendrl.node_agent"
self.type = 'node'
super(NodeAgentNS, self).__init__()
+ NodeAgentNS()
- import __builtin__
- __builtin__.tendrl_ns = NodeAgentNS()
|
a459c9bd1135ede49e9b2f55a633f86d7cdb81e2
|
tests/mocks/RPi.py
|
tests/mocks/RPi.py
|
class GPIO(object):
BOARD = 'board'
IN = 'in'
OUT = 'out'
PUD_UP = 'pud_up'
FALLING = 'falling'
HIGH = 'high'
LOW = 'low'
@classmethod
def setmode(cls, mode):
print("Mock: set GPIO mode {}".format(mode))
@classmethod
def setup(cls, pin, direction, **kwargs):
print("Mock: setup GPIO pin {} to {}".format(pin, direction))
@classmethod
def output(cls, pin, status):
print("Mock: output GPIO pin {} to {}".format(pin, status))
@classmethod
def add_event_detect(cls, pin, status, **kwargs):
print("Mock: detect GPIO pin {} when {}".format(pin, status))
@classmethod
def cleanup(cls):
print("Mock: quit GPIO")
|
class GPIO(object):
BOARD = 'board'
IN = 'in'
OUT = 'out'
PUD_UP = 'pud_up'
FALLING = 'falling'
HIGH = 'high'
LOW = 'low'
@classmethod
def setmode(cls, mode):
print("Mock: set GPIO mode {}".format(mode))
@classmethod
def setup(cls, pin, direction, **kwargs):
print("Mock: setup GPIO pin {} to {}".format(pin, direction))
@classmethod
def output(cls, pin, status):
pass
@classmethod
def add_event_detect(cls, pin, status, **kwargs):
print("Mock: detect GPIO pin {} when {}".format(pin, status))
@classmethod
def cleanup(cls):
print("Mock: quit GPIO")
|
Remove print message in mocks
|
Remove print message in mocks
|
Python
|
mit
|
werdeil/pibooth,werdeil/pibooth
|
class GPIO(object):
BOARD = 'board'
IN = 'in'
OUT = 'out'
PUD_UP = 'pud_up'
FALLING = 'falling'
HIGH = 'high'
LOW = 'low'
@classmethod
def setmode(cls, mode):
print("Mock: set GPIO mode {}".format(mode))
@classmethod
def setup(cls, pin, direction, **kwargs):
print("Mock: setup GPIO pin {} to {}".format(pin, direction))
@classmethod
def output(cls, pin, status):
- print("Mock: output GPIO pin {} to {}".format(pin, status))
+ pass
@classmethod
def add_event_detect(cls, pin, status, **kwargs):
print("Mock: detect GPIO pin {} when {}".format(pin, status))
@classmethod
def cleanup(cls):
print("Mock: quit GPIO")
|
Remove print message in mocks
|
## Code Before:
class GPIO(object):
BOARD = 'board'
IN = 'in'
OUT = 'out'
PUD_UP = 'pud_up'
FALLING = 'falling'
HIGH = 'high'
LOW = 'low'
@classmethod
def setmode(cls, mode):
print("Mock: set GPIO mode {}".format(mode))
@classmethod
def setup(cls, pin, direction, **kwargs):
print("Mock: setup GPIO pin {} to {}".format(pin, direction))
@classmethod
def output(cls, pin, status):
print("Mock: output GPIO pin {} to {}".format(pin, status))
@classmethod
def add_event_detect(cls, pin, status, **kwargs):
print("Mock: detect GPIO pin {} when {}".format(pin, status))
@classmethod
def cleanup(cls):
print("Mock: quit GPIO")
## Instruction:
Remove print message in mocks
## Code After:
class GPIO(object):
BOARD = 'board'
IN = 'in'
OUT = 'out'
PUD_UP = 'pud_up'
FALLING = 'falling'
HIGH = 'high'
LOW = 'low'
@classmethod
def setmode(cls, mode):
print("Mock: set GPIO mode {}".format(mode))
@classmethod
def setup(cls, pin, direction, **kwargs):
print("Mock: setup GPIO pin {} to {}".format(pin, direction))
@classmethod
def output(cls, pin, status):
pass
@classmethod
def add_event_detect(cls, pin, status, **kwargs):
print("Mock: detect GPIO pin {} when {}".format(pin, status))
@classmethod
def cleanup(cls):
print("Mock: quit GPIO")
|
class GPIO(object):
BOARD = 'board'
IN = 'in'
OUT = 'out'
PUD_UP = 'pud_up'
FALLING = 'falling'
HIGH = 'high'
LOW = 'low'
@classmethod
def setmode(cls, mode):
print("Mock: set GPIO mode {}".format(mode))
@classmethod
def setup(cls, pin, direction, **kwargs):
print("Mock: setup GPIO pin {} to {}".format(pin, direction))
@classmethod
def output(cls, pin, status):
- print("Mock: output GPIO pin {} to {}".format(pin, status))
+ pass
@classmethod
def add_event_detect(cls, pin, status, **kwargs):
print("Mock: detect GPIO pin {} when {}".format(pin, status))
@classmethod
def cleanup(cls):
print("Mock: quit GPIO")
|
c9ffe4fb86ccd39d199c953c860a9076cb309e0c
|
labonneboite/importer/jobs/check_etablissements.py
|
labonneboite/importer/jobs/check_etablissements.py
|
import sys
from labonneboite.importer import util as import_util
from labonneboite.importer import settings
if __name__ == "__main__":
filename = import_util.detect_runnable_file("etablissements")
if filename:
with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f:
f.write("LBB_ETABLISSEMENT_INPUT_FILE=%s\n" % filename)
sys.exit(0)
else:
sys.exit(-1)
|
import sys
from labonneboite.importer import util as import_util
from labonneboite.importer import settings
def run():
filename = import_util.detect_runnable_file("etablissements")
if filename:
with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f:
f.write("LBB_ETABLISSEMENT_INPUT_FILE=%s\n" % filename)
sys.exit(0)
else:
sys.exit(-1)
if __name__ == '__main__':
run()
|
Add a run method for the entry point
|
Add a run method for the entry point
|
Python
|
agpl-3.0
|
StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite
|
import sys
from labonneboite.importer import util as import_util
from labonneboite.importer import settings
- if __name__ == "__main__":
+ def run():
filename = import_util.detect_runnable_file("etablissements")
if filename:
with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f:
f.write("LBB_ETABLISSEMENT_INPUT_FILE=%s\n" % filename)
sys.exit(0)
else:
sys.exit(-1)
+ if __name__ == '__main__':
+ run()
|
Add a run method for the entry point
|
## Code Before:
import sys
from labonneboite.importer import util as import_util
from labonneboite.importer import settings
if __name__ == "__main__":
filename = import_util.detect_runnable_file("etablissements")
if filename:
with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f:
f.write("LBB_ETABLISSEMENT_INPUT_FILE=%s\n" % filename)
sys.exit(0)
else:
sys.exit(-1)
## Instruction:
Add a run method for the entry point
## Code After:
import sys
from labonneboite.importer import util as import_util
from labonneboite.importer import settings
def run():
filename = import_util.detect_runnable_file("etablissements")
if filename:
with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f:
f.write("LBB_ETABLISSEMENT_INPUT_FILE=%s\n" % filename)
sys.exit(0)
else:
sys.exit(-1)
if __name__ == '__main__':
run()
|
import sys
from labonneboite.importer import util as import_util
from labonneboite.importer import settings
- if __name__ == "__main__":
+ def run():
filename = import_util.detect_runnable_file("etablissements")
if filename:
with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f:
f.write("LBB_ETABLISSEMENT_INPUT_FILE=%s\n" % filename)
sys.exit(0)
else:
sys.exit(-1)
+
+ if __name__ == '__main__':
+ run()
|
2d0a96403d58c4a939b17e67f8f93190839ff340
|
txircd/modules/cmd_ping.py
|
txircd/modules/cmd_ping.py
|
from twisted.words.protocols import irc
from txircd.modbase import Command
class PingCommand(Command):
def onUse(self, user, data):
if data["params"]:
user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"], prefix=None)
else:
user.sendMessage(irc.ERR_NOORIGIN, ":No origin specified")
def updateActivity(self, user):
pass
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"commands": {
"PING": PingCommand()
}
}
def cleanup(self):
del self.ircd.commands["PING"]
|
from twisted.words.protocols import irc
from txircd.modbase import Command
class PingCommand(Command):
def onUse(self, user, data):
if data["params"]:
user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"])
else:
user.sendMessage(irc.ERR_NOORIGIN, ":No origin specified")
def updateActivity(self, user):
pass
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"commands": {
"PING": PingCommand()
}
}
def cleanup(self):
del self.ircd.commands["PING"]
|
Send the server prefix on the line when the client sends PING
|
Send the server prefix on the line when the client sends PING
|
Python
|
bsd-3-clause
|
Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd
|
from twisted.words.protocols import irc
from txircd.modbase import Command
class PingCommand(Command):
def onUse(self, user, data):
if data["params"]:
- user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"], prefix=None)
+ user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"])
else:
user.sendMessage(irc.ERR_NOORIGIN, ":No origin specified")
def updateActivity(self, user):
pass
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"commands": {
"PING": PingCommand()
}
}
def cleanup(self):
del self.ircd.commands["PING"]
|
Send the server prefix on the line when the client sends PING
|
## Code Before:
from twisted.words.protocols import irc
from txircd.modbase import Command
class PingCommand(Command):
def onUse(self, user, data):
if data["params"]:
user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"], prefix=None)
else:
user.sendMessage(irc.ERR_NOORIGIN, ":No origin specified")
def updateActivity(self, user):
pass
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"commands": {
"PING": PingCommand()
}
}
def cleanup(self):
del self.ircd.commands["PING"]
## Instruction:
Send the server prefix on the line when the client sends PING
## Code After:
from twisted.words.protocols import irc
from txircd.modbase import Command
class PingCommand(Command):
def onUse(self, user, data):
if data["params"]:
user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"])
else:
user.sendMessage(irc.ERR_NOORIGIN, ":No origin specified")
def updateActivity(self, user):
pass
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"commands": {
"PING": PingCommand()
}
}
def cleanup(self):
del self.ircd.commands["PING"]
|
from twisted.words.protocols import irc
from txircd.modbase import Command
class PingCommand(Command):
def onUse(self, user, data):
if data["params"]:
- user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"], prefix=None)
? -------------
+ user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"])
else:
user.sendMessage(irc.ERR_NOORIGIN, ":No origin specified")
def updateActivity(self, user):
pass
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"commands": {
"PING": PingCommand()
}
}
def cleanup(self):
del self.ircd.commands["PING"]
|
6a7d741da6124ec3d8607b5780608b51b7aca8ba
|
editorconfig/exceptions.py
|
editorconfig/exceptions.py
|
class EditorConfigError(Exception):
"""Parent class of all exceptions raised by EditorConfig"""
from ConfigParser import ParsingError as _ParsingError
class ParsingError(_ParsingError, EditorConfigError):
"""Error raised if an EditorConfig file could not be parsed"""
class PathError(ValueError, EditorConfigError):
"""Error raised if invalid filepath is specified"""
class VersionError(ValueError, EditorConfigError):
"""Error raised if invalid version number is specified"""
|
class EditorConfigError(Exception):
"""Parent class of all exceptions raised by EditorConfig"""
try:
from ConfigParser import ParsingError as _ParsingError
except:
from configparser import ParsingError as _ParsingError
class ParsingError(_ParsingError, EditorConfigError):
"""Error raised if an EditorConfig file could not be parsed"""
class PathError(ValueError, EditorConfigError):
"""Error raised if invalid filepath is specified"""
class VersionError(ValueError, EditorConfigError):
"""Error raised if invalid version number is specified"""
|
Fix broken ConfigParser import for Python3
|
Fix broken ConfigParser import for Python3
|
Python
|
bsd-2-clause
|
benjifisher/editorconfig-vim,VictorBjelkholm/editorconfig-vim,johnfraney/editorconfig-vim,benjifisher/editorconfig-vim,pocke/editorconfig-vim,pocke/editorconfig-vim,pocke/editorconfig-vim,VictorBjelkholm/editorconfig-vim,johnfraney/editorconfig-vim,VictorBjelkholm/editorconfig-vim,benjifisher/editorconfig-vim,johnfraney/editorconfig-vim
|
class EditorConfigError(Exception):
"""Parent class of all exceptions raised by EditorConfig"""
+ try:
- from ConfigParser import ParsingError as _ParsingError
+ from ConfigParser import ParsingError as _ParsingError
+ except:
+ from configparser import ParsingError as _ParsingError
class ParsingError(_ParsingError, EditorConfigError):
"""Error raised if an EditorConfig file could not be parsed"""
class PathError(ValueError, EditorConfigError):
"""Error raised if invalid filepath is specified"""
class VersionError(ValueError, EditorConfigError):
"""Error raised if invalid version number is specified"""
|
Fix broken ConfigParser import for Python3
|
## Code Before:
class EditorConfigError(Exception):
"""Parent class of all exceptions raised by EditorConfig"""
from ConfigParser import ParsingError as _ParsingError
class ParsingError(_ParsingError, EditorConfigError):
"""Error raised if an EditorConfig file could not be parsed"""
class PathError(ValueError, EditorConfigError):
"""Error raised if invalid filepath is specified"""
class VersionError(ValueError, EditorConfigError):
"""Error raised if invalid version number is specified"""
## Instruction:
Fix broken ConfigParser import for Python3
## Code After:
class EditorConfigError(Exception):
"""Parent class of all exceptions raised by EditorConfig"""
try:
from ConfigParser import ParsingError as _ParsingError
except:
from configparser import ParsingError as _ParsingError
class ParsingError(_ParsingError, EditorConfigError):
"""Error raised if an EditorConfig file could not be parsed"""
class PathError(ValueError, EditorConfigError):
"""Error raised if invalid filepath is specified"""
class VersionError(ValueError, EditorConfigError):
"""Error raised if invalid version number is specified"""
|
class EditorConfigError(Exception):
"""Parent class of all exceptions raised by EditorConfig"""
+ try:
- from ConfigParser import ParsingError as _ParsingError
+ from ConfigParser import ParsingError as _ParsingError
? ++++
+ except:
+ from configparser import ParsingError as _ParsingError
class ParsingError(_ParsingError, EditorConfigError):
"""Error raised if an EditorConfig file could not be parsed"""
class PathError(ValueError, EditorConfigError):
"""Error raised if invalid filepath is specified"""
class VersionError(ValueError, EditorConfigError):
"""Error raised if invalid version number is specified"""
|
270a03dc78838137051fec49050f550c44be2359
|
facebook_auth/views.py
|
facebook_auth/views.py
|
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
self.login(next_url)
response = http.HttpResponseRedirect(next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
response = http.HttpResponseRedirect(next_url['close'])
return response
def login(self, next_url):
user = authenticate(
code=self.request.GET['code'],
redirect_uri=urls.redirect_uri(next_url['next'],
next_url['close']))
if user:
login(self.request, user)
handler = Handler.as_view()
|
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
import facepy
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
self.next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
try:
self.login()
except facepy.FacepyError as e:
return self.handle_facebook_error(e)
response = http.HttpResponseRedirect(self.next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
response = http.HttpResponseRedirect(self.next_url['close'])
return response
def login(self):
user = authenticate(
code=self.request.GET['code'],
redirect_uri=urls.redirect_uri(self.next_url['next'],
self.next_url['close']))
if user:
login(self.request, user)
def handle_facebook_error(self, e):
return http.HttpResponseRedirect(self.next_url['next'])
handler = Handler.as_view()
|
Add facebook error handler in view.
|
Add facebook error handler in view.
This assumes that there is no other backend which
can authenticate user with facebook credentials.
|
Python
|
mit
|
jgoclawski/django-facebook-auth,pozytywnie/django-facebook-auth,pozytywnie/django-facebook-auth,jgoclawski/django-facebook-auth
|
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
+
+ import facepy
+
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
- next_url = urls.Next().decode(request.GET['next'])
+ self.next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
+ try:
- self.login(next_url)
+ self.login()
+ except facepy.FacepyError as e:
+ return self.handle_facebook_error(e)
- response = http.HttpResponseRedirect(next_url['next'])
+ response = http.HttpResponseRedirect(self.next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
- response = http.HttpResponseRedirect(next_url['close'])
+ response = http.HttpResponseRedirect(self.next_url['close'])
return response
- def login(self, next_url):
+ def login(self):
user = authenticate(
code=self.request.GET['code'],
- redirect_uri=urls.redirect_uri(next_url['next'],
+ redirect_uri=urls.redirect_uri(self.next_url['next'],
- next_url['close']))
+ self.next_url['close']))
if user:
login(self.request, user)
+ def handle_facebook_error(self, e):
+ return http.HttpResponseRedirect(self.next_url['next'])
+
handler = Handler.as_view()
|
Add facebook error handler in view.
|
## Code Before:
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
self.login(next_url)
response = http.HttpResponseRedirect(next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
response = http.HttpResponseRedirect(next_url['close'])
return response
def login(self, next_url):
user = authenticate(
code=self.request.GET['code'],
redirect_uri=urls.redirect_uri(next_url['next'],
next_url['close']))
if user:
login(self.request, user)
handler = Handler.as_view()
## Instruction:
Add facebook error handler in view.
## Code After:
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
import facepy
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
self.next_url = urls.Next().decode(request.GET['next'])
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
try:
self.login()
except facepy.FacepyError as e:
return self.handle_facebook_error(e)
response = http.HttpResponseRedirect(self.next_url['next'])
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
response = http.HttpResponseRedirect(self.next_url['close'])
return response
def login(self):
user = authenticate(
code=self.request.GET['code'],
redirect_uri=urls.redirect_uri(self.next_url['next'],
self.next_url['close']))
if user:
login(self.request, user)
def handle_facebook_error(self, e):
return http.HttpResponseRedirect(self.next_url['next'])
handler = Handler.as_view()
|
import logging
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django import http
from django.views import generic
+
+ import facepy
+
from facebook_auth import urls
logger = logging.getLogger(__name__)
class Handler(generic.View):
def get(self, request):
try:
- next_url = urls.Next().decode(request.GET['next'])
+ self.next_url = urls.Next().decode(request.GET['next'])
? +++++
except urls.InvalidNextUrl:
logger.warning('Invalid facebook handler next.',
extra={'request': request})
return http.HttpResponseBadRequest()
if 'code' in request.GET:
+ try:
- self.login(next_url)
? --------
+ self.login()
? ++++
+ except facepy.FacepyError as e:
+ return self.handle_facebook_error(e)
- response = http.HttpResponseRedirect(next_url['next'])
+ response = http.HttpResponseRedirect(self.next_url['next'])
? +++++
response["P3P"] = ('CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi'
' IVDi CONi HIS OUR IND CNT"')
else:
- response = http.HttpResponseRedirect(next_url['close'])
+ response = http.HttpResponseRedirect(self.next_url['close'])
? +++++
return response
- def login(self, next_url):
? ----------
+ def login(self):
user = authenticate(
code=self.request.GET['code'],
- redirect_uri=urls.redirect_uri(next_url['next'],
+ redirect_uri=urls.redirect_uri(self.next_url['next'],
? +++++
- next_url['close']))
+ self.next_url['close']))
? +++++
if user:
login(self.request, user)
+ def handle_facebook_error(self, e):
+ return http.HttpResponseRedirect(self.next_url['next'])
+
handler = Handler.as_view()
|
bca6f6041e9f49d1d25d7a9c4cb88080d88c45b1
|
dumper/invalidation.py
|
dumper/invalidation.py
|
import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
|
import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
'''
Each path can actually have multiple cached entries, varying based on different HTTP
methods. So a GET request will have a different cached response from a HEAD request.
In order to invalidate a path, we must first know all the different cache keys that the
path might have been cached at. This returns those keys
'''
return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
|
Comment concerning differences in keys per path
|
Comment concerning differences in keys per path
|
Python
|
mit
|
saulshanabrook/django-dumper
|
import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
+ '''
+ Each path can actually have multiple cached entries, varying based on different HTTP
+ methods. So a GET request will have a different cached response from a HEAD request.
+
+ In order to invalidate a path, we must first know all the different cache keys that the
+ path might have been cached at. This returns those keys
+ '''
return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
|
Comment concerning differences in keys per path
|
## Code Before:
import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
## Instruction:
Comment concerning differences in keys per path
## Code After:
import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
'''
Each path can actually have multiple cached entries, varying based on different HTTP
methods. So a GET request will have a different cached response from a HEAD request.
In order to invalidate a path, we must first know all the different cache keys that the
path might have been cached at. This returns those keys
'''
return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
|
import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
+ '''
+ Each path can actually have multiple cached entries, varying based on different HTTP
+ methods. So a GET request will have a different cached response from a HEAD request.
+
+ In order to invalidate a path, we must first know all the different cache keys that the
+ path might have been cached at. This returns those keys
+ '''
return [dumper.utils.cache_key(path, method) for method in dumper.settings.CACHABLE_METHODS]
|
9088d706e08317241ab8238020780d6140507589
|
colour/adaptation/__init__.py
|
colour/adaptation/__init__.py
|
from __future__ import absolute_import
from .dataset import *
from . import dataset
from .vonkries import (
chromatic_adaptation_matrix_VonKries,
chromatic_adaptation_VonKries)
from .fairchild1990 import chromatic_adaptation_Fairchild1990
from .cmccat2000 import (
CMCCAT2000_InductionFactors,
CMCCAT2000_VIEWING_CONDITIONS,
CMCCAT2000_forward,
CMCCAT2000_reverse,
chromatic_adaptation_CMCCAT2000)
from .cie1994 import chromatic_adaptation_CIE1994
__all__ = dataset.__all__
__all__ += ['chromatic_adaptation_matrix_VonKries',
'chromatic_adaptation_VonKries']
__all__ += ['chromatic_adaptation_Fairchild1990']
__all__ += ['CMCCAT2000_InductionFactors',
'CMCCAT2000_VIEWING_CONDITIONS',
'CMCCAT2000_forward',
'CMCCAT2000_reverse',
'chromatic_adaptation_CMCCAT2000']
__all__ += ['chromatic_adaptation_CIE1994']
|
from __future__ import absolute_import
from .dataset import *
from . import dataset
from .vonkries import (
chromatic_adaptation_matrix_VonKries,
chromatic_adaptation_VonKries)
from .fairchild1990 import chromatic_adaptation_Fairchild1990
from .cmccat2000 import (
CMCCAT2000_InductionFactors,
CMCCAT2000_VIEWING_CONDITIONS,
CMCCAT2000_forward,
CMCCAT2000_reverse,
chromatic_adaptation_CMCCAT2000)
from .cie1994 import chromatic_adaptation_CIE1994
__all__ = []
__all__ += dataset.__all__
__all__ += ['chromatic_adaptation_matrix_VonKries',
'chromatic_adaptation_VonKries']
__all__ += ['chromatic_adaptation_Fairchild1990']
__all__ += ['CMCCAT2000_InductionFactors',
'CMCCAT2000_VIEWING_CONDITIONS',
'CMCCAT2000_forward',
'CMCCAT2000_reverse',
'chromatic_adaptation_CMCCAT2000']
__all__ += ['chromatic_adaptation_CIE1994']
|
Fix various documentation related warnings.
|
Fix various documentation related warnings.
|
Python
|
bsd-3-clause
|
colour-science/colour
|
from __future__ import absolute_import
from .dataset import *
from . import dataset
from .vonkries import (
chromatic_adaptation_matrix_VonKries,
chromatic_adaptation_VonKries)
from .fairchild1990 import chromatic_adaptation_Fairchild1990
from .cmccat2000 import (
CMCCAT2000_InductionFactors,
CMCCAT2000_VIEWING_CONDITIONS,
CMCCAT2000_forward,
CMCCAT2000_reverse,
chromatic_adaptation_CMCCAT2000)
from .cie1994 import chromatic_adaptation_CIE1994
+ __all__ = []
- __all__ = dataset.__all__
+ __all__ += dataset.__all__
__all__ += ['chromatic_adaptation_matrix_VonKries',
'chromatic_adaptation_VonKries']
__all__ += ['chromatic_adaptation_Fairchild1990']
__all__ += ['CMCCAT2000_InductionFactors',
'CMCCAT2000_VIEWING_CONDITIONS',
'CMCCAT2000_forward',
'CMCCAT2000_reverse',
'chromatic_adaptation_CMCCAT2000']
__all__ += ['chromatic_adaptation_CIE1994']
|
Fix various documentation related warnings.
|
## Code Before:
from __future__ import absolute_import
from .dataset import *
from . import dataset
from .vonkries import (
chromatic_adaptation_matrix_VonKries,
chromatic_adaptation_VonKries)
from .fairchild1990 import chromatic_adaptation_Fairchild1990
from .cmccat2000 import (
CMCCAT2000_InductionFactors,
CMCCAT2000_VIEWING_CONDITIONS,
CMCCAT2000_forward,
CMCCAT2000_reverse,
chromatic_adaptation_CMCCAT2000)
from .cie1994 import chromatic_adaptation_CIE1994
__all__ = dataset.__all__
__all__ += ['chromatic_adaptation_matrix_VonKries',
'chromatic_adaptation_VonKries']
__all__ += ['chromatic_adaptation_Fairchild1990']
__all__ += ['CMCCAT2000_InductionFactors',
'CMCCAT2000_VIEWING_CONDITIONS',
'CMCCAT2000_forward',
'CMCCAT2000_reverse',
'chromatic_adaptation_CMCCAT2000']
__all__ += ['chromatic_adaptation_CIE1994']
## Instruction:
Fix various documentation related warnings.
## Code After:
from __future__ import absolute_import
from .dataset import *
from . import dataset
from .vonkries import (
chromatic_adaptation_matrix_VonKries,
chromatic_adaptation_VonKries)
from .fairchild1990 import chromatic_adaptation_Fairchild1990
from .cmccat2000 import (
CMCCAT2000_InductionFactors,
CMCCAT2000_VIEWING_CONDITIONS,
CMCCAT2000_forward,
CMCCAT2000_reverse,
chromatic_adaptation_CMCCAT2000)
from .cie1994 import chromatic_adaptation_CIE1994
__all__ = []
__all__ += dataset.__all__
__all__ += ['chromatic_adaptation_matrix_VonKries',
'chromatic_adaptation_VonKries']
__all__ += ['chromatic_adaptation_Fairchild1990']
__all__ += ['CMCCAT2000_InductionFactors',
'CMCCAT2000_VIEWING_CONDITIONS',
'CMCCAT2000_forward',
'CMCCAT2000_reverse',
'chromatic_adaptation_CMCCAT2000']
__all__ += ['chromatic_adaptation_CIE1994']
|
from __future__ import absolute_import
from .dataset import *
from . import dataset
from .vonkries import (
chromatic_adaptation_matrix_VonKries,
chromatic_adaptation_VonKries)
from .fairchild1990 import chromatic_adaptation_Fairchild1990
from .cmccat2000 import (
CMCCAT2000_InductionFactors,
CMCCAT2000_VIEWING_CONDITIONS,
CMCCAT2000_forward,
CMCCAT2000_reverse,
chromatic_adaptation_CMCCAT2000)
from .cie1994 import chromatic_adaptation_CIE1994
+ __all__ = []
- __all__ = dataset.__all__
+ __all__ += dataset.__all__
? +
__all__ += ['chromatic_adaptation_matrix_VonKries',
'chromatic_adaptation_VonKries']
__all__ += ['chromatic_adaptation_Fairchild1990']
__all__ += ['CMCCAT2000_InductionFactors',
'CMCCAT2000_VIEWING_CONDITIONS',
'CMCCAT2000_forward',
'CMCCAT2000_reverse',
'chromatic_adaptation_CMCCAT2000']
__all__ += ['chromatic_adaptation_CIE1994']
|
6db1ddd9c7776cf07222ae58dc9b2c44135ac59a
|
spacy/__init__.py
|
spacy/__init__.py
|
from __future__ import unicode_literals
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# These are imported as part of the API
from thinc.neural.util import prefer_gpu, require_gpu
from .cli.info import info as cli_info
from .glossary import explain
from .about import __version__
from .errors import Warnings, deprecation_warning
from . import util
def load(name, **overrides):
depr_path = overrides.get("path")
if depr_path not in (True, False, None):
deprecation_warning(Warnings.W001.format(path=depr_path))
return util.load_model(name, **overrides)
def blank(name, **kwargs):
LangClass = util.get_lang_class(name)
return LangClass(**kwargs)
def info(model=None, markdown=False, silent=False):
return cli_info(model, markdown, silent)
|
from __future__ import unicode_literals
import warnings
import sys
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# These are imported as part of the API
from thinc.neural.util import prefer_gpu, require_gpu
from .cli.info import info as cli_info
from .glossary import explain
from .about import __version__
from .errors import Warnings, deprecation_warning
from . import util
if __version__ >= '2.1.0' and sys.maxunicode <= 65535:
raise ValueError('''You are running a narrow unicode build,
which is incompatible with spacy >= 2.1.0, reinstall Python and use a
wide unicode build instead. You can also rebuild Python and
set the --enable-unicode=ucs4 flag.''')
def load(name, **overrides):
depr_path = overrides.get("path")
if depr_path not in (True, False, None):
deprecation_warning(Warnings.W001.format(path=depr_path))
return util.load_model(name, **overrides)
def blank(name, **kwargs):
LangClass = util.get_lang_class(name)
return LangClass(**kwargs)
def info(model=None, markdown=False, silent=False):
return cli_info(model, markdown, silent)
|
Raise ValueError for narrow unicode build
|
Raise ValueError for narrow unicode build
|
Python
|
mit
|
explosion/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy
|
from __future__ import unicode_literals
import warnings
+ import sys
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# These are imported as part of the API
from thinc.neural.util import prefer_gpu, require_gpu
from .cli.info import info as cli_info
from .glossary import explain
from .about import __version__
from .errors import Warnings, deprecation_warning
from . import util
+
+ if __version__ >= '2.1.0' and sys.maxunicode <= 65535:
+ raise ValueError('''You are running a narrow unicode build,
+ which is incompatible with spacy >= 2.1.0, reinstall Python and use a
+ wide unicode build instead. You can also rebuild Python and
+ set the --enable-unicode=ucs4 flag.''')
def load(name, **overrides):
depr_path = overrides.get("path")
if depr_path not in (True, False, None):
deprecation_warning(Warnings.W001.format(path=depr_path))
return util.load_model(name, **overrides)
def blank(name, **kwargs):
LangClass = util.get_lang_class(name)
return LangClass(**kwargs)
def info(model=None, markdown=False, silent=False):
return cli_info(model, markdown, silent)
|
Raise ValueError for narrow unicode build
|
## Code Before:
from __future__ import unicode_literals
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# These are imported as part of the API
from thinc.neural.util import prefer_gpu, require_gpu
from .cli.info import info as cli_info
from .glossary import explain
from .about import __version__
from .errors import Warnings, deprecation_warning
from . import util
def load(name, **overrides):
depr_path = overrides.get("path")
if depr_path not in (True, False, None):
deprecation_warning(Warnings.W001.format(path=depr_path))
return util.load_model(name, **overrides)
def blank(name, **kwargs):
LangClass = util.get_lang_class(name)
return LangClass(**kwargs)
def info(model=None, markdown=False, silent=False):
return cli_info(model, markdown, silent)
## Instruction:
Raise ValueError for narrow unicode build
## Code After:
from __future__ import unicode_literals
import warnings
import sys
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# These are imported as part of the API
from thinc.neural.util import prefer_gpu, require_gpu
from .cli.info import info as cli_info
from .glossary import explain
from .about import __version__
from .errors import Warnings, deprecation_warning
from . import util
if __version__ >= '2.1.0' and sys.maxunicode <= 65535:
raise ValueError('''You are running a narrow unicode build,
which is incompatible with spacy >= 2.1.0, reinstall Python and use a
wide unicode build instead. You can also rebuild Python and
set the --enable-unicode=ucs4 flag.''')
def load(name, **overrides):
depr_path = overrides.get("path")
if depr_path not in (True, False, None):
deprecation_warning(Warnings.W001.format(path=depr_path))
return util.load_model(name, **overrides)
def blank(name, **kwargs):
LangClass = util.get_lang_class(name)
return LangClass(**kwargs)
def info(model=None, markdown=False, silent=False):
return cli_info(model, markdown, silent)
|
from __future__ import unicode_literals
import warnings
+ import sys
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# These are imported as part of the API
from thinc.neural.util import prefer_gpu, require_gpu
from .cli.info import info as cli_info
from .glossary import explain
from .about import __version__
from .errors import Warnings, deprecation_warning
from . import util
+
+ if __version__ >= '2.1.0' and sys.maxunicode <= 65535:
+ raise ValueError('''You are running a narrow unicode build,
+ which is incompatible with spacy >= 2.1.0, reinstall Python and use a
+ wide unicode build instead. You can also rebuild Python and
+ set the --enable-unicode=ucs4 flag.''')
def load(name, **overrides):
depr_path = overrides.get("path")
if depr_path not in (True, False, None):
deprecation_warning(Warnings.W001.format(path=depr_path))
return util.load_model(name, **overrides)
def blank(name, **kwargs):
LangClass = util.get_lang_class(name)
return LangClass(**kwargs)
def info(model=None, markdown=False, silent=False):
return cli_info(model, markdown, silent)
|
cc17f806e3fcbc6974a9ee13be58585e681cc59a
|
jose/backends/__init__.py
|
jose/backends/__init__.py
|
try:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey # noqa: F401
except ImportError:
try:
from jose.backends.pycrypto_backend import RSAKey # noqa: F401
except ImportError:
from jose.backends.rsa_backend import RSAKey # noqa: F401
try:
from jose.backends.cryptography_backend import CryptographyECKey as ECKey # noqa: F401
except ImportError:
from jose.backends.ecdsa_backend import ECDSAECKey as ECKey # noqa: F401
|
try:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey # noqa: F401
except ImportError:
try:
from jose.backends.pycrypto_backend import RSAKey # noqa: F401
# time.clock was deprecated in python 3.3 in favor of time.perf_counter
# and removed in python 3.8. pycrypto was never updated for this. If
# time has no clock attribute, let it use perf_counter instead to work
# in 3.8+
# noinspection PyUnresolvedReferences
import time
if not hasattr(time, "clock"):
time.clock = time.perf_counter
except ImportError:
from jose.backends.rsa_backend import RSAKey # noqa: F401
try:
from jose.backends.cryptography_backend import CryptographyECKey as ECKey # noqa: F401
except ImportError:
from jose.backends.ecdsa_backend import ECDSAECKey as ECKey # noqa: F401
|
Add fix for time.clock removal in 3.8 for pycrypto backend
|
Add fix for time.clock removal in 3.8 for pycrypto backend
|
Python
|
mit
|
mpdavis/python-jose
|
try:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey # noqa: F401
except ImportError:
try:
from jose.backends.pycrypto_backend import RSAKey # noqa: F401
+
+ # time.clock was deprecated in python 3.3 in favor of time.perf_counter
+ # and removed in python 3.8. pycrypto was never updated for this. If
+ # time has no clock attribute, let it use perf_counter instead to work
+ # in 3.8+
+ # noinspection PyUnresolvedReferences
+ import time
+ if not hasattr(time, "clock"):
+ time.clock = time.perf_counter
+
except ImportError:
from jose.backends.rsa_backend import RSAKey # noqa: F401
try:
from jose.backends.cryptography_backend import CryptographyECKey as ECKey # noqa: F401
except ImportError:
from jose.backends.ecdsa_backend import ECDSAECKey as ECKey # noqa: F401
|
Add fix for time.clock removal in 3.8 for pycrypto backend
|
## Code Before:
try:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey # noqa: F401
except ImportError:
try:
from jose.backends.pycrypto_backend import RSAKey # noqa: F401
except ImportError:
from jose.backends.rsa_backend import RSAKey # noqa: F401
try:
from jose.backends.cryptography_backend import CryptographyECKey as ECKey # noqa: F401
except ImportError:
from jose.backends.ecdsa_backend import ECDSAECKey as ECKey # noqa: F401
## Instruction:
Add fix for time.clock removal in 3.8 for pycrypto backend
## Code After:
try:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey # noqa: F401
except ImportError:
try:
from jose.backends.pycrypto_backend import RSAKey # noqa: F401
# time.clock was deprecated in python 3.3 in favor of time.perf_counter
# and removed in python 3.8. pycrypto was never updated for this. If
# time has no clock attribute, let it use perf_counter instead to work
# in 3.8+
# noinspection PyUnresolvedReferences
import time
if not hasattr(time, "clock"):
time.clock = time.perf_counter
except ImportError:
from jose.backends.rsa_backend import RSAKey # noqa: F401
try:
from jose.backends.cryptography_backend import CryptographyECKey as ECKey # noqa: F401
except ImportError:
from jose.backends.ecdsa_backend import ECDSAECKey as ECKey # noqa: F401
|
try:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey # noqa: F401
except ImportError:
try:
from jose.backends.pycrypto_backend import RSAKey # noqa: F401
+
+ # time.clock was deprecated in python 3.3 in favor of time.perf_counter
+ # and removed in python 3.8. pycrypto was never updated for this. If
+ # time has no clock attribute, let it use perf_counter instead to work
+ # in 3.8+
+ # noinspection PyUnresolvedReferences
+ import time
+ if not hasattr(time, "clock"):
+ time.clock = time.perf_counter
+
except ImportError:
from jose.backends.rsa_backend import RSAKey # noqa: F401
try:
from jose.backends.cryptography_backend import CryptographyECKey as ECKey # noqa: F401
except ImportError:
from jose.backends.ecdsa_backend import ECDSAECKey as ECKey # noqa: F401
|
57f131218ac7362fdf85389b73dcafb9d35897f4
|
TriangleSimilarityDistanceCalculator.py
|
TriangleSimilarityDistanceCalculator.py
|
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
Update measured Focal Lengths for C920.
|
Update measured Focal Lengths for C920.
|
Python
|
mit
|
AluminatiFRC/Vision2016,AluminatiFRC/Vision2016
|
+
+ PFL_H_C920 = 622
+ PFL_V_C920 = 625
+ PFL_H_LC3000 = 652
+ PFL_V_LC3000 = 652
+
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
- def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
+ def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
- focalLength = perceivedSize * distance / float(self.knownSize)
+ focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
Update measured Focal Lengths for C920.
|
## Code Before:
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
## Instruction:
Update measured Focal Lengths for C920.
## Code After:
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
+
+ PFL_H_C920 = 622
+ PFL_V_C920 = 625
+ PFL_H_LC3000 = 652
+ PFL_V_LC3000 = 652
+
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
- def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
? ^^ ^
+ def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
? ^^^^^^^^^^ ^^^^^^
- focalLength = perceivedSize * distance / float(self.knownSize)
? ^
+ focalLength = perceivedSize * knownDistance / float(self.knownSize)
? ^^^^^^
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
b836b2c39299cc6dbcbdbc8bcffe046f25909edc
|
test_portend.py
|
test_portend.py
|
import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = ''
port = portend.find_available_local_port()
return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
def id_for_info(info):
af, = info[:1]
return str(af)
def build_listening_infos():
params = list(socket_infos())
ids = list(map(id_for_info, params))
return locals()
@pytest.fixture(**build_listening_infos())
def listening_addr(request):
af, socktype, proto, canonname, sa = request.param
sock = socket.socket(af, socktype, proto)
sock.bind(sa)
sock.listen(5)
try:
yield sa
finally:
sock.close()
class TestCheckPort:
def test_check_port_listening(self, listening_addr):
with pytest.raises(IOError):
portend._check_port(*listening_addr[:2])
|
import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = ''
port = portend.find_available_local_port()
return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
def id_for_info(info):
af, = info[:1]
return str(af)
def build_addr_infos():
params = list(socket_infos())
ids = list(map(id_for_info, params))
return locals()
@pytest.fixture(**build_addr_infos())
def listening_addr(request):
af, socktype, proto, canonname, sa = request.param
sock = socket.socket(af, socktype, proto)
sock.bind(sa)
sock.listen(5)
try:
yield sa
finally:
sock.close()
@pytest.fixture(**build_addr_infos())
def nonlistening_addr(request):
af, socktype, proto, canonname, sa = request.param
return sa
class TestCheckPort:
def test_check_port_listening(self, listening_addr):
with pytest.raises(IOError):
portend._check_port(*listening_addr[:2])
def test_check_port_nonlistening(self, nonlistening_addr):
portend._check_port(*nonlistening_addr[:2])
|
Add tests for nonlistening addresses as well.
|
Add tests for nonlistening addresses as well.
|
Python
|
mit
|
jaraco/portend
|
import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = ''
port = portend.find_available_local_port()
return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
def id_for_info(info):
af, = info[:1]
return str(af)
- def build_listening_infos():
+ def build_addr_infos():
params = list(socket_infos())
ids = list(map(id_for_info, params))
return locals()
- @pytest.fixture(**build_listening_infos())
+ @pytest.fixture(**build_addr_infos())
def listening_addr(request):
af, socktype, proto, canonname, sa = request.param
sock = socket.socket(af, socktype, proto)
sock.bind(sa)
sock.listen(5)
try:
yield sa
finally:
sock.close()
+ @pytest.fixture(**build_addr_infos())
+ def nonlistening_addr(request):
+ af, socktype, proto, canonname, sa = request.param
+ return sa
+
+
class TestCheckPort:
def test_check_port_listening(self, listening_addr):
with pytest.raises(IOError):
portend._check_port(*listening_addr[:2])
+ def test_check_port_nonlistening(self, nonlistening_addr):
+ portend._check_port(*nonlistening_addr[:2])
+
|
Add tests for nonlistening addresses as well.
|
## Code Before:
import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = ''
port = portend.find_available_local_port()
return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
def id_for_info(info):
af, = info[:1]
return str(af)
def build_listening_infos():
params = list(socket_infos())
ids = list(map(id_for_info, params))
return locals()
@pytest.fixture(**build_listening_infos())
def listening_addr(request):
af, socktype, proto, canonname, sa = request.param
sock = socket.socket(af, socktype, proto)
sock.bind(sa)
sock.listen(5)
try:
yield sa
finally:
sock.close()
class TestCheckPort:
def test_check_port_listening(self, listening_addr):
with pytest.raises(IOError):
portend._check_port(*listening_addr[:2])
## Instruction:
Add tests for nonlistening addresses as well.
## Code After:
import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = ''
port = portend.find_available_local_port()
return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
def id_for_info(info):
af, = info[:1]
return str(af)
def build_addr_infos():
params = list(socket_infos())
ids = list(map(id_for_info, params))
return locals()
@pytest.fixture(**build_addr_infos())
def listening_addr(request):
af, socktype, proto, canonname, sa = request.param
sock = socket.socket(af, socktype, proto)
sock.bind(sa)
sock.listen(5)
try:
yield sa
finally:
sock.close()
@pytest.fixture(**build_addr_infos())
def nonlistening_addr(request):
af, socktype, proto, canonname, sa = request.param
return sa
class TestCheckPort:
def test_check_port_listening(self, listening_addr):
with pytest.raises(IOError):
portend._check_port(*listening_addr[:2])
def test_check_port_nonlistening(self, nonlistening_addr):
portend._check_port(*nonlistening_addr[:2])
|
import socket
import pytest
import portend
def socket_infos():
"""
Generate addr infos for connections to localhost
"""
host = ''
port = portend.find_available_local_port()
return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
def id_for_info(info):
af, = info[:1]
return str(af)
- def build_listening_infos():
+ def build_addr_infos():
params = list(socket_infos())
ids = list(map(id_for_info, params))
return locals()
- @pytest.fixture(**build_listening_infos())
? ^^^^^^^^^
+ @pytest.fixture(**build_addr_infos())
? ^^^^
def listening_addr(request):
af, socktype, proto, canonname, sa = request.param
sock = socket.socket(af, socktype, proto)
sock.bind(sa)
sock.listen(5)
try:
yield sa
finally:
sock.close()
+ @pytest.fixture(**build_addr_infos())
+ def nonlistening_addr(request):
+ af, socktype, proto, canonname, sa = request.param
+ return sa
+
+
class TestCheckPort:
def test_check_port_listening(self, listening_addr):
with pytest.raises(IOError):
portend._check_port(*listening_addr[:2])
+
+ def test_check_port_nonlistening(self, nonlistening_addr):
+ portend._check_port(*nonlistening_addr[:2])
|
bb90fe7c59435d1bef361b64d4083710ffadcf7f
|
common/apps.py
|
common/apps.py
|
from django.apps import AppConfig
from django.conf import settings
from common.helpers.db import db_is_initialized
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.display_missing_environment_variables()
from common.helpers.tags import import_tags_from_csv
if db_is_initialized():
import_tags_from_csv()
def display_missing_environment_variables(self):
for key, value in settings.ENVIRONMENT_VARIABLE_WARNINGS.items():
if not hasattr(settings, key):
print(value['message'])
|
from django.apps import AppConfig
from django.conf import settings
from common.helpers.db import db_is_initialized
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.display_missing_environment_variables()
from common.helpers.tags import import_tags_from_csv
if db_is_initialized():
import_tags_from_csv()
def display_missing_environment_variables(self):
for key, value in settings.ENVIRONMENT_VARIABLE_WARNINGS.items():
if not hasattr(settings, key):
if value['error']:
raise EnvironmentError(value['message'])
else:
print(value['message'])
|
Stop server startup when required environment variables are missing
|
Stop server startup when required environment variables are missing
|
Python
|
mit
|
DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange,DemocracyLab/CivicTechExchange
|
from django.apps import AppConfig
from django.conf import settings
from common.helpers.db import db_is_initialized
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.display_missing_environment_variables()
from common.helpers.tags import import_tags_from_csv
if db_is_initialized():
import_tags_from_csv()
def display_missing_environment_variables(self):
for key, value in settings.ENVIRONMENT_VARIABLE_WARNINGS.items():
if not hasattr(settings, key):
+ if value['error']:
+ raise EnvironmentError(value['message'])
+ else:
- print(value['message'])
+ print(value['message'])
|
Stop server startup when required environment variables are missing
|
## Code Before:
from django.apps import AppConfig
from django.conf import settings
from common.helpers.db import db_is_initialized
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.display_missing_environment_variables()
from common.helpers.tags import import_tags_from_csv
if db_is_initialized():
import_tags_from_csv()
def display_missing_environment_variables(self):
for key, value in settings.ENVIRONMENT_VARIABLE_WARNINGS.items():
if not hasattr(settings, key):
print(value['message'])
## Instruction:
Stop server startup when required environment variables are missing
## Code After:
from django.apps import AppConfig
from django.conf import settings
from common.helpers.db import db_is_initialized
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.display_missing_environment_variables()
from common.helpers.tags import import_tags_from_csv
if db_is_initialized():
import_tags_from_csv()
def display_missing_environment_variables(self):
for key, value in settings.ENVIRONMENT_VARIABLE_WARNINGS.items():
if not hasattr(settings, key):
if value['error']:
raise EnvironmentError(value['message'])
else:
print(value['message'])
|
from django.apps import AppConfig
from django.conf import settings
from common.helpers.db import db_is_initialized
class CommonConfig(AppConfig):
name = 'common'
def ready(self):
self.display_missing_environment_variables()
from common.helpers.tags import import_tags_from_csv
if db_is_initialized():
import_tags_from_csv()
def display_missing_environment_variables(self):
for key, value in settings.ENVIRONMENT_VARIABLE_WARNINGS.items():
if not hasattr(settings, key):
+ if value['error']:
+ raise EnvironmentError(value['message'])
+ else:
- print(value['message'])
+ print(value['message'])
? ++++
|
76e766998984da126de4cb6121c07690fbdeeba1
|
pystil/data/graph/line.py
|
pystil/data/graph/line.py
|
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site, graph, criteria, from_date, to_date, step, stamp, lang):
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
if criteria == 'unique' else count(1).label("count"))
.filter(on(site))
.filter(between(from_date, to_date)))
if criteria == 'new':
rq = rq.filter(Visit.last_visit == None)
results = rq.group_by(Visit.day).order_by(Visit.day).all()
return make_time_serie(results, criteria, from_date, to_date, lang)
|
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site, graph, criteria, from_date, to_date, step, stamp, lang):
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
if criteria in ('unique', 'new') else count(1).label("count"))
.filter(on(site))
.filter(between(from_date, to_date)))
if criteria == 'new':
rq = rq.filter(Visit.last_visit == None)
results = rq.group_by(Visit.day).order_by(Visit.day).all()
return make_time_serie(results, criteria, from_date, to_date, lang)
|
Fix the new/unique visits (at least!)
|
Fix the new/unique visits (at least!)
|
Python
|
bsd-3-clause
|
Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil
|
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site, graph, criteria, from_date, to_date, step, stamp, lang):
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
- if criteria == 'unique' else count(1).label("count"))
+ if criteria in ('unique', 'new') else count(1).label("count"))
.filter(on(site))
.filter(between(from_date, to_date)))
if criteria == 'new':
rq = rq.filter(Visit.last_visit == None)
results = rq.group_by(Visit.day).order_by(Visit.day).all()
return make_time_serie(results, criteria, from_date, to_date, lang)
|
Fix the new/unique visits (at least!)
|
## Code Before:
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site, graph, criteria, from_date, to_date, step, stamp, lang):
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
if criteria == 'unique' else count(1).label("count"))
.filter(on(site))
.filter(between(from_date, to_date)))
if criteria == 'new':
rq = rq.filter(Visit.last_visit == None)
results = rq.group_by(Visit.day).order_by(Visit.day).all()
return make_time_serie(results, criteria, from_date, to_date, lang)
## Instruction:
Fix the new/unique visits (at least!)
## Code After:
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site, graph, criteria, from_date, to_date, step, stamp, lang):
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
if criteria in ('unique', 'new') else count(1).label("count"))
.filter(on(site))
.filter(between(from_date, to_date)))
if criteria == 'new':
rq = rq.filter(Visit.last_visit == None)
results = rq.group_by(Visit.day).order_by(Visit.day).all()
return make_time_serie(results, criteria, from_date, to_date, lang)
|
"""Treat line data"""
from pystil.data.utils import make_time_serie, on, between
from pystil.db import db, count, Visit, distinct
def process_data(site, graph, criteria, from_date, to_date, step, stamp, lang):
rq = (db.session
.query(Visit.day.label("key"),
count(distinct(Visit.uuid)).label("count")
- if criteria == 'unique' else count(1).label("count"))
? ^^
+ if criteria in ('unique', 'new') else count(1).label("count"))
? ^^ + ++++++++
.filter(on(site))
.filter(between(from_date, to_date)))
if criteria == 'new':
rq = rq.filter(Visit.last_visit == None)
results = rq.group_by(Visit.day).order_by(Visit.day).all()
return make_time_serie(results, criteria, from_date, to_date, lang)
|
75c48ecbac476fd751e55745cc2935c1dac1f138
|
longest_duplicated_substring.py
|
longest_duplicated_substring.py
|
import sys
# O(n^4) approach: generate all possible substrings and
# compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
# Alternate approach with while loop here and max update outside.
# Can also break length check into function.
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
import sys
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
Move todos into issues tracking on GitHub
|
Move todos into issues tracking on GitHub
|
Python
|
mit
|
taylor-peterson/longest-duplicated-substring
|
import sys
-
- # O(n^4) approach: generate all possible substrings and
- # compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
- # Alternate approach with while loop here and max update outside.
- # Can also break length check into function.
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
Move todos into issues tracking on GitHub
|
## Code Before:
import sys
# O(n^4) approach: generate all possible substrings and
# compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
# Alternate approach with while loop here and max update outside.
# Can also break length check into function.
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
## Instruction:
Move todos into issues tracking on GitHub
## Code After:
import sys
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
import sys
-
- # O(n^4) approach: generate all possible substrings and
- # compare each for equality.
def longest_duplicated_substring(string):
"""Return the longest duplicated substring.
Keyword Arguments:
string -- the string to examine for duplicated substrings
This approach examines each possible pair of starting points
for duplicated substrings. If the characters at those points are
the same, the match is extended up to the maximum length for those
points. Each new longest duplicated substring is recorded as the
best found so far.
This solution is optimal for the naive brute-force approach and
runs in O(n^3).
"""
lds = ""
string_length = len(string)
for i in range(string_length):
for j in range(i+1,string_length):
- # Alternate approach with while loop here and max update outside.
- # Can also break length check into function.
for substring_length in range(string_length-j):
if string[i+substring_length] != string[j+substring_length]:
break
elif substring_length + 1 > len(lds):
lds = string[i:i+substring_length+1]
return lds
if __name__ == "__main__":
print(longest_duplicated_substring(' '.join(map(str, sys.argv[1:]))))
|
fc23b7e6a330bd24d49edb60df3a7e8d948c6c32
|
main.py
|
main.py
|
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Canvas, Color, Rectangle
from action_map import ActionMap
from camera import Camera
from graphics import Graphics
class ActionGame(Widget):
action_map = ActionMap()
graphics = Graphics()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.camera = Camera(self.graphics, self.action_map)
self.add_widget(self.camera)
self.bind(size=self.resize)
def update(self, dt):
self.camera.update()
def on_touch_down(self, touch):
self.last_touch_x = touch.x
self.last_touch_y = touch.y
def on_touch_move(self, touch):
self.camera.change_pos_by(self.last_touch_x - touch.x, self.last_touch_y - touch.y )
self.last_touch_x = touch.x
self.last_touch_y = touch.y
def resize(self, instance, value):
self.camera.resize(self)
class ActionApp(App):
def build(self):
game = ActionGame()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
if __name__ == '__main__':
ActionApp().run()
|
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Canvas, Color, Rectangle
from action_map import ActionMap
from camera import Camera
from graphics import Graphics
class ActionGame(Widget):
action_map = ActionMap()
graphics = Graphics()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.camera = Camera(self.graphics, self.action_map)
self.add_widget(self.camera)
self.bind(size=self.resize)
def update(self, dt):
self.camera.update()
def on_touch_move(self, touch):
self.camera.change_pos_by(-touch.dx, -touch.dy)
def resize(self, instance, value):
self.camera.resize(self)
class ActionApp(App):
def build(self):
game = ActionGame()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
if __name__ == '__main__':
ActionApp().run()
|
Simplify camera response to touch input
|
Simplify camera response to touch input
|
Python
|
mit
|
Corrob/Action-Game
|
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Canvas, Color, Rectangle
from action_map import ActionMap
from camera import Camera
from graphics import Graphics
class ActionGame(Widget):
action_map = ActionMap()
graphics = Graphics()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.camera = Camera(self.graphics, self.action_map)
self.add_widget(self.camera)
self.bind(size=self.resize)
def update(self, dt):
self.camera.update()
- def on_touch_down(self, touch):
- self.last_touch_x = touch.x
- self.last_touch_y = touch.y
-
def on_touch_move(self, touch):
+ self.camera.change_pos_by(-touch.dx, -touch.dy)
- self.camera.change_pos_by(self.last_touch_x - touch.x, self.last_touch_y - touch.y )
- self.last_touch_x = touch.x
- self.last_touch_y = touch.y
def resize(self, instance, value):
self.camera.resize(self)
class ActionApp(App):
def build(self):
game = ActionGame()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
if __name__ == '__main__':
ActionApp().run()
|
Simplify camera response to touch input
|
## Code Before:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Canvas, Color, Rectangle
from action_map import ActionMap
from camera import Camera
from graphics import Graphics
class ActionGame(Widget):
action_map = ActionMap()
graphics = Graphics()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.camera = Camera(self.graphics, self.action_map)
self.add_widget(self.camera)
self.bind(size=self.resize)
def update(self, dt):
self.camera.update()
def on_touch_down(self, touch):
self.last_touch_x = touch.x
self.last_touch_y = touch.y
def on_touch_move(self, touch):
self.camera.change_pos_by(self.last_touch_x - touch.x, self.last_touch_y - touch.y )
self.last_touch_x = touch.x
self.last_touch_y = touch.y
def resize(self, instance, value):
self.camera.resize(self)
class ActionApp(App):
def build(self):
game = ActionGame()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
if __name__ == '__main__':
ActionApp().run()
## Instruction:
Simplify camera response to touch input
## Code After:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Canvas, Color, Rectangle
from action_map import ActionMap
from camera import Camera
from graphics import Graphics
class ActionGame(Widget):
action_map = ActionMap()
graphics = Graphics()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.camera = Camera(self.graphics, self.action_map)
self.add_widget(self.camera)
self.bind(size=self.resize)
def update(self, dt):
self.camera.update()
def on_touch_move(self, touch):
self.camera.change_pos_by(-touch.dx, -touch.dy)
def resize(self, instance, value):
self.camera.resize(self)
class ActionApp(App):
def build(self):
game = ActionGame()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
if __name__ == '__main__':
ActionApp().run()
|
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.graphics import Canvas, Color, Rectangle
from action_map import ActionMap
from camera import Camera
from graphics import Graphics
class ActionGame(Widget):
action_map = ActionMap()
graphics = Graphics()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.camera = Camera(self.graphics, self.action_map)
self.add_widget(self.camera)
self.bind(size=self.resize)
def update(self, dt):
self.camera.update()
- def on_touch_down(self, touch):
- self.last_touch_x = touch.x
- self.last_touch_y = touch.y
-
def on_touch_move(self, touch):
+ self.camera.change_pos_by(-touch.dx, -touch.dy)
- self.camera.change_pos_by(self.last_touch_x - touch.x, self.last_touch_y - touch.y )
- self.last_touch_x = touch.x
- self.last_touch_y = touch.y
def resize(self, instance, value):
self.camera.resize(self)
class ActionApp(App):
def build(self):
game = ActionGame()
Clock.schedule_interval(game.update, 1.0 / 60.0)
return game
if __name__ == '__main__':
ActionApp().run()
|
534633d078fe6f81e67ead075ac31faac0c3c60d
|
tests/__init__.py
|
tests/__init__.py
|
import pycurl
def setup_package():
print('Testing %s' % pycurl.version)
|
def setup_package():
# import here, not globally, so that running
# python -m tests.appmanager
# to launch the app manager is possible without having pycurl installed
# (as the test app does not depend on pycurl)
import pycurl
print('Testing %s' % pycurl.version)
|
Make it possible to run test app without pycurl being installed
|
Make it possible to run test app without pycurl being installed
|
Python
|
lgpl-2.1
|
pycurl/pycurl,pycurl/pycurl,pycurl/pycurl
|
- import pycurl
-
def setup_package():
+ # import here, not globally, so that running
+ # python -m tests.appmanager
+ # to launch the app manager is possible without having pycurl installed
+ # (as the test app does not depend on pycurl)
+ import pycurl
+
print('Testing %s' % pycurl.version)
|
Make it possible to run test app without pycurl being installed
|
## Code Before:
import pycurl
def setup_package():
print('Testing %s' % pycurl.version)
## Instruction:
Make it possible to run test app without pycurl being installed
## Code After:
def setup_package():
# import here, not globally, so that running
# python -m tests.appmanager
# to launch the app manager is possible without having pycurl installed
# (as the test app does not depend on pycurl)
import pycurl
print('Testing %s' % pycurl.version)
|
- import pycurl
-
def setup_package():
+ # import here, not globally, so that running
+ # python -m tests.appmanager
+ # to launch the app manager is possible without having pycurl installed
+ # (as the test app does not depend on pycurl)
+ import pycurl
+
print('Testing %s' % pycurl.version)
|
178006e4a299ca67e758184be50ae94333f09821
|
test_settings.py
|
test_settings.py
|
from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
|
from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
ONA_API_URL = 'https://odk.ona.io'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
|
Add url setting to test settings
|
Add url setting to test settings
|
Python
|
bsd-2-clause
|
praekelt/malaria24-django,praekelt/malaria24-django,praekelt/malaria24-django,praekelt/malaria24-django
|
from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
+ ONA_API_URL = 'https://odk.ona.io'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
|
Add url setting to test settings
|
## Code Before:
from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
## Instruction:
Add url setting to test settings
## Code After:
from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
ONA_API_URL = 'https://odk.ona.io'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
|
from malaria24.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'malaria24',
}
}
ONAPIE_ACCESS_TOKEN = 'foo'
+ ONA_API_URL = 'https://odk.ona.io'
VUMI_GO_ACCOUNT_KEY = 'VUMI_GO_ACCOUNT_KEY'
VUMI_GO_API_TOKEN = 'VUMI_GO_API_TOKEN'
VUMI_GO_CONVERSATION_KEY = 'VUMI_GO_CONVERSATION_KEY'
|
331ce5fde1a653997900f3e247f9d34a2c47fb54
|
projects/models.py
|
projects/models.py
|
from django.conf import settings
from django.db import models
class InlistItem(models.Model):
text = models.CharField(max_length=255, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return self.text
class Meta:
unique_together = ('text', 'user')
|
from django.conf import settings
from django.db import models
class InlistItem(models.Model):
text = models.CharField(max_length=255, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return self.text
class Meta:
unique_together = ('text', 'user')
ordering = ('pk',)
|
Add explicit ordering to inlist items
|
Add explicit ordering to inlist items
|
Python
|
mit
|
XeryusTC/projman,XeryusTC/projman,XeryusTC/projman
|
from django.conf import settings
from django.db import models
class InlistItem(models.Model):
text = models.CharField(max_length=255, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return self.text
class Meta:
unique_together = ('text', 'user')
+ ordering = ('pk',)
|
Add explicit ordering to inlist items
|
## Code Before:
from django.conf import settings
from django.db import models
class InlistItem(models.Model):
text = models.CharField(max_length=255, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return self.text
class Meta:
unique_together = ('text', 'user')
## Instruction:
Add explicit ordering to inlist items
## Code After:
from django.conf import settings
from django.db import models
class InlistItem(models.Model):
text = models.CharField(max_length=255, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return self.text
class Meta:
unique_together = ('text', 'user')
ordering = ('pk',)
|
from django.conf import settings
from django.db import models
class InlistItem(models.Model):
text = models.CharField(max_length=255, default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
def __str__(self):
return self.text
class Meta:
unique_together = ('text', 'user')
+ ordering = ('pk',)
|
2ee763ae1e4564a57692cb7161f99daab4ae77b7
|
cookiecutter/main.py
|
cookiecutter/main.py
|
import argparse
import os
from .find import find_template
from .generate import generate_context, generate_files
from .vcs import git_clone
def main():
""" Entry point for the package, as defined in setup.py. """
# Get command line input/output arguments
parser = argparse.ArgumentParser(
description='Create a project from a Cookiecutter project template.'
)
parser.add_argument(
'input_dir',
help='Cookiecutter project template dir, e.g. {{project.repo_name}}/'
)
args = parser.parse_args()
# If it's a git repo, clone and prompt
if args.input_dir.endswith('.git'):
repo_dir = git_clone(args.input_dir)
project_template = find_template(repo_dir)
os.chdir(repo_dir)
else:
project_template = args.input_dir
# Create project from local context and project template.
context = generate_context()
generate_files(
input_dir=project_template,
context=context
)
if __name__ == '__main__':
main()
|
import argparse
import os
from .cleanup import remove_repo
from .find import find_template
from .generate import generate_context, generate_files
from .vcs import git_clone
def main():
""" Entry point for the package, as defined in setup.py. """
# Get command line input/output arguments
parser = argparse.ArgumentParser(
description='Create a project from a Cookiecutter project template.'
)
parser.add_argument(
'input_dir',
help='Cookiecutter project template dir, e.g. {{project.repo_name}}/'
)
args = parser.parse_args()
# If it's a git repo, clone and prompt
if args.input_dir.endswith('.git'):
got_repo_arg = True
repo_dir = git_clone(args.input_dir)
project_template = find_template(repo_dir)
os.chdir(repo_dir)
else:
project_template = args.input_dir
# Create project from local context and project template.
context = generate_context()
generate_files(
input_dir=project_template,
context=context
)
# Remove repo if Cookiecutter cloned it in the first place.
# Here the user just wants a project, not a project template.
if got_repo_arg:
generated_project = context['project']['repo_name']
remove_repo(repo_dir, generated_project)
if __name__ == '__main__':
main()
|
Clean up after cloned repo if needed. (partial checkin)
|
Clean up after cloned repo if needed. (partial checkin)
|
Python
|
bsd-3-clause
|
atlassian/cookiecutter,dajose/cookiecutter,luzfcb/cookiecutter,foodszhang/cookiecutter,Springerle/cookiecutter,willingc/cookiecutter,utek/cookiecutter,takeflight/cookiecutter,takeflight/cookiecutter,willingc/cookiecutter,stevepiercy/cookiecutter,vincentbernat/cookiecutter,cguardia/cookiecutter,0k/cookiecutter,nhomar/cookiecutter,janusnic/cookiecutter,benthomasson/cookiecutter,0k/cookiecutter,foodszhang/cookiecutter,kkujawinski/cookiecutter,ionelmc/cookiecutter,michaeljoseph/cookiecutter,sp1rs/cookiecutter,jhermann/cookiecutter,lucius-feng/cookiecutter,agconti/cookiecutter,michaeljoseph/cookiecutter,ramiroluz/cookiecutter,letolab/cookiecutter,hackebrot/cookiecutter,audreyr/cookiecutter,sp1rs/cookiecutter,kkujawinski/cookiecutter,vincentbernat/cookiecutter,agconti/cookiecutter,lucius-feng/cookiecutter,drgarcia1986/cookiecutter,drgarcia1986/cookiecutter,atlassian/cookiecutter,ionelmc/cookiecutter,lgp171188/cookiecutter,audreyr/cookiecutter,nhomar/cookiecutter,alex/cookiecutter,cichm/cookiecutter,moi65/cookiecutter,lgp171188/cookiecutter,hackebrot/cookiecutter,tylerdave/cookiecutter,terryjbates/cookiecutter,stevepiercy/cookiecutter,janusnic/cookiecutter,utek/cookiecutter,moi65/cookiecutter,christabor/cookiecutter,vintasoftware/cookiecutter,alex/cookiecutter,cichm/cookiecutter,tylerdave/cookiecutter,letolab/cookiecutter,Vauxoo/cookiecutter,Springerle/cookiecutter,jhermann/cookiecutter,vintasoftware/cookiecutter,cguardia/cookiecutter,Vauxoo/cookiecutter,benthomasson/cookiecutter,dajose/cookiecutter,pjbull/cookiecutter,christabor/cookiecutter,venumech/cookiecutter,luzfcb/cookiecutter,terryjbates/cookiecutter,pjbull/cookiecutter,ramiroluz/cookiecutter,venumech/cookiecutter
|
import argparse
import os
+ from .cleanup import remove_repo
from .find import find_template
from .generate import generate_context, generate_files
from .vcs import git_clone
def main():
""" Entry point for the package, as defined in setup.py. """
# Get command line input/output arguments
parser = argparse.ArgumentParser(
description='Create a project from a Cookiecutter project template.'
)
parser.add_argument(
'input_dir',
help='Cookiecutter project template dir, e.g. {{project.repo_name}}/'
)
args = parser.parse_args()
# If it's a git repo, clone and prompt
if args.input_dir.endswith('.git'):
+ got_repo_arg = True
repo_dir = git_clone(args.input_dir)
project_template = find_template(repo_dir)
os.chdir(repo_dir)
else:
project_template = args.input_dir
# Create project from local context and project template.
context = generate_context()
generate_files(
input_dir=project_template,
context=context
)
+ # Remove repo if Cookiecutter cloned it in the first place.
+ # Here the user just wants a project, not a project template.
+ if got_repo_arg:
+ generated_project = context['project']['repo_name']
+ remove_repo(repo_dir, generated_project)
if __name__ == '__main__':
main()
|
Clean up after cloned repo if needed. (partial checkin)
|
## Code Before:
import argparse
import os
from .find import find_template
from .generate import generate_context, generate_files
from .vcs import git_clone
def main():
""" Entry point for the package, as defined in setup.py. """
# Get command line input/output arguments
parser = argparse.ArgumentParser(
description='Create a project from a Cookiecutter project template.'
)
parser.add_argument(
'input_dir',
help='Cookiecutter project template dir, e.g. {{project.repo_name}}/'
)
args = parser.parse_args()
# If it's a git repo, clone and prompt
if args.input_dir.endswith('.git'):
repo_dir = git_clone(args.input_dir)
project_template = find_template(repo_dir)
os.chdir(repo_dir)
else:
project_template = args.input_dir
# Create project from local context and project template.
context = generate_context()
generate_files(
input_dir=project_template,
context=context
)
if __name__ == '__main__':
main()
## Instruction:
Clean up after cloned repo if needed. (partial checkin)
## Code After:
import argparse
import os
from .cleanup import remove_repo
from .find import find_template
from .generate import generate_context, generate_files
from .vcs import git_clone
def main():
""" Entry point for the package, as defined in setup.py. """
# Get command line input/output arguments
parser = argparse.ArgumentParser(
description='Create a project from a Cookiecutter project template.'
)
parser.add_argument(
'input_dir',
help='Cookiecutter project template dir, e.g. {{project.repo_name}}/'
)
args = parser.parse_args()
# If it's a git repo, clone and prompt
if args.input_dir.endswith('.git'):
got_repo_arg = True
repo_dir = git_clone(args.input_dir)
project_template = find_template(repo_dir)
os.chdir(repo_dir)
else:
project_template = args.input_dir
# Create project from local context and project template.
context = generate_context()
generate_files(
input_dir=project_template,
context=context
)
# Remove repo if Cookiecutter cloned it in the first place.
# Here the user just wants a project, not a project template.
if got_repo_arg:
generated_project = context['project']['repo_name']
remove_repo(repo_dir, generated_project)
if __name__ == '__main__':
main()
|
import argparse
import os
+ from .cleanup import remove_repo
from .find import find_template
from .generate import generate_context, generate_files
from .vcs import git_clone
def main():
""" Entry point for the package, as defined in setup.py. """
# Get command line input/output arguments
parser = argparse.ArgumentParser(
description='Create a project from a Cookiecutter project template.'
)
parser.add_argument(
'input_dir',
help='Cookiecutter project template dir, e.g. {{project.repo_name}}/'
)
args = parser.parse_args()
# If it's a git repo, clone and prompt
if args.input_dir.endswith('.git'):
+ got_repo_arg = True
repo_dir = git_clone(args.input_dir)
project_template = find_template(repo_dir)
os.chdir(repo_dir)
else:
project_template = args.input_dir
# Create project from local context and project template.
context = generate_context()
generate_files(
input_dir=project_template,
context=context
)
+ # Remove repo if Cookiecutter cloned it in the first place.
+ # Here the user just wants a project, not a project template.
+ if got_repo_arg:
+ generated_project = context['project']['repo_name']
+ remove_repo(repo_dir, generated_project)
if __name__ == '__main__':
main()
|
d48ceb2364f463c725175010c3d29ea903dbcd1a
|
setup.py
|
setup.py
|
from distutils.core import setup
DESCRIPTION = """
Python money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.
"""
setup(
name='money',
description='Python Money Class',
# long_description=DESCRIPTION,
version='1.1.0-dev',
author='Carlos Palol',
author_email='[email protected]',
url='https://github.com/carlospalol/money',
license='MIT',
packages=[
'money',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
]
)
|
from distutils.core import setup
DESCRIPTION = """
Python money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.
"""
SOURCE_ROOT = 'src'
# Python 2 backwards compatibility
if sys.version_info[0] == 2:
SOURCE_ROOT = 'src-py2'
setup(
name='money',
description='Python Money Class',
# long_description=DESCRIPTION,
version='1.1.0-dev',
author='Carlos Palol',
author_email='[email protected]',
url='https://github.com/carlospalol/money',
license='MIT',
package_dir={'': SOURCE_ROOT},
packages=[
'money',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
]
)
|
Switch source root if py2
|
Switch source root if py2
|
Python
|
mit
|
carlospalol/money,Isendir/money
|
from distutils.core import setup
DESCRIPTION = """
Python money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.
"""
+
+ SOURCE_ROOT = 'src'
+
+ # Python 2 backwards compatibility
+ if sys.version_info[0] == 2:
+ SOURCE_ROOT = 'src-py2'
+
setup(
name='money',
description='Python Money Class',
# long_description=DESCRIPTION,
version='1.1.0-dev',
author='Carlos Palol',
author_email='[email protected]',
url='https://github.com/carlospalol/money',
license='MIT',
+ package_dir={'': SOURCE_ROOT},
packages=[
'money',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
]
)
|
Switch source root if py2
|
## Code Before:
from distutils.core import setup
DESCRIPTION = """
Python money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.
"""
setup(
name='money',
description='Python Money Class',
# long_description=DESCRIPTION,
version='1.1.0-dev',
author='Carlos Palol',
author_email='[email protected]',
url='https://github.com/carlospalol/money',
license='MIT',
packages=[
'money',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
]
)
## Instruction:
Switch source root if py2
## Code After:
from distutils.core import setup
DESCRIPTION = """
Python money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.
"""
SOURCE_ROOT = 'src'
# Python 2 backwards compatibility
if sys.version_info[0] == 2:
SOURCE_ROOT = 'src-py2'
setup(
name='money',
description='Python Money Class',
# long_description=DESCRIPTION,
version='1.1.0-dev',
author='Carlos Palol',
author_email='[email protected]',
url='https://github.com/carlospalol/money',
license='MIT',
package_dir={'': SOURCE_ROOT},
packages=[
'money',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
]
)
|
from distutils.core import setup
DESCRIPTION = """
Python money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.
"""
+
+ SOURCE_ROOT = 'src'
+
+ # Python 2 backwards compatibility
+ if sys.version_info[0] == 2:
+ SOURCE_ROOT = 'src-py2'
+
setup(
name='money',
description='Python Money Class',
# long_description=DESCRIPTION,
version='1.1.0-dev',
author='Carlos Palol',
author_email='[email protected]',
url='https://github.com/carlospalol/money',
license='MIT',
+ package_dir={'': SOURCE_ROOT},
packages=[
'money',
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
]
)
|
7f1db4023f2310529822d721379b1019aaf320fc
|
tablib/formats/_df.py
|
tablib/formats/_df.py
|
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from pandas import DataFrame
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
try:
from pandas import DataFrame
except ImportError:
DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
if DataFrame is None:
return False
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
if DataFrame is None:
raise NotImplementedError(
'DataFrame Format requires `pandas` to be installed.'
' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
Raise NotImplementedError if pandas is not installed
|
Raise NotImplementedError if pandas is not installed
|
Python
|
mit
|
kennethreitz/tablib
|
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
+ try:
- from pandas import DataFrame
+ from pandas import DataFrame
+ except ImportError:
+ DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
+ if DataFrame is None:
+ return False
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
+ if DataFrame is None:
+ raise NotImplementedError(
+ 'DataFrame Format requires `pandas` to be installed.'
+ ' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
Raise NotImplementedError if pandas is not installed
|
## Code Before:
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from pandas import DataFrame
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
## Instruction:
Raise NotImplementedError if pandas is not installed
## Code After:
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
try:
from pandas import DataFrame
except ImportError:
DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
if DataFrame is None:
return False
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
if DataFrame is None:
raise NotImplementedError(
'DataFrame Format requires `pandas` to be installed.'
' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
+ try:
- from pandas import DataFrame
+ from pandas import DataFrame
? ++++
+ except ImportError:
+ DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df', )
def detect(stream):
"""Returns True if given stream is a DataFrame."""
+ if DataFrame is None:
+ return False
try:
DataFrame(stream)
return True
except ValueError:
return False
def export_set(dset, index=None):
"""Returns DataFrame representation of DataBook."""
+ if DataFrame is None:
+ raise NotImplementedError(
+ 'DataFrame Format requires `pandas` to be installed.'
+ ' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def import_set(dset, in_stream):
"""Returns dataset from DataFrame."""
dset.wipe()
dset.dict = in_stream.to_dict(orient='records')
|
e8942651a43c7af1375b42ddd6521b4e65169b95
|
conanfile.py
|
conanfile.py
|
from conans import ConanFile, CMake
class Core8(ConanFile):
name = "core8"
version = "0.1"
url = "https://github.com/benvenutti/core8.git"
settings = "os", "compiler", "build_type", "arch"
license = "MIT"
exports_sources = "*"
def build(self):
cmake = CMake(self.settings)
self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
self.run("cmake --build . %s" % cmake.build_config)
def package(self):
self.copy("*.hpp", dst="include/core8", src="include/core8")
self.copy("*", dst="lib", src="lib")
def package_info(self):
self.cpp_info.libs = ["core8"]
|
from conans import ConanFile, CMake
class Core8(ConanFile):
name = "core8"
version = "0.1"
url = "https://github.com/benvenutti/core8.git"
description = """A Chip-8 VM implemented in C++"""
settings = "os", "compiler", "build_type", "arch"
license = "MIT"
exports_sources = "*"
def build(self):
cmake = CMake(self.settings)
self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
self.run("cmake --build . %s" % cmake.build_config)
self.run("ctest .")
def package(self):
self.copy("*.hpp", dst="include/core8", src="include/core8")
self.copy("*", dst="lib", src="lib")
def package_info(self):
self.cpp_info.libs = ["core8"]
|
Add description and test build stage
|
Add description and test build stage
|
Python
|
mit
|
benvenutti/core8,benvenutti/core8
|
from conans import ConanFile, CMake
class Core8(ConanFile):
name = "core8"
version = "0.1"
url = "https://github.com/benvenutti/core8.git"
+ description = """A Chip-8 VM implemented in C++"""
settings = "os", "compiler", "build_type", "arch"
license = "MIT"
exports_sources = "*"
def build(self):
cmake = CMake(self.settings)
self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
self.run("cmake --build . %s" % cmake.build_config)
+ self.run("ctest .")
def package(self):
self.copy("*.hpp", dst="include/core8", src="include/core8")
self.copy("*", dst="lib", src="lib")
def package_info(self):
self.cpp_info.libs = ["core8"]
|
Add description and test build stage
|
## Code Before:
from conans import ConanFile, CMake
class Core8(ConanFile):
name = "core8"
version = "0.1"
url = "https://github.com/benvenutti/core8.git"
settings = "os", "compiler", "build_type", "arch"
license = "MIT"
exports_sources = "*"
def build(self):
cmake = CMake(self.settings)
self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
self.run("cmake --build . %s" % cmake.build_config)
def package(self):
self.copy("*.hpp", dst="include/core8", src="include/core8")
self.copy("*", dst="lib", src="lib")
def package_info(self):
self.cpp_info.libs = ["core8"]
## Instruction:
Add description and test build stage
## Code After:
from conans import ConanFile, CMake
class Core8(ConanFile):
name = "core8"
version = "0.1"
url = "https://github.com/benvenutti/core8.git"
description = """A Chip-8 VM implemented in C++"""
settings = "os", "compiler", "build_type", "arch"
license = "MIT"
exports_sources = "*"
def build(self):
cmake = CMake(self.settings)
self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
self.run("cmake --build . %s" % cmake.build_config)
self.run("ctest .")
def package(self):
self.copy("*.hpp", dst="include/core8", src="include/core8")
self.copy("*", dst="lib", src="lib")
def package_info(self):
self.cpp_info.libs = ["core8"]
|
from conans import ConanFile, CMake
class Core8(ConanFile):
name = "core8"
version = "0.1"
url = "https://github.com/benvenutti/core8.git"
+ description = """A Chip-8 VM implemented in C++"""
settings = "os", "compiler", "build_type", "arch"
license = "MIT"
exports_sources = "*"
def build(self):
cmake = CMake(self.settings)
self.run('cmake %s %s' % (self.conanfile_directory, cmake.command_line))
self.run("cmake --build . %s" % cmake.build_config)
+ self.run("ctest .")
def package(self):
self.copy("*.hpp", dst="include/core8", src="include/core8")
self.copy("*", dst="lib", src="lib")
def package_info(self):
self.cpp_info.libs = ["core8"]
|
547e002534d3a9757c84bad7e125b9186dd78078
|
tests/test_common.py
|
tests/test_common.py
|
import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/etc/slack']
self.config = ConfigParser.ConfigParser()
self.config.read(search_paths)
if self.config.has_section('Slack'):
self.access_token = self.config.get('Slack', 'token')
elif 'SLACK_TOKEN' in os.environ:
self.access_token = os.environ['SLACK_TOKEN']
else:
print('Authorization token not detected! The token is pulled from '\
'~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.')
self.test_channel = self.config.get('Slack', 'test-channel')
def set_up_slack(self):
self.slack = slack.Slack(self.access_token)
|
import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/etc/slack']
self.config = ConfigParser.ConfigParser()
self.config.read(search_paths)
if self.config.has_section('Slack'):
self.access_token = self.config.get('Slack', 'token')
elif 'SLACK_TOKEN' in os.environ:
self.access_token = os.environ['SLACK_TOKEN']
else:
print('Authorization token not detected! The token is pulled from '\
'~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.')
self.test_channel = self.config.get('Slack', 'test-channel')
self.test_channel_name = self.config.get('Slack', 'test-channel-name')
def set_up_slack(self):
self.slack = slack.Slack(self.access_token)
|
Add new channel name for test.
|
Add new channel name for test.
|
Python
|
mit
|
nabetama/slacky
|
import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/etc/slack']
self.config = ConfigParser.ConfigParser()
self.config.read(search_paths)
if self.config.has_section('Slack'):
self.access_token = self.config.get('Slack', 'token')
elif 'SLACK_TOKEN' in os.environ:
self.access_token = os.environ['SLACK_TOKEN']
else:
print('Authorization token not detected! The token is pulled from '\
'~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.')
- self.test_channel = self.config.get('Slack', 'test-channel')
+ self.test_channel = self.config.get('Slack', 'test-channel')
+ self.test_channel_name = self.config.get('Slack', 'test-channel-name')
def set_up_slack(self):
self.slack = slack.Slack(self.access_token)
|
Add new channel name for test.
|
## Code Before:
import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/etc/slack']
self.config = ConfigParser.ConfigParser()
self.config.read(search_paths)
if self.config.has_section('Slack'):
self.access_token = self.config.get('Slack', 'token')
elif 'SLACK_TOKEN' in os.environ:
self.access_token = os.environ['SLACK_TOKEN']
else:
print('Authorization token not detected! The token is pulled from '\
'~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.')
self.test_channel = self.config.get('Slack', 'test-channel')
def set_up_slack(self):
self.slack = slack.Slack(self.access_token)
## Instruction:
Add new channel name for test.
## Code After:
import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/etc/slack']
self.config = ConfigParser.ConfigParser()
self.config.read(search_paths)
if self.config.has_section('Slack'):
self.access_token = self.config.get('Slack', 'token')
elif 'SLACK_TOKEN' in os.environ:
self.access_token = os.environ['SLACK_TOKEN']
else:
print('Authorization token not detected! The token is pulled from '\
'~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.')
self.test_channel = self.config.get('Slack', 'test-channel')
self.test_channel_name = self.config.get('Slack', 'test-channel-name')
def set_up_slack(self):
self.slack = slack.Slack(self.access_token)
|
import os, os.path
import ConfigParser
package = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import slack
class TestSlack(object):
def setup(self):
self.set_up_config()
self.set_up_slack()
def set_up_config(self):
search_paths = [os.path.expanduser('~/.slack'), '/etc/slack']
self.config = ConfigParser.ConfigParser()
self.config.read(search_paths)
if self.config.has_section('Slack'):
self.access_token = self.config.get('Slack', 'token')
elif 'SLACK_TOKEN' in os.environ:
self.access_token = os.environ['SLACK_TOKEN']
else:
print('Authorization token not detected! The token is pulled from '\
'~/.slack, /etc/slack, or the environment variable SLACK_TOKEN.')
- self.test_channel = self.config.get('Slack', 'test-channel')
+ self.test_channel = self.config.get('Slack', 'test-channel')
? +++++
+ self.test_channel_name = self.config.get('Slack', 'test-channel-name')
def set_up_slack(self):
self.slack = slack.Slack(self.access_token)
|
f62ccee6bffa4dff9047a2f4b7499412dd3e2fb1
|
tomviz/python/SwapAxes.py
|
tomviz/python/SwapAxes.py
|
def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
data_py = dataset.active_scalars
dataset.active_scalars = data_py.swapaxes(axis1, axis2)
|
def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
import numpy as np
data_py = dataset.active_scalars
swapped = data_py.swapaxes(axis1, axis2)
dataset.active_scalars = np.asfortranarray(swapped)
|
Convert array back to fortran before setting
|
Convert array back to fortran before setting
Unfortunately, it looks like numpy.ndarray.swapaxes converts
the ordering from Fortran to C. When this happens, a warning
message will be printed to the console later that a conversion to
Fortran ordering is required.
Instead of printing the warning, just convert it back to Fortran
ordering ourselves. We already know that this operator unfortunately
converts the ordering to C.
Signed-off-by: Patrick Avery <[email protected]>
|
Python
|
bsd-3-clause
|
OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz
|
def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
+ import numpy as np
+
data_py = dataset.active_scalars
- dataset.active_scalars = data_py.swapaxes(axis1, axis2)
+ swapped = data_py.swapaxes(axis1, axis2)
+ dataset.active_scalars = np.asfortranarray(swapped)
|
Convert array back to fortran before setting
|
## Code Before:
def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
data_py = dataset.active_scalars
dataset.active_scalars = data_py.swapaxes(axis1, axis2)
## Instruction:
Convert array back to fortran before setting
## Code After:
def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
import numpy as np
data_py = dataset.active_scalars
swapped = data_py.swapaxes(axis1, axis2)
dataset.active_scalars = np.asfortranarray(swapped)
|
def transform(dataset, axis1, axis2):
"""Swap two axes in a dataset"""
+ import numpy as np
+
data_py = dataset.active_scalars
- dataset.active_scalars = data_py.swapaxes(axis1, axis2)
+ swapped = data_py.swapaxes(axis1, axis2)
+ dataset.active_scalars = np.asfortranarray(swapped)
|
658f0f6825b4f4a226349fcee63a0c5fbbd5ba9e
|
webapp/cached.py
|
webapp/cached.py
|
from datetime import datetime, timedelta
import os
class cached(object):
def __init__(self, *args, **kwargs):
self.cached_function_responses = {}
self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE'])))
def __call__(self, func):
def inner(*args, **kwargs):
param = args[0]
if len(args) > 1:
param = args[1]
max_age = kwargs.get('max_age', self.default_max_age)
if func not in self.cached_function_responses:
self.cached_function_responses[func] = {}
if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age):
if 'max_age' in kwargs:
del kwargs['max_age']
res = func(*args, **kwargs)
self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()}
return self.cached_function_responses[func][param]['data']
return inner
|
from datetime import datetime, timedelta
import os
class cached(object):
def __init__(self, *args, **kwargs):
self.cached_function_responses = {}
self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE'])))
def __call__(self, func):
def inner(*args, **kwargs):
param = args[1] if len(args) > 1 else args[0]
max_age = kwargs.get('max_age', self.default_max_age)
if func not in self.cached_function_responses:
self.cached_function_responses[func] = {}
if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age):
if 'max_age' in kwargs:
del kwargs['max_age']
res = func(*args, **kwargs)
self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()}
return self.cached_function_responses[func][param]['data']
return inner
|
Use ternary operator for arg selection.
|
Use ternary operator for arg selection.
|
Python
|
mit
|
cheddartv/stockstream.live,cheddartv/stockstream.live
|
from datetime import datetime, timedelta
import os
class cached(object):
def __init__(self, *args, **kwargs):
self.cached_function_responses = {}
self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE'])))
def __call__(self, func):
def inner(*args, **kwargs):
+ param = args[1] if len(args) > 1 else args[0]
- param = args[0]
- if len(args) > 1:
- param = args[1]
max_age = kwargs.get('max_age', self.default_max_age)
if func not in self.cached_function_responses:
self.cached_function_responses[func] = {}
if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age):
if 'max_age' in kwargs:
del kwargs['max_age']
res = func(*args, **kwargs)
self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()}
return self.cached_function_responses[func][param]['data']
return inner
|
Use ternary operator for arg selection.
|
## Code Before:
from datetime import datetime, timedelta
import os
class cached(object):
def __init__(self, *args, **kwargs):
self.cached_function_responses = {}
self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE'])))
def __call__(self, func):
def inner(*args, **kwargs):
param = args[0]
if len(args) > 1:
param = args[1]
max_age = kwargs.get('max_age', self.default_max_age)
if func not in self.cached_function_responses:
self.cached_function_responses[func] = {}
if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age):
if 'max_age' in kwargs:
del kwargs['max_age']
res = func(*args, **kwargs)
self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()}
return self.cached_function_responses[func][param]['data']
return inner
## Instruction:
Use ternary operator for arg selection.
## Code After:
from datetime import datetime, timedelta
import os
class cached(object):
def __init__(self, *args, **kwargs):
self.cached_function_responses = {}
self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE'])))
def __call__(self, func):
def inner(*args, **kwargs):
param = args[1] if len(args) > 1 else args[0]
max_age = kwargs.get('max_age', self.default_max_age)
if func not in self.cached_function_responses:
self.cached_function_responses[func] = {}
if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age):
if 'max_age' in kwargs:
del kwargs['max_age']
res = func(*args, **kwargs)
self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()}
return self.cached_function_responses[func][param]['data']
return inner
|
from datetime import datetime, timedelta
import os
class cached(object):
def __init__(self, *args, **kwargs):
self.cached_function_responses = {}
self.default_max_age = kwargs.get("default_cache_max_age", timedelta(seconds=int(os.environ['CACHE_AGE'])))
def __call__(self, func):
def inner(*args, **kwargs):
+ param = args[1] if len(args) > 1 else args[0]
- param = args[0]
- if len(args) > 1:
- param = args[1]
max_age = kwargs.get('max_age', self.default_max_age)
if func not in self.cached_function_responses:
self.cached_function_responses[func] = {}
if not max_age or param not in self.cached_function_responses[func] or (datetime.now() - self.cached_function_responses[func][param]['fetch_time'] > max_age):
if 'max_age' in kwargs:
del kwargs['max_age']
res = func(*args, **kwargs)
self.cached_function_responses[func][param] = {'data': res, 'fetch_time': datetime.now()}
return self.cached_function_responses[func][param]['data']
return inner
|
b07d74f99338165f8bb83ac0599452b021b96a8f
|
django_boolean_sum.py
|
django_boolean_sum.py
|
from django.conf import settings
from django.db.models.aggregates import Sum
from django.db.models.sql.aggregates import Sum as BaseSQLSum
class SQLSum(BaseSQLSum):
@property
def sql_template(self):
if settings.DATABASES['default']['ENGINE'] == \
'django.db.backends.postgresql_psycopg2':
return '%(function)s(%(field)s::int)'
return '%(function)s(%(field)s)'
class BooleanSum(Sum):
function = None
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLSum(col, source=source, is_summary=is_summary,
**self.extra)
query.aggregates[alias] = aggregate
|
from django.conf import settings
from django.db.models.aggregates import Sum
class SQLSum(Sum):
@property
def sql_template(self):
if settings.DATABASES['default']['ENGINE'] == \
'django.db.backends.postgresql_psycopg2':
return '%(function)s(%(field)s::int)'
return '%(function)s(%(field)s)'
class BooleanSum(Sum):
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLSum(col, source=source, is_summary=is_summary,
**self.extra)
query.aggregates[alias] = aggregate
|
Add support for Django 1.10+
|
Add support for Django 1.10+
|
Python
|
bsd-2-clause
|
Mibou/django-boolean-sum
|
from django.conf import settings
from django.db.models.aggregates import Sum
- from django.db.models.sql.aggregates import Sum as BaseSQLSum
- class SQLSum(BaseSQLSum):
+ class SQLSum(Sum):
@property
def sql_template(self):
if settings.DATABASES['default']['ENGINE'] == \
'django.db.backends.postgresql_psycopg2':
return '%(function)s(%(field)s::int)'
return '%(function)s(%(field)s)'
class BooleanSum(Sum):
- function = None
-
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLSum(col, source=source, is_summary=is_summary,
**self.extra)
query.aggregates[alias] = aggregate
|
Add support for Django 1.10+
|
## Code Before:
from django.conf import settings
from django.db.models.aggregates import Sum
from django.db.models.sql.aggregates import Sum as BaseSQLSum
class SQLSum(BaseSQLSum):
@property
def sql_template(self):
if settings.DATABASES['default']['ENGINE'] == \
'django.db.backends.postgresql_psycopg2':
return '%(function)s(%(field)s::int)'
return '%(function)s(%(field)s)'
class BooleanSum(Sum):
function = None
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLSum(col, source=source, is_summary=is_summary,
**self.extra)
query.aggregates[alias] = aggregate
## Instruction:
Add support for Django 1.10+
## Code After:
from django.conf import settings
from django.db.models.aggregates import Sum
class SQLSum(Sum):
@property
def sql_template(self):
if settings.DATABASES['default']['ENGINE'] == \
'django.db.backends.postgresql_psycopg2':
return '%(function)s(%(field)s::int)'
return '%(function)s(%(field)s)'
class BooleanSum(Sum):
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLSum(col, source=source, is_summary=is_summary,
**self.extra)
query.aggregates[alias] = aggregate
|
from django.conf import settings
from django.db.models.aggregates import Sum
- from django.db.models.sql.aggregates import Sum as BaseSQLSum
- class SQLSum(BaseSQLSum):
? -------
+ class SQLSum(Sum):
@property
def sql_template(self):
if settings.DATABASES['default']['ENGINE'] == \
'django.db.backends.postgresql_psycopg2':
return '%(function)s(%(field)s::int)'
return '%(function)s(%(field)s)'
class BooleanSum(Sum):
- function = None
-
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLSum(col, source=source, is_summary=is_summary,
**self.extra)
query.aggregates[alias] = aggregate
|
efed9e50dccea80cb536f106044265f8f1e2a32b
|
models.py
|
models.py
|
import peewee
db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres')
class IBModel(peewee.Model):
class Meta:
database = db
class User(IBModel):
user_id = peewee.CharField(max_length=128, primary_key=True)
auth_token = peewee.TextField()
class Module(IBModel):
module_id = peewee.TextField()
module_code = peewee.CharField(max_length=16)
acad_year = peewee.CharField(max_length=16)
semester = peewee.IntegerField()
class Meta:
primary_key = peewee.CompositeKey('module_code', 'acad_year', 'semester')
def setup_database():
db.connect()
try:
db.create_tables([User, Module])
except peewee.OperationalError as e:
print(e)
|
import os
import peewee
class IBModel(peewee.Model):
class Meta:
database = db
class User(IBModel):
user_id = peewee.CharField(max_length=128, primary_key=True)
auth_token = peewee.TextField()
class Module(IBModel):
module_id = peewee.TextField()
module_code = peewee.CharField(max_length=16)
acad_year = peewee.CharField(max_length=16)
semester = peewee.IntegerField()
class Meta:
primary_key = peewee.CompositeKey('module_code', 'acad_year', 'semester')
def setup_database():
db.connect()
try:
db.create_tables([User, Module])
except peewee.OperationalError as e:
print(e)
if __name__ == '__main__':
if 'HEROKU' in os.environ:
import urlparse
urlparse.uses_netloc.append('postgres')
url = urlparse.urlparse(os.environ["DATABASE_URL"])
db = PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port)
else:
db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres')
setup_database()
|
Set up database according to environment
|
Set up database according to environment
|
Python
|
mit
|
karen/ivle-bot,karenang/ivle-bot
|
+ import os
import peewee
-
- db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres')
class IBModel(peewee.Model):
class Meta:
database = db
class User(IBModel):
user_id = peewee.CharField(max_length=128, primary_key=True)
auth_token = peewee.TextField()
class Module(IBModel):
module_id = peewee.TextField()
module_code = peewee.CharField(max_length=16)
acad_year = peewee.CharField(max_length=16)
semester = peewee.IntegerField()
class Meta:
primary_key = peewee.CompositeKey('module_code', 'acad_year', 'semester')
def setup_database():
db.connect()
try:
db.create_tables([User, Module])
except peewee.OperationalError as e:
print(e)
+ if __name__ == '__main__':
+ if 'HEROKU' in os.environ:
+ import urlparse
+ urlparse.uses_netloc.append('postgres')
+ url = urlparse.urlparse(os.environ["DATABASE_URL"])
+ db = PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port)
+ else:
+ db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres')
+ setup_database()
|
Set up database according to environment
|
## Code Before:
import peewee
db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres')
class IBModel(peewee.Model):
class Meta:
database = db
class User(IBModel):
user_id = peewee.CharField(max_length=128, primary_key=True)
auth_token = peewee.TextField()
class Module(IBModel):
module_id = peewee.TextField()
module_code = peewee.CharField(max_length=16)
acad_year = peewee.CharField(max_length=16)
semester = peewee.IntegerField()
class Meta:
primary_key = peewee.CompositeKey('module_code', 'acad_year', 'semester')
def setup_database():
db.connect()
try:
db.create_tables([User, Module])
except peewee.OperationalError as e:
print(e)
## Instruction:
Set up database according to environment
## Code After:
import os
import peewee
class IBModel(peewee.Model):
class Meta:
database = db
class User(IBModel):
user_id = peewee.CharField(max_length=128, primary_key=True)
auth_token = peewee.TextField()
class Module(IBModel):
module_id = peewee.TextField()
module_code = peewee.CharField(max_length=16)
acad_year = peewee.CharField(max_length=16)
semester = peewee.IntegerField()
class Meta:
primary_key = peewee.CompositeKey('module_code', 'acad_year', 'semester')
def setup_database():
db.connect()
try:
db.create_tables([User, Module])
except peewee.OperationalError as e:
print(e)
if __name__ == '__main__':
if 'HEROKU' in os.environ:
import urlparse
urlparse.uses_netloc.append('postgres')
url = urlparse.urlparse(os.environ["DATABASE_URL"])
db = PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port)
else:
db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres')
setup_database()
|
+ import os
import peewee
-
- db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres')
class IBModel(peewee.Model):
class Meta:
database = db
class User(IBModel):
user_id = peewee.CharField(max_length=128, primary_key=True)
auth_token = peewee.TextField()
class Module(IBModel):
module_id = peewee.TextField()
module_code = peewee.CharField(max_length=16)
acad_year = peewee.CharField(max_length=16)
semester = peewee.IntegerField()
class Meta:
primary_key = peewee.CompositeKey('module_code', 'acad_year', 'semester')
def setup_database():
db.connect()
try:
db.create_tables([User, Module])
except peewee.OperationalError as e:
print(e)
+ if __name__ == '__main__':
+ if 'HEROKU' in os.environ:
+ import urlparse
+ urlparse.uses_netloc.append('postgres')
+ url = urlparse.urlparse(os.environ["DATABASE_URL"])
+ db = PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port)
+ else:
+ db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres')
+ setup_database()
|
7b7f626c54694ec72166094ad568254ecfcdce8a
|
strictyaml/__init__.py
|
strictyaml/__init__.py
|
from strictyaml.parser import load
# Validators
from strictyaml.validators import Optional
from strictyaml.validators import Validator
from strictyaml.validators import OrValidator
from strictyaml.validators import Any
from strictyaml.validators import Scalar
from strictyaml.validators import Enum
from strictyaml.validators import Str
from strictyaml.validators import Int
from strictyaml.validators import Bool
from strictyaml.validators import Float
from strictyaml.validators import Decimal
from strictyaml.validators import Map
from strictyaml.validators import MapPattern
from strictyaml.validators import Seq
from strictyaml.validators import UniqueSeq
# Exceptions
from strictyaml.exceptions import StrictYAMLError
# Validaton
from strictyaml.exceptions import YAMLValidationError
# Disallowed token exceptions
from strictyaml.exceptions import DisallowedToken
from strictyaml.exceptions import TagTokenDisallowed
from strictyaml.exceptions import FlowMappingDisallowed
from strictyaml.exceptions import AnchorTokenDisallowed
|
from strictyaml.parser import load
# Validators
from strictyaml.validators import Optional
from strictyaml.validators import Validator
from strictyaml.validators import OrValidator
from strictyaml.validators import Any
from strictyaml.validators import Scalar
from strictyaml.validators import Enum
from strictyaml.validators import Str
from strictyaml.validators import Int
from strictyaml.validators import Bool
from strictyaml.validators import Float
from strictyaml.validators import Decimal
from strictyaml.validators import Map
from strictyaml.validators import MapPattern
from strictyaml.validators import Seq
from strictyaml.validators import UniqueSeq
# Exceptions
from strictyaml.exceptions import YAMLError
from strictyaml.exceptions import StrictYAMLError
from strictyaml.exceptions import YAMLValidationError
# Disallowed token exceptions
from strictyaml.exceptions import DisallowedToken
from strictyaml.exceptions import TagTokenDisallowed
from strictyaml.exceptions import FlowMappingDisallowed
from strictyaml.exceptions import AnchorTokenDisallowed
|
REFACTOR : Import YAMLError so it is usable as a generic exception.
|
REFACTOR : Import YAMLError so it is usable as a generic exception.
|
Python
|
mit
|
crdoconnor/strictyaml,crdoconnor/strictyaml
|
from strictyaml.parser import load
# Validators
from strictyaml.validators import Optional
from strictyaml.validators import Validator
from strictyaml.validators import OrValidator
from strictyaml.validators import Any
from strictyaml.validators import Scalar
from strictyaml.validators import Enum
from strictyaml.validators import Str
from strictyaml.validators import Int
from strictyaml.validators import Bool
from strictyaml.validators import Float
from strictyaml.validators import Decimal
from strictyaml.validators import Map
from strictyaml.validators import MapPattern
from strictyaml.validators import Seq
from strictyaml.validators import UniqueSeq
# Exceptions
+ from strictyaml.exceptions import YAMLError
from strictyaml.exceptions import StrictYAMLError
-
- # Validaton
from strictyaml.exceptions import YAMLValidationError
# Disallowed token exceptions
from strictyaml.exceptions import DisallowedToken
from strictyaml.exceptions import TagTokenDisallowed
from strictyaml.exceptions import FlowMappingDisallowed
from strictyaml.exceptions import AnchorTokenDisallowed
|
REFACTOR : Import YAMLError so it is usable as a generic exception.
|
## Code Before:
from strictyaml.parser import load
# Validators
from strictyaml.validators import Optional
from strictyaml.validators import Validator
from strictyaml.validators import OrValidator
from strictyaml.validators import Any
from strictyaml.validators import Scalar
from strictyaml.validators import Enum
from strictyaml.validators import Str
from strictyaml.validators import Int
from strictyaml.validators import Bool
from strictyaml.validators import Float
from strictyaml.validators import Decimal
from strictyaml.validators import Map
from strictyaml.validators import MapPattern
from strictyaml.validators import Seq
from strictyaml.validators import UniqueSeq
# Exceptions
from strictyaml.exceptions import StrictYAMLError
# Validaton
from strictyaml.exceptions import YAMLValidationError
# Disallowed token exceptions
from strictyaml.exceptions import DisallowedToken
from strictyaml.exceptions import TagTokenDisallowed
from strictyaml.exceptions import FlowMappingDisallowed
from strictyaml.exceptions import AnchorTokenDisallowed
## Instruction:
REFACTOR : Import YAMLError so it is usable as a generic exception.
## Code After:
from strictyaml.parser import load
# Validators
from strictyaml.validators import Optional
from strictyaml.validators import Validator
from strictyaml.validators import OrValidator
from strictyaml.validators import Any
from strictyaml.validators import Scalar
from strictyaml.validators import Enum
from strictyaml.validators import Str
from strictyaml.validators import Int
from strictyaml.validators import Bool
from strictyaml.validators import Float
from strictyaml.validators import Decimal
from strictyaml.validators import Map
from strictyaml.validators import MapPattern
from strictyaml.validators import Seq
from strictyaml.validators import UniqueSeq
# Exceptions
from strictyaml.exceptions import YAMLError
from strictyaml.exceptions import StrictYAMLError
from strictyaml.exceptions import YAMLValidationError
# Disallowed token exceptions
from strictyaml.exceptions import DisallowedToken
from strictyaml.exceptions import TagTokenDisallowed
from strictyaml.exceptions import FlowMappingDisallowed
from strictyaml.exceptions import AnchorTokenDisallowed
|
from strictyaml.parser import load
# Validators
from strictyaml.validators import Optional
from strictyaml.validators import Validator
from strictyaml.validators import OrValidator
from strictyaml.validators import Any
from strictyaml.validators import Scalar
from strictyaml.validators import Enum
from strictyaml.validators import Str
from strictyaml.validators import Int
from strictyaml.validators import Bool
from strictyaml.validators import Float
from strictyaml.validators import Decimal
from strictyaml.validators import Map
from strictyaml.validators import MapPattern
from strictyaml.validators import Seq
from strictyaml.validators import UniqueSeq
# Exceptions
+ from strictyaml.exceptions import YAMLError
from strictyaml.exceptions import StrictYAMLError
-
- # Validaton
from strictyaml.exceptions import YAMLValidationError
# Disallowed token exceptions
from strictyaml.exceptions import DisallowedToken
from strictyaml.exceptions import TagTokenDisallowed
from strictyaml.exceptions import FlowMappingDisallowed
from strictyaml.exceptions import AnchorTokenDisallowed
|
c530ea901c374fef97390260e66492f37fc90a3f
|
setman/__init__.py
|
setman/__init__.py
|
from setman.lazy import LazySettings
__all__ = ('get_version', 'settings')
VERSION = (0, 1, 'beta')
settings = LazySettings()
def get_version(version=None):
"""
Return setman version number in human readable form.
You could call this function without args and in this case value from
``setman.VERSION`` would be used.
"""
version = version or VERSION
if len(version) > 2 and version[2] is not None:
if isinstance(version[2], int):
return '%d.%d.%d' % version
return '%d.%d-%s' % version
return '%d.%d' % version[:2]
|
try:
from setman.lazy import LazySettings
except ImportError:
# Do not care about "Settings cannot be imported, because environment
# variable DJANGO_SETTINGS_MODULE is undefined." errors
LazySettings = type('LazySettings', (object, ), {})
__all__ = ('get_version', 'settings')
VERSION = (0, 1, 'beta')
settings = LazySettings()
def get_version(version=None):
"""
Return setman version number in human readable form.
You could call this function without args and in this case value from
``setman.VERSION`` would be used.
"""
version = version or VERSION
if len(version) > 2 and version[2] is not None:
if isinstance(version[2], int):
return '%d.%d.%d' % version
return '%d.%d-%s' % version
return '%d.%d' % version[:2]
|
Fix installing ``django-setman`` via PIP.
|
Fix installing ``django-setman`` via PIP.
|
Python
|
bsd-3-clause
|
playpauseandstop/setman,owais/django-setman,owais/django-setman
|
+ try:
- from setman.lazy import LazySettings
+ from setman.lazy import LazySettings
+ except ImportError:
+ # Do not care about "Settings cannot be imported, because environment
+ # variable DJANGO_SETTINGS_MODULE is undefined." errors
+ LazySettings = type('LazySettings', (object, ), {})
__all__ = ('get_version', 'settings')
VERSION = (0, 1, 'beta')
settings = LazySettings()
def get_version(version=None):
"""
Return setman version number in human readable form.
You could call this function without args and in this case value from
``setman.VERSION`` would be used.
"""
version = version or VERSION
if len(version) > 2 and version[2] is not None:
if isinstance(version[2], int):
return '%d.%d.%d' % version
return '%d.%d-%s' % version
return '%d.%d' % version[:2]
|
Fix installing ``django-setman`` via PIP.
|
## Code Before:
from setman.lazy import LazySettings
__all__ = ('get_version', 'settings')
VERSION = (0, 1, 'beta')
settings = LazySettings()
def get_version(version=None):
"""
Return setman version number in human readable form.
You could call this function without args and in this case value from
``setman.VERSION`` would be used.
"""
version = version or VERSION
if len(version) > 2 and version[2] is not None:
if isinstance(version[2], int):
return '%d.%d.%d' % version
return '%d.%d-%s' % version
return '%d.%d' % version[:2]
## Instruction:
Fix installing ``django-setman`` via PIP.
## Code After:
try:
from setman.lazy import LazySettings
except ImportError:
# Do not care about "Settings cannot be imported, because environment
# variable DJANGO_SETTINGS_MODULE is undefined." errors
LazySettings = type('LazySettings', (object, ), {})
__all__ = ('get_version', 'settings')
VERSION = (0, 1, 'beta')
settings = LazySettings()
def get_version(version=None):
"""
Return setman version number in human readable form.
You could call this function without args and in this case value from
``setman.VERSION`` would be used.
"""
version = version or VERSION
if len(version) > 2 and version[2] is not None:
if isinstance(version[2], int):
return '%d.%d.%d' % version
return '%d.%d-%s' % version
return '%d.%d' % version[:2]
|
+ try:
- from setman.lazy import LazySettings
+ from setman.lazy import LazySettings
? ++++
+ except ImportError:
+ # Do not care about "Settings cannot be imported, because environment
+ # variable DJANGO_SETTINGS_MODULE is undefined." errors
+ LazySettings = type('LazySettings', (object, ), {})
__all__ = ('get_version', 'settings')
VERSION = (0, 1, 'beta')
settings = LazySettings()
def get_version(version=None):
"""
Return setman version number in human readable form.
You could call this function without args and in this case value from
``setman.VERSION`` would be used.
"""
version = version or VERSION
if len(version) > 2 and version[2] is not None:
if isinstance(version[2], int):
return '%d.%d.%d' % version
return '%d.%d-%s' % version
return '%d.%d' % version[:2]
|
f5ac1fa0738384fada4abb979ba25dddecc56372
|
compose/utils.py
|
compose/utils.py
|
import json
import hashlib
def json_hash(obj):
dump = json.dumps(obj, sort_keys=True)
h = hashlib.sha256()
h.update(dump)
return h.hexdigest()
|
import json
import hashlib
def json_hash(obj):
dump = json.dumps(obj, sort_keys=True, separators=(',', ':'))
h = hashlib.sha256()
h.update(dump)
return h.hexdigest()
|
Remove whitespace from json hash
|
Remove whitespace from json hash
Reasoning:
https://github.com/aanand/fig/commit/e5d8447f063498164f12567554a2eec16b4a3c88#commitcomment-11243708
Signed-off-by: Ben Firshman <[email protected]>
|
Python
|
apache-2.0
|
alunduil/fig,danix800/docker.github.io,joaofnfernandes/docker.github.io,tiry/compose,mrfuxi/compose,mnowster/compose,talolard/compose,joaofnfernandes/docker.github.io,JimGalasyn/docker.github.io,bdwill/docker.github.io,jrabbit/compose,uvgroovy/compose,rgbkrk/compose,Chouser/compose,anweiss/docker.github.io,shin-/docker.github.io,BSWANG/denverdino.github.io,danix800/docker.github.io,Yelp/docker-compose,albers/compose,mindaugasrukas/compose,Katlean/fig,LuisBosquez/docker.github.io,troy0820/docker.github.io,mnuessler/compose,saada/compose,viranch/compose,runcom/compose,bbirand/compose,josephpage/compose,andrewgee/compose,aanand/fig,mdaue/compose,xydinesh/compose,docker-zh/docker.github.io,amitsaha/compose,marcusmartins/compose,mosquito/docker-compose,denverdino/docker.github.io,shin-/compose,jzwlqx/denverdino.github.io,sebglazebrook/compose,dopry/compose,VinceBarresi/compose,denverdino/denverdino.github.io,MSakamaki/compose,Yelp/docker-compose,sanscontext/docker.github.io,tpounds/compose,tiry/compose,philwrenn/compose,joaofnfernandes/docker.github.io,simonista/compose,tpounds/compose,runcom/compose,d2bit/compose,ekristen/compose,dockerhn/compose,genki/compose,ralphtheninja/compose,jonaseck2/compose,charleswhchan/compose,thaJeztah/compose,thaJeztah/docker.github.io,TheDataShed/compose,bobphill/compose,shin-/docker.github.io,browning/compose,thaJeztah/compose,dopry/compose,troy0820/docker.github.io,bbirand/compose,alexandrev/compose,danix800/docker.github.io,jessekl/compose,mchasal/compose,marcusmartins/compose,phiroict/docker,shubheksha/docker.github.io,docker/docker.github.io,phiroict/docker,michael-k/docker-compose,phiroict/docker,shin-/docker.github.io,iamluc/compose,dockerhn/compose,johnstep/docker.github.io,BSWANG/denverdino.github.io,cclauss/compose,artemkaint/compose,brunocascio/compose,schmunk42/compose,glogiotatidis/compose,unodba/compose,aduermael/docker.github.io,mindaugasrukas/compose,bsmr-docker/compose,iamluc/compose,denverdino/denverdino.github.io,JimGalasyn/docker.github.io,aduermael/docker.github.io,anweiss/docker.github.io,joeuo/docker.github.io,LuisBosquez/docker.github.io,shubheksha/docker.github.io,swoopla/compose,Chouser/compose,phiroict/docker,jzwlqx/denverdino.github.io,ggtools/compose,LuisBosquez/docker.github.io,sdurrheimer/compose,denverdino/denverdino.github.io,bsmr-docker/compose,jzwlqx/denverdino.github.io,goloveychuk/compose,unodba/compose,noironetworks/compose,KalleDK/compose,benhamill/compose,jgrowl/compose,twitherspoon/compose,londoncalling/docker.github.io,gdevillele/docker.github.io,BSWANG/denverdino.github.io,jonaseck2/compose,goloveychuk/compose,artemkaint/compose,browning/compose,danix800/docker.github.io,joeuo/docker.github.io,londoncalling/docker.github.io,rillig/docker.github.io,anweiss/docker.github.io,docker-zh/docker.github.io,au-phiware/compose,johnstep/docker.github.io,johnstep/docker.github.io,mark-adams/compose,denverdino/compose,gdevillele/docker.github.io,rillig/docker.github.io,KevinGreene/compose,johnstep/docker.github.io,twitherspoon/compose,jiekechoo/compose,ZJaffee/compose,amitsaha/compose,anweiss/docker.github.io,bfirsh/fig,rillig/docker.github.io,thieman/compose,mohitsoni/compose,menglingwei/denverdino.github.io,jessekl/compose,docker-zh/docker.github.io,alexisbellido/docker.github.io,philwrenn/compose,mosquito/docker-compose,docker-zh/docker.github.io,RobertNorthard/compose,funkyfuture/docker-compose,pspierce/compose,calou/compose,shubheksha/docker.github.io,johnstep/docker.github.io,DoubleMalt/compose,mbailey/compose,docker/docker.github.io,gdevillele/docker.github.io,JimGalasyn/docker.github.io,zhangspook/compose,andrewgee/compose,swoopla/compose,rstacruz/compose,joaofnfernandes/docker.github.io,moxiegirl/compose,brunocascio/compose,KevinGreene/compose,jzwlqx/denverdino.github.io,JimGalasyn/docker.github.io,shin-/docker.github.io,dilgerma/compose,sanscontext/docker.github.io,bdwill/docker.github.io,denverdino/docker.github.io,denverdino/denverdino.github.io,kojiromike/compose,au-phiware/compose,mark-adams/compose,thieman/compose,londoncalling/docker.github.io,thaJeztah/docker.github.io,docker/docker.github.io,anweiss/docker.github.io,saada/compose,alexandrev/compose,rstacruz/compose,docker/docker.github.io,mrfuxi/compose,vdemeester/compose,glogiotatidis/compose,lukemarsden/compose,troy0820/docker.github.io,gtrdotmcs/compose,feelobot/compose,vdemeester/compose,nhumrich/compose,ekristen/compose,troy0820/docker.github.io,mbailey/compose,vlajos/compose,KalleDK/compose,denverdino/compose,benhamill/compose,feelobot/compose,jorgeLuizChaves/compose,rgbkrk/compose,moxiegirl/compose,Dakno/compose,aanand/fig,shubheksha/docker.github.io,joeuo/docker.github.io,schmunk42/compose,lukemarsden/compose,xydinesh/compose,qzio/compose,denverdino/denverdino.github.io,DoubleMalt/compose,ionrock/compose,VinceBarresi/compose,tangkun75/compose,screwgoth/compose,sanscontext/docker.github.io,charleswhchan/compose,jeanpralo/compose,lmesz/compose,thaJeztah/docker.github.io,menglingwei/denverdino.github.io,sebglazebrook/compose,sanscontext/docker.github.io,uvgroovy/compose,MSakamaki/compose,mnuessler/compose,joeuo/docker.github.io,denverdino/docker.github.io,dnephin/compose,kojiromike/compose,bdwill/docker.github.io,aduermael/docker.github.io,gdevillele/docker.github.io,bfirsh/fig,ph-One/compose,londoncalling/docker.github.io,hoogenm/compose,mchasal/compose,ggtools/compose,dbdd4us/compose,josephpage/compose,funkyfuture/docker-compose,talolard/compose,bobphill/compose,pspierce/compose,JimGalasyn/docker.github.io,menglingwei/denverdino.github.io,jgrowl/compose,cgvarela/compose,denverdino/docker.github.io,mdaue/compose,phiroict/docker,rillig/docker.github.io,mohitsoni/compose,LuisBosquez/docker.github.io,zhangspook/compose,tangkun75/compose,jrabbit/compose,LuisBosquez/docker.github.io,lmesz/compose,TomasTomecek/compose,shin-/compose,thaJeztah/docker.github.io,dnephin/compose,ionrock/compose,kikkomep/compose,bdwill/docker.github.io,docker-zh/docker.github.io,prologic/compose,vlajos/compose,dbdd4us/compose,noironetworks/compose,screwgoth/compose,menglingwei/denverdino.github.io,kikkomep/compose,cclauss/compose,viranch/compose,denverdino/docker.github.io,ZJaffee/compose,simonista/compose,alexisbellido/docker.github.io,jeanpralo/compose,joeuo/docker.github.io,qzio/compose,alunduil/fig,nhumrich/compose,cgvarela/compose,aduermael/docker.github.io,ChrisChinchilla/compose,thaJeztah/docker.github.io,RobertNorthard/compose,docker/docker.github.io,shubheksha/docker.github.io,TheDataShed/compose,gtrdotmcs/compose,londoncalling/docker.github.io,joaofnfernandes/docker.github.io,BSWANG/denverdino.github.io,dilgerma/compose,GM-Alex/compose,bdwill/docker.github.io,TomasTomecek/compose,sanscontext/docker.github.io,jzwlqx/denverdino.github.io,mnowster/compose,calou/compose,menglingwei/denverdino.github.io,genki/compose,albers/compose,gdevillele/docker.github.io,alexisbellido/docker.github.io,alexisbellido/docker.github.io,michael-k/docker-compose,ChrisChinchilla/compose,GM-Alex/compose,alexisbellido/docker.github.io,prologic/compose,ralphtheninja/compose,Dakno/compose,jorgeLuizChaves/compose,sdurrheimer/compose,shin-/docker.github.io,ph-One/compose,jiekechoo/compose,BSWANG/denverdino.github.io,hoogenm/compose,Katlean/fig,j-fuentes/compose,j-fuentes/compose,d2bit/compose
|
import json
import hashlib
def json_hash(obj):
- dump = json.dumps(obj, sort_keys=True)
+ dump = json.dumps(obj, sort_keys=True, separators=(',', ':'))
h = hashlib.sha256()
h.update(dump)
return h.hexdigest()
|
Remove whitespace from json hash
|
## Code Before:
import json
import hashlib
def json_hash(obj):
dump = json.dumps(obj, sort_keys=True)
h = hashlib.sha256()
h.update(dump)
return h.hexdigest()
## Instruction:
Remove whitespace from json hash
## Code After:
import json
import hashlib
def json_hash(obj):
dump = json.dumps(obj, sort_keys=True, separators=(',', ':'))
h = hashlib.sha256()
h.update(dump)
return h.hexdigest()
|
import json
import hashlib
def json_hash(obj):
- dump = json.dumps(obj, sort_keys=True)
+ dump = json.dumps(obj, sort_keys=True, separators=(',', ':'))
? ++++++++++++++++++++++ +
h = hashlib.sha256()
h.update(dump)
return h.hexdigest()
|
3cf942c5cf7f791cbbd04bf1d092c2c8061b69ac
|
prjxray/site_type.py
|
prjxray/site_type.py
|
""" Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
|
""" Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
INOUT = "INOUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
|
Add INOUT to direction enum.
|
prjxray: Add INOUT to direction enum.
INOUT is found on the PS7 interface on the Zynq.
Signed-off-by: Tim 'mithro' Ansell <[email protected]>
|
Python
|
isc
|
SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray
|
""" Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
+ INOUT = "INOUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
|
Add INOUT to direction enum.
|
## Code Before:
""" Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
## Instruction:
Add INOUT to direction enum.
## Code After:
""" Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
INOUT = "INOUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
|
""" Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
+ INOUT = "INOUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
|
6099451fe088fe74945bbeedeeee66896bd7ff3d
|
voctocore/lib/sources/__init__.py
|
voctocore/lib/sources/__init__.py
|
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
elif kind == 'test':
sources[name] = TestSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
log.warning('Unknown source kind "%s", defaulting to "tcp"', kind)
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
|
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
if kind != 'test':
log.warning('Unknown value "%s" in attribute "kind" in definition of source %s (see section [source.%s] in configuration). Falling back to kind "test".', kind, name, name)
sources[name] = TestSource(name, has_audio, has_video)
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
|
Use test sources as the default in configuration (and improve warning message, when falling back to)
|
Use test sources as the default in configuration (and improve warning message, when falling back to)
|
Python
|
mit
|
voc/voctomix,voc/voctomix
|
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
- elif kind == 'test':
- sources[name] = TestSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
- log.warning('Unknown source kind "%s", defaulting to "tcp"', kind)
+ if kind != 'test':
+ log.warning('Unknown value "%s" in attribute "kind" in definition of source %s (see section [source.%s] in configuration). Falling back to kind "test".', kind, name, name)
+ sources[name] = TestSource(name, has_audio, has_video)
+
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
|
Use test sources as the default in configuration (and improve warning message, when falling back to)
|
## Code Before:
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
elif kind == 'test':
sources[name] = TestSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
log.warning('Unknown source kind "%s", defaulting to "tcp"', kind)
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
## Instruction:
Use test sources as the default in configuration (and improve warning message, when falling back to)
## Code After:
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
if kind != 'test':
log.warning('Unknown value "%s" in attribute "kind" in definition of source %s (see section [source.%s] in configuration). Falling back to kind "test".', kind, name, name)
sources[name] = TestSource(name, has_audio, has_video)
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
|
import logging
from lib.config import Config
from lib.sources.decklinkavsource import DeckLinkAVSource
from lib.sources.imgvsource import ImgVSource
from lib.sources.tcpavsource import TCPAVSource
from lib.sources.testsource import TestSource
from lib.sources.videoloopsource import VideoLoopSource
log = logging.getLogger('AVSourceManager')
sources = {}
def spawn_source(name, port, has_audio=True, has_video=True,
force_num_streams=None):
kind = Config.getSourceKind(name)
if kind == 'img':
sources[name] = ImgVSource(name)
elif kind == 'decklink':
sources[name] = DeckLinkAVSource(name, has_audio, has_video)
- elif kind == 'test':
- sources[name] = TestSource(name, has_audio, has_video)
elif kind == 'videoloop':
sources[name] = VideoLoopSource(name)
elif kind == 'tcp':
sources[name] = TCPAVSource(name, port, has_audio, has_video,
force_num_streams)
else:
- log.warning('Unknown source kind "%s", defaulting to "tcp"', kind)
+ if kind != 'test':
+ log.warning('Unknown value "%s" in attribute "kind" in definition of source %s (see section [source.%s] in configuration). Falling back to kind "test".', kind, name, name)
+ sources[name] = TestSource(name, has_audio, has_video)
+
return sources[name]
def restart_source(name):
assert False, "restart_source() not implemented"
|
389ca2213c2ba3c86c783372e3e933a12f90506e
|
ckanext/requestdata/controllers/admin.py
|
ckanext/requestdata/controllers/admin.py
|
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class AdminController(BaseController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
|
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
from ckan.controllers.admin import AdminController
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class AdminController(AdminController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
|
Extend Admin instead of Base controller
|
Extend Admin instead of Base controller
|
Python
|
agpl-3.0
|
ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata,ViderumGlobal/ckanext-requestdata
|
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
+ from ckan.controllers.admin import AdminController
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
- class AdminController(BaseController):
+ class AdminController(AdminController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
|
Extend Admin instead of Base controller
|
## Code Before:
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class AdminController(BaseController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
## Instruction:
Extend Admin instead of Base controller
## Code After:
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
from ckan.controllers.admin import AdminController
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
class AdminController(AdminController):
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
|
from ckan.lib import base
from ckan import logic
from ckan.plugins import toolkit
+ from ckan.controllers.admin import AdminController
get_action = logic.get_action
NotFound = logic.NotFound
NotAuthorized = logic.NotAuthorized
redirect = base.redirect
abort = base.abort
BaseController = base.BaseController
- class AdminController(BaseController):
? ^^^^
+ class AdminController(AdminController):
? ^^^^^
def email(self):
'''Email template admin tab.
:param :
:type
'''
return toolkit.render('admin/email.html')
def requests_data(self):
'''
Return all of the data requests in admin panel
:return:
'''
return toolkit.render('admin/all_requests_data.html')
|
9d6c8eaa491d0988bf16633bbba9847350f57778
|
spacy/lang/norm_exceptions.py
|
spacy/lang/norm_exceptions.py
|
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
|
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
"‘‘": '"',
"’’": '"',
"?": "?",
"!": "!",
",": ",",
";": ";",
":": ":",
"。": ".",
"।": ".",
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
"——": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
|
Update base norm exceptions with more unicode characters
|
Update base norm exceptions with more unicode characters
e.g. unicode variations of punctuation used in Chinese
|
Python
|
mit
|
aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy
|
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
+ "‘‘": '"',
+ "’’": '"',
+ "?": "?",
+ "!": "!",
+ ",": ",",
+ ";": ";",
+ ":": ":",
+ "。": ".",
+ "।": ".",
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
+ "——": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
|
Update base norm exceptions with more unicode characters
|
## Code Before:
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
## Instruction:
Update base norm exceptions with more unicode characters
## Code After:
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
"‘‘": '"',
"’’": '"',
"?": "?",
"!": "!",
",": ",",
";": ";",
":": ":",
"。": ".",
"।": ".",
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
"——": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
|
from __future__ import unicode_literals
# These exceptions are used to add NORM values based on a token's ORTH value.
# Individual languages can also add their own exceptions and overwrite them -
# for example, British vs. American spelling in English.
# Norms are only set if no alternative is provided in the tokenizer exceptions.
# Note that this does not change any other token attributes. Its main purpose
# is to normalise the word representations so that equivalent tokens receive
# similar representations. For example: $ and € are very different, but they're
# both currency symbols. By normalising currency symbols to $, all symbols are
# seen as similar, no matter how common they are in the training data.
BASE_NORMS = {
"'s": "'s",
"'S": "'s",
"’s": "'s",
"’S": "'s",
"’": "'",
"‘": "'",
"´": "'",
"`": "'",
"”": '"',
"“": '"',
"''": '"',
"``": '"',
"´´": '"',
"„": '"',
"»": '"',
"«": '"',
+ "‘‘": '"',
+ "’’": '"',
+ "?": "?",
+ "!": "!",
+ ",": ",",
+ ";": ";",
+ ":": ":",
+ "。": ".",
+ "।": ".",
"…": "...",
"—": "-",
"–": "-",
"--": "-",
"---": "-",
+ "——": "-",
"€": "$",
"£": "$",
"¥": "$",
"฿": "$",
"US$": "$",
"C$": "$",
"A$": "$"
}
|
f367d3122084c85e11efeb20d560a856e9f24d0e
|
zuice/django.py
|
zuice/django.py
|
django = __import__("django.conf.urls.defaults", {})
from zuice import Injector
def _view_builder(bindings):
def view(request, view_class, **kwargs):
view_injector = Injector(bindings)
view = view_injector.get_from_type(view_class)
bindings_for_response = bindings.copy()
bindings_for_response.bind('request').to_instance(request)
for item in kwargs.iteritems():
bindings_for_response.bind_name(item[0]).to_instance(item[1])
response_injector = Injector(bindings_for_response)
response = response_injector.call(view.respond)
return response.render(request)
return view
def url_to_class_builder(bindings):
def url_to_class(regex, view_class, kwargs=None, name=None):
if kwargs is None:
kwargs = {}
kwargs['view_class'] = view_class
return django.conf.urls.defaults.url(regex, _view_builder(bindings), kwargs, name=name)
return url_to_class
|
django = __import__("django.conf.urls.defaults", {})
from zuice import Injector
def _view_builder(bindings):
def view(request, view_class, **kwargs):
view_injector = Injector(bindings)
view = view_injector.get_from_type(view_class)
bindings_for_response = bindings.copy()
bindings_for_response.bind('request').to_instance(request)
for item in kwargs.iteritems():
bindings_for_response.bind_name(item[0]).to_instance(item[1])
response_injector = Injector(bindings_for_response)
response = response_injector.call(view.respond)
return response.render(request)
return view
def url_to_class_builder(bindings):
view = _view_builder(bindings.copy())
def url_to_class(regex, view_class, kwargs=None, name=None):
if kwargs is None:
kwargs = {}
kwargs['view_class'] = view_class
return django.conf.urls.defaults.url(regex, view, kwargs, name=name)
return url_to_class
|
Refactor url_to_class_builder so that the view is only built once
|
Refactor url_to_class_builder so that the view is only built once
|
Python
|
bsd-2-clause
|
mwilliamson/zuice
|
django = __import__("django.conf.urls.defaults", {})
from zuice import Injector
def _view_builder(bindings):
def view(request, view_class, **kwargs):
view_injector = Injector(bindings)
view = view_injector.get_from_type(view_class)
bindings_for_response = bindings.copy()
bindings_for_response.bind('request').to_instance(request)
for item in kwargs.iteritems():
bindings_for_response.bind_name(item[0]).to_instance(item[1])
response_injector = Injector(bindings_for_response)
response = response_injector.call(view.respond)
return response.render(request)
return view
def url_to_class_builder(bindings):
+ view = _view_builder(bindings.copy())
def url_to_class(regex, view_class, kwargs=None, name=None):
if kwargs is None:
kwargs = {}
kwargs['view_class'] = view_class
- return django.conf.urls.defaults.url(regex, _view_builder(bindings), kwargs, name=name)
+ return django.conf.urls.defaults.url(regex, view, kwargs, name=name)
return url_to_class
|
Refactor url_to_class_builder so that the view is only built once
|
## Code Before:
django = __import__("django.conf.urls.defaults", {})
from zuice import Injector
def _view_builder(bindings):
def view(request, view_class, **kwargs):
view_injector = Injector(bindings)
view = view_injector.get_from_type(view_class)
bindings_for_response = bindings.copy()
bindings_for_response.bind('request').to_instance(request)
for item in kwargs.iteritems():
bindings_for_response.bind_name(item[0]).to_instance(item[1])
response_injector = Injector(bindings_for_response)
response = response_injector.call(view.respond)
return response.render(request)
return view
def url_to_class_builder(bindings):
def url_to_class(regex, view_class, kwargs=None, name=None):
if kwargs is None:
kwargs = {}
kwargs['view_class'] = view_class
return django.conf.urls.defaults.url(regex, _view_builder(bindings), kwargs, name=name)
return url_to_class
## Instruction:
Refactor url_to_class_builder so that the view is only built once
## Code After:
django = __import__("django.conf.urls.defaults", {})
from zuice import Injector
def _view_builder(bindings):
def view(request, view_class, **kwargs):
view_injector = Injector(bindings)
view = view_injector.get_from_type(view_class)
bindings_for_response = bindings.copy()
bindings_for_response.bind('request').to_instance(request)
for item in kwargs.iteritems():
bindings_for_response.bind_name(item[0]).to_instance(item[1])
response_injector = Injector(bindings_for_response)
response = response_injector.call(view.respond)
return response.render(request)
return view
def url_to_class_builder(bindings):
view = _view_builder(bindings.copy())
def url_to_class(regex, view_class, kwargs=None, name=None):
if kwargs is None:
kwargs = {}
kwargs['view_class'] = view_class
return django.conf.urls.defaults.url(regex, view, kwargs, name=name)
return url_to_class
|
django = __import__("django.conf.urls.defaults", {})
from zuice import Injector
def _view_builder(bindings):
def view(request, view_class, **kwargs):
view_injector = Injector(bindings)
view = view_injector.get_from_type(view_class)
bindings_for_response = bindings.copy()
bindings_for_response.bind('request').to_instance(request)
for item in kwargs.iteritems():
bindings_for_response.bind_name(item[0]).to_instance(item[1])
response_injector = Injector(bindings_for_response)
response = response_injector.call(view.respond)
return response.render(request)
return view
def url_to_class_builder(bindings):
+ view = _view_builder(bindings.copy())
def url_to_class(regex, view_class, kwargs=None, name=None):
if kwargs is None:
kwargs = {}
kwargs['view_class'] = view_class
- return django.conf.urls.defaults.url(regex, _view_builder(bindings), kwargs, name=name)
? - ------------------
+ return django.conf.urls.defaults.url(regex, view, kwargs, name=name)
return url_to_class
|
d01a5cdf950b7421703e2a018ee0306935e79555
|
sugar/activity/__init__.py
|
sugar/activity/__init__.py
|
import gtk
from sugar.graphics.grid import Grid
settings = gtk.settings_get_default()
grid = Grid()
sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1))
settings.set_string_property('gtk-icon-sizes', sizes, '')
settings.set_string_property('gtk-font-name', 'Sans 14', '')
def get_default_type(activity_type):
"""Get the activity default type.
It's the type of the main network service which tracks presence
and provides info about the activity, for example the title."""
splitted_id = activity_type.split('.')
splitted_id.reverse()
return '_' + '_'.join(splitted_id) + '._udp'
|
import gtk
from sugar.graphics.grid import Grid
settings = gtk.settings_get_default()
grid = Grid()
sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1))
settings.set_string_property('gtk-icon-sizes', sizes, '')
def get_default_type(activity_type):
"""Get the activity default type.
It's the type of the main network service which tracks presence
and provides info about the activity, for example the title."""
splitted_id = activity_type.split('.')
splitted_id.reverse()
return '_' + '_'.join(splitted_id) + '._udp'
|
Move font size in the theme
|
Move font size in the theme
|
Python
|
lgpl-2.1
|
Daksh/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,ceibal-tatu/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,quozl/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,godiard/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,i5o/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,samdroid-apps/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,ceibal-tatu/sugar-toolkit,sugarlabs/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,samdroid-apps/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,tchx84/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,godiard/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,puneetgkaur/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,gusDuarte/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit
|
import gtk
from sugar.graphics.grid import Grid
settings = gtk.settings_get_default()
grid = Grid()
sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1))
settings.set_string_property('gtk-icon-sizes', sizes, '')
- settings.set_string_property('gtk-font-name', 'Sans 14', '')
-
def get_default_type(activity_type):
"""Get the activity default type.
It's the type of the main network service which tracks presence
and provides info about the activity, for example the title."""
splitted_id = activity_type.split('.')
splitted_id.reverse()
return '_' + '_'.join(splitted_id) + '._udp'
|
Move font size in the theme
|
## Code Before:
import gtk
from sugar.graphics.grid import Grid
settings = gtk.settings_get_default()
grid = Grid()
sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1))
settings.set_string_property('gtk-icon-sizes', sizes, '')
settings.set_string_property('gtk-font-name', 'Sans 14', '')
def get_default_type(activity_type):
"""Get the activity default type.
It's the type of the main network service which tracks presence
and provides info about the activity, for example the title."""
splitted_id = activity_type.split('.')
splitted_id.reverse()
return '_' + '_'.join(splitted_id) + '._udp'
## Instruction:
Move font size in the theme
## Code After:
import gtk
from sugar.graphics.grid import Grid
settings = gtk.settings_get_default()
grid = Grid()
sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1))
settings.set_string_property('gtk-icon-sizes', sizes, '')
def get_default_type(activity_type):
"""Get the activity default type.
It's the type of the main network service which tracks presence
and provides info about the activity, for example the title."""
splitted_id = activity_type.split('.')
splitted_id.reverse()
return '_' + '_'.join(splitted_id) + '._udp'
|
import gtk
from sugar.graphics.grid import Grid
settings = gtk.settings_get_default()
grid = Grid()
sizes = 'gtk-large-toolbar=%d, %d' % (grid.dimension(1), grid.dimension(1))
settings.set_string_property('gtk-icon-sizes', sizes, '')
- settings.set_string_property('gtk-font-name', 'Sans 14', '')
-
def get_default_type(activity_type):
"""Get the activity default type.
It's the type of the main network service which tracks presence
and provides info about the activity, for example the title."""
splitted_id = activity_type.split('.')
splitted_id.reverse()
return '_' + '_'.join(splitted_id) + '._udp'
|
30ed3800fdeec4aec399e6e0ec0760e46eb891ec
|
djangoautoconf/model_utils/model_reversion.py
|
djangoautoconf/model_utils/model_reversion.py
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
from reversion.revisions import default_revision_manager
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
default_revision_manager.save_revision((item,))
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
def create_initial_version(obj):
try:
from reversion.revisions import default_revision_manager
default_revision_manager.save_revision((obj,))
except:
from reversion.revisions import add_to_revision
add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
Fix broken initial version creation.
|
Fix broken initial version creation.
|
Python
|
bsd-3-clause
|
weijia/djangoautoconf,weijia/djangoautoconf
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
+
+
+ def create_initial_version(obj):
+ try:
- from reversion.revisions import default_revision_manager
+ from reversion.revisions import default_revision_manager
+ default_revision_manager.save_revision((obj,))
+ except:
+ from reversion.revisions import add_to_revision
+ add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
- default_revision_manager.save_revision((item,))
+ create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
Fix broken initial version creation.
|
## Code Before:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
from reversion.revisions import default_revision_manager
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
default_revision_manager.save_revision((item,))
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
## Instruction:
Fix broken initial version creation.
## Code After:
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
def create_initial_version(obj):
try:
from reversion.revisions import default_revision_manager
default_revision_manager.save_revision((obj,))
except:
from reversion.revisions import add_to_revision
add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save
from django.dispatch import receiver
from reversion.models import Version
+
+
+ def create_initial_version(obj):
+ try:
- from reversion.revisions import default_revision_manager
+ from reversion.revisions import default_revision_manager
? ++++++++
+ default_revision_manager.save_revision((obj,))
+ except:
+ from reversion.revisions import add_to_revision
+ add_to_revision(obj)
global_save_signal_receiver = []
class PreSaveHandler(object):
def __init__(self, model_inst):
super(PreSaveHandler, self).__init__()
self.model_inst = model_inst
def object_save_handler(self, sender, instance, **kwargs):
# logging.error("======================================")
if not (instance.pk is None):
content_type = ContentType.objects.get_for_model(self.model_inst)
versioned_pk_queryset = Version.objects.filter(content_type=content_type).filter(object_id_int=instance.pk)
if not versioned_pk_queryset.exists():
item = self.model_inst.objects.get(pk=instance.pk)
try:
- default_revision_manager.save_revision((item,))
+ create_initial_version(item)
except:
pass
def add_reversion_before_save(model_inst):
s = PreSaveHandler(model_inst)
global_save_signal_receiver.append(s)
receiver(pre_save, sender=model_inst)(s.object_save_handler)
|
c6917a2f439b99078e67310230f1d0cfa0de8a7b
|
tests/builder_tests.py
|
tests/builder_tests.py
|
import ujson
import unittest
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.pool import NullPool
from interrogate import Builder
class InterrogateTestCase(unittest.TestCase):
def valid_builder_args(self):
model = self.model
type_constraints = {
'string': [
'name',
'email'
],
'numeric': [
'age',
'height'
],
'nullable': [
'email',
'height'
]
}
query_constraints = {
'breadth': None,
'depth': 32,
'elements': 64
}
return [model, type_constraints, query_constraints]
def make_builder(self, model=None, type_constraints=None, query_constraints=None):
dm, dt, dq = self.valid_builder_args()
return Builder(
model or dm,
type_constraints or dt,
query_constraints or dq
)
def setUp(self):
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
age = Column(Integer)
height = Column(Integer)
engine = create_engine("sqlite://", poolclass=NullPool)
Base.metadata.create_all(engine)
self.model = User
self.session = sessionmaker(bind=engine)()
def tearDown(self):
self.session.close()
|
import ujson
import unittest
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from interrogate import Builder
class InterrogateTestCase(unittest.TestCase):
def valid_builder_args(self):
model = self.model
query_constraints = {
'breadth': None,
'depth': 32,
'elements': 64
}
return [model, query_constraints]
def make_builder(self, model=None, query_constraints=None):
dm, dt, dq = self.valid_builder_args()
return Builder(
model or dm,
query_constraints or dq
)
def setUp(self):
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
age = Column(Integer)
height = Column(Integer)
engine = create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)
self.model = User
self.session = sessionmaker(bind=engine)()
def tearDown(self):
self.session.close()
def add_user(self, **kwargs):
user = self.model(**kwargs)
self.session.add(user)
self.session.commit()
|
Add test helper for creating users
|
Add test helper for creating users
|
Python
|
mit
|
numberoverzero/jsonquery
|
import ujson
import unittest
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.pool import NullPool
from interrogate import Builder
class InterrogateTestCase(unittest.TestCase):
def valid_builder_args(self):
model = self.model
- type_constraints = {
- 'string': [
- 'name',
- 'email'
- ],
- 'numeric': [
- 'age',
- 'height'
- ],
- 'nullable': [
- 'email',
- 'height'
- ]
- }
query_constraints = {
'breadth': None,
'depth': 32,
'elements': 64
}
- return [model, type_constraints, query_constraints]
+ return [model, query_constraints]
- def make_builder(self, model=None, type_constraints=None, query_constraints=None):
+ def make_builder(self, model=None, query_constraints=None):
dm, dt, dq = self.valid_builder_args()
return Builder(
model or dm,
- type_constraints or dt,
query_constraints or dq
)
def setUp(self):
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
age = Column(Integer)
height = Column(Integer)
- engine = create_engine("sqlite://", poolclass=NullPool)
+ engine = create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)
self.model = User
self.session = sessionmaker(bind=engine)()
def tearDown(self):
self.session.close()
+ def add_user(self, **kwargs):
+ user = self.model(**kwargs)
+ self.session.add(user)
+ self.session.commit()
+
|
Add test helper for creating users
|
## Code Before:
import ujson
import unittest
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.pool import NullPool
from interrogate import Builder
class InterrogateTestCase(unittest.TestCase):
def valid_builder_args(self):
model = self.model
type_constraints = {
'string': [
'name',
'email'
],
'numeric': [
'age',
'height'
],
'nullable': [
'email',
'height'
]
}
query_constraints = {
'breadth': None,
'depth': 32,
'elements': 64
}
return [model, type_constraints, query_constraints]
def make_builder(self, model=None, type_constraints=None, query_constraints=None):
dm, dt, dq = self.valid_builder_args()
return Builder(
model or dm,
type_constraints or dt,
query_constraints or dq
)
def setUp(self):
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
age = Column(Integer)
height = Column(Integer)
engine = create_engine("sqlite://", poolclass=NullPool)
Base.metadata.create_all(engine)
self.model = User
self.session = sessionmaker(bind=engine)()
def tearDown(self):
self.session.close()
## Instruction:
Add test helper for creating users
## Code After:
import ujson
import unittest
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from interrogate import Builder
class InterrogateTestCase(unittest.TestCase):
def valid_builder_args(self):
model = self.model
query_constraints = {
'breadth': None,
'depth': 32,
'elements': 64
}
return [model, query_constraints]
def make_builder(self, model=None, query_constraints=None):
dm, dt, dq = self.valid_builder_args()
return Builder(
model or dm,
query_constraints or dq
)
def setUp(self):
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
age = Column(Integer)
height = Column(Integer)
engine = create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)
self.model = User
self.session = sessionmaker(bind=engine)()
def tearDown(self):
self.session.close()
def add_user(self, **kwargs):
user = self.model(**kwargs)
self.session.add(user)
self.session.commit()
|
import ujson
import unittest
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.pool import NullPool
from interrogate import Builder
class InterrogateTestCase(unittest.TestCase):
def valid_builder_args(self):
model = self.model
- type_constraints = {
- 'string': [
- 'name',
- 'email'
- ],
- 'numeric': [
- 'age',
- 'height'
- ],
- 'nullable': [
- 'email',
- 'height'
- ]
- }
query_constraints = {
'breadth': None,
'depth': 32,
'elements': 64
}
- return [model, type_constraints, query_constraints]
? ------------------
+ return [model, query_constraints]
- def make_builder(self, model=None, type_constraints=None, query_constraints=None):
? -----------------------
+ def make_builder(self, model=None, query_constraints=None):
dm, dt, dq = self.valid_builder_args()
return Builder(
model or dm,
- type_constraints or dt,
query_constraints or dq
)
def setUp(self):
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
age = Column(Integer)
height = Column(Integer)
- engine = create_engine("sqlite://", poolclass=NullPool)
? ^ ------- ^ ^^^^^^
+ engine = create_engine("sqlite://", echo=True)
? ^^^ ^^ ^
Base.metadata.create_all(engine)
self.model = User
self.session = sessionmaker(bind=engine)()
def tearDown(self):
self.session.close()
+
+ def add_user(self, **kwargs):
+ user = self.model(**kwargs)
+ self.session.add(user)
+ self.session.commit()
|
c6f2ff563c08eb43ba3f33bc9aaa2647e78701d2
|
fenced_code_plus/__init__.py
|
fenced_code_plus/__init__.py
|
from fenced_code_plus import FencedCodePlusExtension
from fenced_code_plus import makeExtension
|
from __future__ import absolute_import
from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension
from fenced_code_plus.fenced_code_plus import makeExtension
|
Make import compatable with python3.5
|
Make import compatable with python3.5
|
Python
|
bsd-3-clause
|
amfarrell/fenced-code-plus
|
+ from __future__ import absolute_import
- from fenced_code_plus import FencedCodePlusExtension
- from fenced_code_plus import makeExtension
+ from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension
+ from fenced_code_plus.fenced_code_plus import makeExtension
+
|
Make import compatable with python3.5
|
## Code Before:
from fenced_code_plus import FencedCodePlusExtension
from fenced_code_plus import makeExtension
## Instruction:
Make import compatable with python3.5
## Code After:
from __future__ import absolute_import
from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension
from fenced_code_plus.fenced_code_plus import makeExtension
|
+ from __future__ import absolute_import
+
- from fenced_code_plus import FencedCodePlusExtension
+ from fenced_code_plus.fenced_code_plus import FencedCodePlusExtension
? +++++++++++++++++
- from fenced_code_plus import makeExtension
+ from fenced_code_plus.fenced_code_plus import makeExtension
? +++++++++++++++++
|
c9b97f6d1148378d1ba7189a1838ea03e240de40
|
pycron/__init__.py
|
pycron/__init__.py
|
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
@input: cron-like string
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
|
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if ',' in value:
if '*' in value:
raise ValueError
values = filter(None, [int(x.strip()) for x in value.split(',')])
if target in values:
return True
return False
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
@input: cron-like string (minute, hour, day of month, month, day of week)
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
|
Add parsing for list of numbers.
|
Add parsing for list of numbers.
|
Python
|
mit
|
kipe/pycron
|
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
+
+ if ',' in value:
+ if '*' in value:
+ raise ValueError
+
+ values = filter(None, [int(x.strip()) for x in value.split(',')])
+ if target in values:
+ return True
+ return False
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
- @input: cron-like string
+ @input: cron-like string (minute, hour, day of month, month, day of week)
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
|
Add parsing for list of numbers.
|
## Code Before:
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
@input: cron-like string
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
## Instruction:
Add parsing for list of numbers.
## Code After:
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if ',' in value:
if '*' in value:
raise ValueError
values = filter(None, [int(x.strip()) for x in value.split(',')])
if target in values:
return True
return False
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
@input: cron-like string (minute, hour, day of month, month, day of week)
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
|
from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
+
+ if ',' in value:
+ if '*' in value:
+ raise ValueError
+
+ values = filter(None, [int(x.strip()) for x in value.split(',')])
+ if target in values:
+ return True
+ return False
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
raise ValueError
return target % int(interval) == 0
if int(value) == target:
return True
return False
def is_now(s):
'''
A very simple cron-like parser to determine, if (cron-like) string is valid for this date and time.
- @input: cron-like string
+ @input: cron-like string (minute, hour, day of month, month, day of week)
@output: boolean of result
'''
now = datetime.now()
minute, hour, dom, month, dow = s.split(' ')
return _parse_arg(minute, now.minute, 30) \
and _parse_arg(hour, now.hour, 12) \
and _parse_arg(dom, now.day, 14) \
and _parse_arg(month, now.month, 6) \
and _parse_arg(dow, now.weekday(), 3)
|
eeeba609afe732b8e95aa535e70d4cdd2ae1aac7
|
tests/unit/test_cufflinks.py
|
tests/unit/test_cufflinks.py
|
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
# fixed_fn = os.path.join(self.out_dir, "fixed.gtf")
# fixed = cufflinks.fix_cufflinks_attributes(self.ref_gtf, clean, fixed_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
# assert(file_exists(fixed))
def tearDown(self):
shutil.rmtree(self.out_dir)
|
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
def tearDown(self):
shutil.rmtree(self.out_dir)
|
Remove some cruft from the cufflinks test.
|
Remove some cruft from the cufflinks test.
|
Python
|
mit
|
vladsaveliev/bcbio-nextgen,biocyberman/bcbio-nextgen,verdurin/bcbio-nextgen,fw1121/bcbio-nextgen,gifford-lab/bcbio-nextgen,chapmanb/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,hjanime/bcbio-nextgen,verdurin/bcbio-nextgen,lbeltrame/bcbio-nextgen,verdurin/bcbio-nextgen,SciLifeLab/bcbio-nextgen,chapmanb/bcbio-nextgen,lpantano/bcbio-nextgen,vladsaveliev/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,mjafin/bcbio-nextgen,brainstorm/bcbio-nextgen,lbeltrame/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,fw1121/bcbio-nextgen,a113n/bcbio-nextgen,brainstorm/bcbio-nextgen,SciLifeLab/bcbio-nextgen,mjafin/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,mjafin/bcbio-nextgen,lbeltrame/bcbio-nextgen,biocyberman/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,chapmanb/bcbio-nextgen,gifford-lab/bcbio-nextgen,lpantano/bcbio-nextgen,lpantano/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,gifford-lab/bcbio-nextgen,fw1121/bcbio-nextgen,vladsaveliev/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,a113n/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,hjanime/bcbio-nextgen,SciLifeLab/bcbio-nextgen,brainstorm/bcbio-nextgen,biocyberman/bcbio-nextgen,hjanime/bcbio-nextgen,a113n/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen
|
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
- # fixed_fn = os.path.join(self.out_dir, "fixed.gtf")
- # fixed = cufflinks.fix_cufflinks_attributes(self.ref_gtf, clean, fixed_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
- # assert(file_exists(fixed))
def tearDown(self):
shutil.rmtree(self.out_dir)
|
Remove some cruft from the cufflinks test.
|
## Code Before:
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
# fixed_fn = os.path.join(self.out_dir, "fixed.gtf")
# fixed = cufflinks.fix_cufflinks_attributes(self.ref_gtf, clean, fixed_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
# assert(file_exists(fixed))
def tearDown(self):
shutil.rmtree(self.out_dir)
## Instruction:
Remove some cruft from the cufflinks test.
## Code After:
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
def tearDown(self):
shutil.rmtree(self.out_dir)
|
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(DATA_DIR, "cufflinks", "merged.gtf")
ref_gtf = os.path.join(DATA_DIR, "cufflinks", "ref-transcripts.gtf")
out_dir = "cufflinks-test"
def setUp(self):
safe_makedir(self.out_dir)
@attr("unit")
def test_cufflinks_clean(self):
clean_fn = os.path.join(self.out_dir, "clean.gtf")
dirty_fn = os.path.join(self.out_dir, "dirty.gtf")
clean, dirty = cufflinks.clean_assembly(self.merged_gtf, clean_fn,
dirty_fn)
- # fixed_fn = os.path.join(self.out_dir, "fixed.gtf")
- # fixed = cufflinks.fix_cufflinks_attributes(self.ref_gtf, clean, fixed_fn)
assert(file_exists(clean))
assert(os.path.exists(dirty))
- # assert(file_exists(fixed))
def tearDown(self):
shutil.rmtree(self.out_dir)
|
83c12d598221aac8e7173fb7d78083bc1c5ab64b
|
tests/test_commands.py
|
tests/test_commands.py
|
import unittest
from cobe.commands import LearnIrcLogCommand
class testIrcLogParsing(unittest.TestCase):
def setUp(self):
self.command = LearnIrcLogCommand()
def testNonPubmsg(self):
msg = "this is some non-pubmsg text found in a log"
cmd = self.command
self.assertEqual(None, cmd._parse_irc_message(msg))
def testNormalPubmsg(self):
msg = "12:00 <foo> bar baz"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
def testKibotQuotePubmsg(self):
msg = "12:00 <foo> \"bar baz\" --user, 01-oct-09"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
if __name__ == '__main__':
unittest.main()
|
import unittest
from cobe.commands import LearnIrcLogCommand
class testIrcLogParsing(unittest.TestCase):
def setUp(self):
self.command = LearnIrcLogCommand()
def testNonPubmsg(self):
msg = "this is some non-pubmsg text found in a log"
cmd = self.command
self.assertEqual(None, cmd._parse_irc_message(msg))
def testNormalPubmsg(self):
msg = "12:00 <foo> bar baz"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
def testKibotQuotePubmsg(self):
msg = "12:00 <foo> \"bar baz\" --user, 01-oct-09"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
def testIgnoredNickPubmsg(self):
msg = "12:00 <foo> bar baz"
cmd = self.command
self.assertEqual(None, cmd._parse_irc_message(msg, ["foo"]))
if __name__ == '__main__':
unittest.main()
|
Add a unit test for ignored nicks in _parse_irc_message
|
Add a unit test for ignored nicks in _parse_irc_message
|
Python
|
mit
|
pteichman/cobe,wodim/cobe-ng,wodim/cobe-ng,DarkMio/cobe,tiagochiavericosta/cobe,meska/cobe,LeMagnesium/cobe,LeMagnesium/cobe,DarkMio/cobe,meska/cobe,tiagochiavericosta/cobe,pteichman/cobe
|
import unittest
from cobe.commands import LearnIrcLogCommand
class testIrcLogParsing(unittest.TestCase):
def setUp(self):
self.command = LearnIrcLogCommand()
def testNonPubmsg(self):
msg = "this is some non-pubmsg text found in a log"
cmd = self.command
self.assertEqual(None, cmd._parse_irc_message(msg))
def testNormalPubmsg(self):
msg = "12:00 <foo> bar baz"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
def testKibotQuotePubmsg(self):
msg = "12:00 <foo> \"bar baz\" --user, 01-oct-09"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
+ def testIgnoredNickPubmsg(self):
+ msg = "12:00 <foo> bar baz"
+ cmd = self.command
+
+ self.assertEqual(None, cmd._parse_irc_message(msg, ["foo"]))
+
if __name__ == '__main__':
unittest.main()
|
Add a unit test for ignored nicks in _parse_irc_message
|
## Code Before:
import unittest
from cobe.commands import LearnIrcLogCommand
class testIrcLogParsing(unittest.TestCase):
def setUp(self):
self.command = LearnIrcLogCommand()
def testNonPubmsg(self):
msg = "this is some non-pubmsg text found in a log"
cmd = self.command
self.assertEqual(None, cmd._parse_irc_message(msg))
def testNormalPubmsg(self):
msg = "12:00 <foo> bar baz"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
def testKibotQuotePubmsg(self):
msg = "12:00 <foo> \"bar baz\" --user, 01-oct-09"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
if __name__ == '__main__':
unittest.main()
## Instruction:
Add a unit test for ignored nicks in _parse_irc_message
## Code After:
import unittest
from cobe.commands import LearnIrcLogCommand
class testIrcLogParsing(unittest.TestCase):
def setUp(self):
self.command = LearnIrcLogCommand()
def testNonPubmsg(self):
msg = "this is some non-pubmsg text found in a log"
cmd = self.command
self.assertEqual(None, cmd._parse_irc_message(msg))
def testNormalPubmsg(self):
msg = "12:00 <foo> bar baz"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
def testKibotQuotePubmsg(self):
msg = "12:00 <foo> \"bar baz\" --user, 01-oct-09"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
def testIgnoredNickPubmsg(self):
msg = "12:00 <foo> bar baz"
cmd = self.command
self.assertEqual(None, cmd._parse_irc_message(msg, ["foo"]))
if __name__ == '__main__':
unittest.main()
|
import unittest
from cobe.commands import LearnIrcLogCommand
class testIrcLogParsing(unittest.TestCase):
def setUp(self):
self.command = LearnIrcLogCommand()
def testNonPubmsg(self):
msg = "this is some non-pubmsg text found in a log"
cmd = self.command
self.assertEqual(None, cmd._parse_irc_message(msg))
def testNormalPubmsg(self):
msg = "12:00 <foo> bar baz"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
def testKibotQuotePubmsg(self):
msg = "12:00 <foo> \"bar baz\" --user, 01-oct-09"
cmd = self.command
self.assertEqual("bar baz", cmd._parse_irc_message(msg))
+ def testIgnoredNickPubmsg(self):
+ msg = "12:00 <foo> bar baz"
+ cmd = self.command
+
+ self.assertEqual(None, cmd._parse_irc_message(msg, ["foo"]))
+
if __name__ == '__main__':
unittest.main()
|
e3adb0e716cd3f200baa037f6d5a1dd0bb598202
|
src/shield/__init__.py
|
src/shield/__init__.py
|
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
import inspect
from . import registry
class _method_wrapper(object):
"""A placeholder object used to wrap methods until the rules decorator
comes around and adds everything to the shield registry."""
def __init__(self, fn, permissions, owner, target):
self.permissions = permissions
self.owner = owner
self.target = target
self.fn = fn
def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs)
class rule:
def __init__(self, owner, permissions, target=None):
"""owner: The owner of the permissions.
permissions: The set of permissions that the owner has
target: The model that we are checking if the owner has permissions for
"""
self.owner = owner
self.permissions = permissions
self.target = target
def __call__(self, fn):
return _method_wrapper(fn, self.permissions, self.owner, self.target)
def rules(cls):
"""Add all permission methods on the decorated object to our registry."""
# This is called after the class object is instantiated and all methods are
# wrapped with the decorator. Iterate over all of our personal wrapped
# methods, unwrap them, and add them to the registry.
mems = inspect.getmembers(cls, lambda x: isinstance(x, _method_wrapper))
for name, member in mems:
# Unwrap each method
# Add the member to the registry
for perm in member.permissions:
registry.registry[(member.owner, perm, member.target)] = member.fn
# Now that the method has been added to the registry, unwrap the method
# since we don't need the wrapper anymore.
setattr(cls, name, member.fn)
|
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
from . import registry
class rule:
"""Add the decorated rule to our registry"""
def __init__(self, *perms, **kwargs):
"""owner: The owner of the permissions.
permissions: The set of permissions that the owner has
target: The model that we are checking if the owner has permissions for
"""
# Owner is a mandatory kwarg param
self.owner = kwargs['owner']
# Target is an optional param used to denote what registry the
# decorated function goes into
self.target = kwargs.get('target')
# The permission list!
self.permissions = perms
def __call__(self, fn):
"""Add the passed function to the registry
"""
for perm in self.permissions:
# If we have no target, this goes into the general registry
# otherwise it goes into the targeted registry
if self.target is None:
registry.general[(self.owner, perm)] = fn
else:
registry.targeted[(self.owner, perm, self.target)] = fn
# We really have no reason to keep the wrapper now that we have added
# the function to the registry
return fn
|
Delete the class method shenannigans
|
Delete the class method shenannigans
|
Python
|
mit
|
concordusapps/python-shield
|
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
- import inspect
from . import registry
+ class rule:
+ """Add the decorated rule to our registry"""
- class _method_wrapper(object):
- """A placeholder object used to wrap methods until the rules decorator
- comes around and adds everything to the shield registry."""
- def __init__(self, fn, permissions, owner, target):
- self.permissions = permissions
- self.owner = owner
- self.target = target
- self.fn = fn
-
- def __call__(self, *args, **kwargs):
+ def __init__(self, *perms, **kwargs):
- return self.fn(*args, **kwargs)
-
-
- class rule:
-
- def __init__(self, owner, permissions, target=None):
"""owner: The owner of the permissions.
permissions: The set of permissions that the owner has
target: The model that we are checking if the owner has permissions for
"""
+ # Owner is a mandatory kwarg param
- self.owner = owner
+ self.owner = kwargs['owner']
+
+ # Target is an optional param used to denote what registry the
+ # decorated function goes into
+ self.target = kwargs.get('target')
+
+ # The permission list!
- self.permissions = permissions
+ self.permissions = perms
- self.target = target
def __call__(self, fn):
- return _method_wrapper(fn, self.permissions, self.owner, self.target)
+ """Add the passed function to the registry
+ """
+ for perm in self.permissions:
+ # If we have no target, this goes into the general registry
+ # otherwise it goes into the targeted registry
+ if self.target is None:
+ registry.general[(self.owner, perm)] = fn
+ else:
+ registry.targeted[(self.owner, perm, self.target)] = fn
+ # We really have no reason to keep the wrapper now that we have added
+ # the function to the registry
+ return fn
- def rules(cls):
- """Add all permission methods on the decorated object to our registry."""
- # This is called after the class object is instantiated and all methods are
- # wrapped with the decorator. Iterate over all of our personal wrapped
- # methods, unwrap them, and add them to the registry.
-
- mems = inspect.getmembers(cls, lambda x: isinstance(x, _method_wrapper))
-
- for name, member in mems:
- # Unwrap each method
- # Add the member to the registry
- for perm in member.permissions:
- registry.registry[(member.owner, perm, member.target)] = member.fn
-
- # Now that the method has been added to the registry, unwrap the method
- # since we don't need the wrapper anymore.
- setattr(cls, name, member.fn)
-
|
Delete the class method shenannigans
|
## Code Before:
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
import inspect
from . import registry
class _method_wrapper(object):
"""A placeholder object used to wrap methods until the rules decorator
comes around and adds everything to the shield registry."""
def __init__(self, fn, permissions, owner, target):
self.permissions = permissions
self.owner = owner
self.target = target
self.fn = fn
def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs)
class rule:
def __init__(self, owner, permissions, target=None):
"""owner: The owner of the permissions.
permissions: The set of permissions that the owner has
target: The model that we are checking if the owner has permissions for
"""
self.owner = owner
self.permissions = permissions
self.target = target
def __call__(self, fn):
return _method_wrapper(fn, self.permissions, self.owner, self.target)
def rules(cls):
"""Add all permission methods on the decorated object to our registry."""
# This is called after the class object is instantiated and all methods are
# wrapped with the decorator. Iterate over all of our personal wrapped
# methods, unwrap them, and add them to the registry.
mems = inspect.getmembers(cls, lambda x: isinstance(x, _method_wrapper))
for name, member in mems:
# Unwrap each method
# Add the member to the registry
for perm in member.permissions:
registry.registry[(member.owner, perm, member.target)] = member.fn
# Now that the method has been added to the registry, unwrap the method
# since we don't need the wrapper anymore.
setattr(cls, name, member.fn)
## Instruction:
Delete the class method shenannigans
## Code After:
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
from . import registry
class rule:
"""Add the decorated rule to our registry"""
def __init__(self, *perms, **kwargs):
"""owner: The owner of the permissions.
permissions: The set of permissions that the owner has
target: The model that we are checking if the owner has permissions for
"""
# Owner is a mandatory kwarg param
self.owner = kwargs['owner']
# Target is an optional param used to denote what registry the
# decorated function goes into
self.target = kwargs.get('target')
# The permission list!
self.permissions = perms
def __call__(self, fn):
"""Add the passed function to the registry
"""
for perm in self.permissions:
# If we have no target, this goes into the general registry
# otherwise it goes into the targeted registry
if self.target is None:
registry.general[(self.owner, perm)] = fn
else:
registry.targeted[(self.owner, perm, self.target)] = fn
# We really have no reason to keep the wrapper now that we have added
# the function to the registry
return fn
|
from __future__ import print_function, unicode_literals
from __future__ import absolute_import, division
- import inspect
from . import registry
+ class rule:
+ """Add the decorated rule to our registry"""
- class _method_wrapper(object):
- """A placeholder object used to wrap methods until the rules decorator
- comes around and adds everything to the shield registry."""
- def __init__(self, fn, permissions, owner, target):
- self.permissions = permissions
- self.owner = owner
- self.target = target
- self.fn = fn
-
- def __call__(self, *args, **kwargs):
? ^^^^ ^ ^
+ def __init__(self, *perms, **kwargs):
? ^^^^ ^^ ^
- return self.fn(*args, **kwargs)
-
-
- class rule:
-
- def __init__(self, owner, permissions, target=None):
"""owner: The owner of the permissions.
permissions: The set of permissions that the owner has
target: The model that we are checking if the owner has permissions for
"""
+ # Owner is a mandatory kwarg param
- self.owner = owner
+ self.owner = kwargs['owner']
? ++++++++ ++
+
+ # Target is an optional param used to denote what registry the
+ # decorated function goes into
+ self.target = kwargs.get('target')
+
+ # The permission list!
- self.permissions = permissions
? - -----
+ self.permissions = perms
- self.target = target
def __call__(self, fn):
- return _method_wrapper(fn, self.permissions, self.owner, self.target)
+ """Add the passed function to the registry
+ """
+ for perm in self.permissions:
+ # If we have no target, this goes into the general registry
+ # otherwise it goes into the targeted registry
+ if self.target is None:
+ registry.general[(self.owner, perm)] = fn
+ else:
+ registry.targeted[(self.owner, perm, self.target)] = fn
+ # We really have no reason to keep the wrapper now that we have added
-
- def rules(cls):
- """Add all permission methods on the decorated object to our registry."""
- # This is called after the class object is instantiated and all methods are
- # wrapped with the decorator. Iterate over all of our personal wrapped
- # methods, unwrap them, and add them to the registry.
-
- mems = inspect.getmembers(cls, lambda x: isinstance(x, _method_wrapper))
-
- for name, member in mems:
- # Unwrap each method
- # Add the member to the registry
? ---- ^^^^^^
+ # the function to the registry
? ^^^^^^^^
+ return fn
- for perm in member.permissions:
- registry.registry[(member.owner, perm, member.target)] = member.fn
-
- # Now that the method has been added to the registry, unwrap the method
- # since we don't need the wrapper anymore.
- setattr(cls, name, member.fn)
|
198181baa0b095d120b456e7191c0c49c98b3c03
|
conans/client/generators/xcode.py
|
conans/client/generators/xcode.py
|
from conans.model import Generator
from conans.paths import BUILD_INFO_XCODE
class XCodeGenerator(Generator):
template = '''
HEADER_SEARCH_PATHS = $(inherited) {include_dirs}
LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs}
OTHER_LDFLAGS = $(inherited) {linker_flags} {libs}
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags}
OTHER_CFLAGS = $(inherited)
OTHER_CPLUSPLUSFLAGS = $(inherited)
'''
def __init__(self, deps_cpp_info, cpp_info):
super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info)
self.include_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.include_paths)
self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.lib_paths)
self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs])
self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines)
self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags)
self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags)
@property
def filename(self):
return BUILD_INFO_XCODE
@property
def content(self):
return self.template.format(**self.__dict__)
|
from conans.model import Generator
from conans.paths import BUILD_INFO_XCODE
class XCodeGenerator(Generator):
template = '''
HEADER_SEARCH_PATHS = $(inherited) {include_dirs}
LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs}
OTHER_LDFLAGS = $(inherited) {linker_flags} {libs}
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags}
OTHER_CFLAGS = $(inherited)
OTHER_CPLUSPLUSFLAGS = $(inherited)
'''
def __init__(self, deps_cpp_info, cpp_info):
super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info)
self.include_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.include_paths)
self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.lib_paths)
self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs])
self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines)
self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags)
self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags)
@property
def filename(self):
return BUILD_INFO_XCODE
@property
def content(self):
return self.template.format(**self.__dict__)
|
Fix copy and paste error
|
Fix copy and paste error
|
Python
|
mit
|
conan-io/conan,conan-io/conan,luckielordie/conan,dragly/conan,lasote/conan,dragly/conan,tivek/conan,luckielordie/conan,memsharded/conan,conan-io/conan,memsharded/conan,birsoyo/conan,lasote/conan,memsharded/conan,mropert/conan,Xaltotun/conan,memsharded/conan,Xaltotun/conan,mropert/conan,birsoyo/conan,tivek/conan
|
from conans.model import Generator
from conans.paths import BUILD_INFO_XCODE
class XCodeGenerator(Generator):
template = '''
HEADER_SEARCH_PATHS = $(inherited) {include_dirs}
LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs}
OTHER_LDFLAGS = $(inherited) {linker_flags} {libs}
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags}
OTHER_CFLAGS = $(inherited)
OTHER_CPLUSPLUSFLAGS = $(inherited)
'''
def __init__(self, deps_cpp_info, cpp_info):
- super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info)
+ super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info)
self.include_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.include_paths)
self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.lib_paths)
self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs])
self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines)
self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags)
self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags)
@property
def filename(self):
return BUILD_INFO_XCODE
@property
def content(self):
return self.template.format(**self.__dict__)
|
Fix copy and paste error
|
## Code Before:
from conans.model import Generator
from conans.paths import BUILD_INFO_XCODE
class XCodeGenerator(Generator):
template = '''
HEADER_SEARCH_PATHS = $(inherited) {include_dirs}
LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs}
OTHER_LDFLAGS = $(inherited) {linker_flags} {libs}
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags}
OTHER_CFLAGS = $(inherited)
OTHER_CPLUSPLUSFLAGS = $(inherited)
'''
def __init__(self, deps_cpp_info, cpp_info):
super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info)
self.include_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.include_paths)
self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.lib_paths)
self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs])
self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines)
self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags)
self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags)
@property
def filename(self):
return BUILD_INFO_XCODE
@property
def content(self):
return self.template.format(**self.__dict__)
## Instruction:
Fix copy and paste error
## Code After:
from conans.model import Generator
from conans.paths import BUILD_INFO_XCODE
class XCodeGenerator(Generator):
template = '''
HEADER_SEARCH_PATHS = $(inherited) {include_dirs}
LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs}
OTHER_LDFLAGS = $(inherited) {linker_flags} {libs}
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags}
OTHER_CFLAGS = $(inherited)
OTHER_CPLUSPLUSFLAGS = $(inherited)
'''
def __init__(self, deps_cpp_info, cpp_info):
super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info)
self.include_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.include_paths)
self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.lib_paths)
self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs])
self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines)
self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags)
self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags)
@property
def filename(self):
return BUILD_INFO_XCODE
@property
def content(self):
return self.template.format(**self.__dict__)
|
from conans.model import Generator
from conans.paths import BUILD_INFO_XCODE
class XCodeGenerator(Generator):
template = '''
HEADER_SEARCH_PATHS = $(inherited) {include_dirs}
LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs}
OTHER_LDFLAGS = $(inherited) {linker_flags} {libs}
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags}
OTHER_CFLAGS = $(inherited)
OTHER_CPLUSPLUSFLAGS = $(inherited)
'''
def __init__(self, deps_cpp_info, cpp_info):
- super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info)
? ^^^^^^^^^ ^^
+ super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info)
? ^^^ ^
self.include_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.include_paths)
self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/")
for p in deps_cpp_info.lib_paths)
self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs])
self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines)
self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags)
self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags)
@property
def filename(self):
return BUILD_INFO_XCODE
@property
def content(self):
return self.template.format(**self.__dict__)
|
b242de3217ad9cf6a98ca2513ed1e4f66d2537ad
|
tests/NongeneratingSymbolsRemove/SimpleTest.py
|
tests/NongeneratingSymbolsRemove/SimpleTest.py
|
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
|
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
|
Add simple test of removing nongenerating symbols
|
Add simple test of removing nongenerating symbols
|
Python
|
mit
|
PatrikValkovic/grammpy
|
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
+ class A(Nonterminal):
+ pass
+
+
+ class B(Nonterminal):
+ pass
+
+
+ class C(Nonterminal):
+ pass
+
+
+ class RuleAto0B(Rule):
+ fromSymbol = A
+ right = [0, B]
+
+
+ class RuleBto1(Rule):
+ fromSymbol = B
+ toSymbol = 1
+
+
class SimpleTest(TestCase):
- pass
+ def test_simpleTest(self):
+ g = Grammar(terminals=[0, 1],
+ nonterminals=[A, B, C],
+ rules=[RuleAto0B, RuleBto1])
+ changed = ContextFree.remove_nongenerastingSymbols(g)
+ self.assertTrue(changed.have_term([0, 1]))
+ self.assertTrue(changed.have_nonterm([A, B]))
+ self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
|
Add simple test of removing nongenerating symbols
|
## Code Before:
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
## Instruction:
Add simple test of removing nongenerating symbols
## Code After:
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
class A(Nonterminal):
pass
class B(Nonterminal):
pass
class C(Nonterminal):
pass
class RuleAto0B(Rule):
fromSymbol = A
right = [0, B]
class RuleBto1(Rule):
fromSymbol = B
toSymbol = 1
class SimpleTest(TestCase):
def test_simpleTest(self):
g = Grammar(terminals=[0, 1],
nonterminals=[A, B, C],
rules=[RuleAto0B, RuleBto1])
changed = ContextFree.remove_nongenerastingSymbols(g)
self.assertTrue(changed.have_term([0, 1]))
self.assertTrue(changed.have_nonterm([A, B]))
self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
|
from unittest import TestCase, main
from grammpy import *
from grammpy_transforms import ContextFree
+ class A(Nonterminal):
+ pass
+
+
+ class B(Nonterminal):
+ pass
+
+
+ class C(Nonterminal):
+ pass
+
+
+ class RuleAto0B(Rule):
+ fromSymbol = A
+ right = [0, B]
+
+
+ class RuleBto1(Rule):
+ fromSymbol = B
+ toSymbol = 1
+
+
class SimpleTest(TestCase):
- pass
+ def test_simpleTest(self):
+ g = Grammar(terminals=[0, 1],
+ nonterminals=[A, B, C],
+ rules=[RuleAto0B, RuleBto1])
+ changed = ContextFree.remove_nongenerastingSymbols(g)
+ self.assertTrue(changed.have_term([0, 1]))
+ self.assertTrue(changed.have_nonterm([A, B]))
+ self.assertFalse(changed.have_nonterm(C))
if __name__ == '__main__':
main()
|
d51b7bf7766dc4d56158fcc7e072e27f275f57e8
|
skyfield/__init__.py
|
skyfield/__init__.py
|
__version_info__ = (0, 2)
__version__ = '%s.%s' % __version_info__
|
VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION))
|
Rename silly __version_info__ symbol to VERSION
|
Rename silly __version_info__ symbol to VERSION
Django uses the name VERSION and it always seems good to rid ourselves
of another faux-dunder symbol that really means nothing to the Python
runtime and therefore should not enjoy the (in-?)dignity of a dunder.
|
Python
|
mit
|
GuidoBR/python-skyfield,ozialien/python-skyfield,exoanalytic/python-skyfield,ozialien/python-skyfield,exoanalytic/python-skyfield,skyfielders/python-skyfield,GuidoBR/python-skyfield,skyfielders/python-skyfield
|
- __version_info__ = (0, 2)
- __version__ = '%s.%s' % __version_info__
+ VERSION = (0, 2)
+ __version__ = '.'.join(map(str, VERSION))
|
Rename silly __version_info__ symbol to VERSION
|
## Code Before:
__version_info__ = (0, 2)
__version__ = '%s.%s' % __version_info__
## Instruction:
Rename silly __version_info__ symbol to VERSION
## Code After:
VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION))
|
- __version_info__ = (0, 2)
- __version__ = '%s.%s' % __version_info__
+ VERSION = (0, 2)
+ __version__ = '.'.join(map(str, VERSION))
|
402f71cc65f714cf880c9c9569e83f5bcd47ec72
|
paintstore/widgets.py
|
paintstore/widgets.py
|
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
class ColorPickerWidget(forms.TextInput):
class Media:
css = {
"all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),)
}
js = (
("%s/%s" % (settings.STATIC_URL, "paintstore/jquery_1.7.2.js")),
("%s/%s" % (settings.STATIC_URL, "paintstore/colorpicker.js"))
)
input_type = 'colorpicker'
def render(self, name, value, attrs=None):
script = u"""<script type='text/javascript'>
$(document).ready(function(){
$('#%s').ColorPicker({
onSubmit: function(hsb, hex, rgb, el, parent) {
$(el).val('#' + hex);
$(el).ColorPickerHide();
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
}).bind('keyup', function(){
$(this).ColorPickerSetColor(this.value.replace('#', ''));
});
});
</script>
""" % ("id_%s" % name,)
super_render = super(ColorPickerWidget, self).render(name, value, attrs)
return mark_safe(u"%s%s" % (super_render, script))
|
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
class ColorPickerWidget(forms.TextInput):
class Media:
css = {
"all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),)
}
js = (
("%s/%s" % (settings.STATIC_URL, "paintstore/jquery_1.7.2.js")),
("%s/%s" % (settings.STATIC_URL, "paintstore/colorpicker.js"))
)
input_type = 'colorpicker'
def render(self, name, value, attrs=None):
script = u"""<script type='text/javascript'>
$(document).ready(function(){{
$('#{0}').ColorPicker({{
onSubmit: function(hsb, hex, rgb, el, parent) {{
$(el).val('#' + hex);
$(el).ColorPickerHide();
$('#{0}').css('background-color', '#' + hex);
}},
onBeforeShow: function () {{
$(this).ColorPickerSetColor(this.value);
}}
}}).bind('keyup', function(){{
$(this).ColorPickerSetColor(this.value.replace('#', ''));
}});
$('#{0}').css('background-color', $('#{0}').val());
}});
</script>
""".format(u'id_'+name)
super_render = super(ColorPickerWidget, self).render(name, value, attrs)
return mark_safe(u"%s%s" % (super_render, script))
|
Change the background to reflect the color chosen
|
Change the background to reflect the color chosen
|
Python
|
mit
|
jamescw/django-paintstore,jamescw/django-paintstore
|
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
class ColorPickerWidget(forms.TextInput):
class Media:
css = {
"all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),)
}
js = (
("%s/%s" % (settings.STATIC_URL, "paintstore/jquery_1.7.2.js")),
("%s/%s" % (settings.STATIC_URL, "paintstore/colorpicker.js"))
)
input_type = 'colorpicker'
def render(self, name, value, attrs=None):
script = u"""<script type='text/javascript'>
- $(document).ready(function(){
+ $(document).ready(function(){{
- $('#%s').ColorPicker({
+ $('#{0}').ColorPicker({{
- onSubmit: function(hsb, hex, rgb, el, parent) {
+ onSubmit: function(hsb, hex, rgb, el, parent) {{
$(el).val('#' + hex);
$(el).ColorPickerHide();
+ $('#{0}').css('background-color', '#' + hex);
- },
+ }},
- onBeforeShow: function () {
+ onBeforeShow: function () {{
$(this).ColorPickerSetColor(this.value);
- }
+ }}
- }).bind('keyup', function(){
+ }}).bind('keyup', function(){{
$(this).ColorPickerSetColor(this.value.replace('#', ''));
- });
+ }});
+ $('#{0}').css('background-color', $('#{0}').val());
- });
+ }});
</script>
- """ % ("id_%s" % name,)
+ """.format(u'id_'+name)
super_render = super(ColorPickerWidget, self).render(name, value, attrs)
return mark_safe(u"%s%s" % (super_render, script))
|
Change the background to reflect the color chosen
|
## Code Before:
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
class ColorPickerWidget(forms.TextInput):
class Media:
css = {
"all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),)
}
js = (
("%s/%s" % (settings.STATIC_URL, "paintstore/jquery_1.7.2.js")),
("%s/%s" % (settings.STATIC_URL, "paintstore/colorpicker.js"))
)
input_type = 'colorpicker'
def render(self, name, value, attrs=None):
script = u"""<script type='text/javascript'>
$(document).ready(function(){
$('#%s').ColorPicker({
onSubmit: function(hsb, hex, rgb, el, parent) {
$(el).val('#' + hex);
$(el).ColorPickerHide();
},
onBeforeShow: function () {
$(this).ColorPickerSetColor(this.value);
}
}).bind('keyup', function(){
$(this).ColorPickerSetColor(this.value.replace('#', ''));
});
});
</script>
""" % ("id_%s" % name,)
super_render = super(ColorPickerWidget, self).render(name, value, attrs)
return mark_safe(u"%s%s" % (super_render, script))
## Instruction:
Change the background to reflect the color chosen
## Code After:
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
class ColorPickerWidget(forms.TextInput):
class Media:
css = {
"all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),)
}
js = (
("%s/%s" % (settings.STATIC_URL, "paintstore/jquery_1.7.2.js")),
("%s/%s" % (settings.STATIC_URL, "paintstore/colorpicker.js"))
)
input_type = 'colorpicker'
def render(self, name, value, attrs=None):
script = u"""<script type='text/javascript'>
$(document).ready(function(){{
$('#{0}').ColorPicker({{
onSubmit: function(hsb, hex, rgb, el, parent) {{
$(el).val('#' + hex);
$(el).ColorPickerHide();
$('#{0}').css('background-color', '#' + hex);
}},
onBeforeShow: function () {{
$(this).ColorPickerSetColor(this.value);
}}
}}).bind('keyup', function(){{
$(this).ColorPickerSetColor(this.value.replace('#', ''));
}});
$('#{0}').css('background-color', $('#{0}').val());
}});
</script>
""".format(u'id_'+name)
super_render = super(ColorPickerWidget, self).render(name, value, attrs)
return mark_safe(u"%s%s" % (super_render, script))
|
from django import forms
from django.conf import settings
from django.utils.safestring import mark_safe
class ColorPickerWidget(forms.TextInput):
class Media:
css = {
"all": ("%s/%s" % (settings.STATIC_URL, "paintstore/css/colorpicker.css"),)
}
js = (
("%s/%s" % (settings.STATIC_URL, "paintstore/jquery_1.7.2.js")),
("%s/%s" % (settings.STATIC_URL, "paintstore/colorpicker.js"))
)
input_type = 'colorpicker'
def render(self, name, value, attrs=None):
script = u"""<script type='text/javascript'>
- $(document).ready(function(){
+ $(document).ready(function(){{
? +
- $('#%s').ColorPicker({
? ^^
+ $('#{0}').ColorPicker({{
? ^^^ +
- onSubmit: function(hsb, hex, rgb, el, parent) {
+ onSubmit: function(hsb, hex, rgb, el, parent) {{
? +
$(el).val('#' + hex);
$(el).ColorPickerHide();
+ $('#{0}').css('background-color', '#' + hex);
- },
+ }},
? +
- onBeforeShow: function () {
+ onBeforeShow: function () {{
? +
$(this).ColorPickerSetColor(this.value);
- }
+ }}
? +
- }).bind('keyup', function(){
+ }}).bind('keyup', function(){{
? + +
$(this).ColorPickerSetColor(this.value.replace('#', ''));
- });
+ }});
? +
+ $('#{0}').css('background-color', $('#{0}').val());
- });
+ }});
? +
</script>
- """ % ("id_%s" % name,)
+ """.format(u'id_'+name)
super_render = super(ColorPickerWidget, self).render(name, value, attrs)
return mark_safe(u"%s%s" % (super_render, script))
|
633c3a356a0ed88c00fbb1a5c972171de2255890
|
dinosaurs/transaction/database.py
|
dinosaurs/transaction/database.py
|
from peewee import *
db = SqliteDatabase('emails.db')
class Transaction(Model):
cost = FloatField()
address = CharField()
tempPass = CharField()
domain = CharField(index=True)
email = CharField(primary_key=True, unique=True)
is_complete = BooleanField(default=False, index=True)
class Meta:
database = db
|
from datetime import datetime
from peewee import *
from dinosaurs import settings
from dinosaurs.transaction.coin import generate_address
db = SqliteDatabase(settings.database)
class Transaction(Model):
cost = FloatField()
address = CharField()
started = DateField()
tempPass = CharField()
domain = CharField(index=True)
email = CharField(primary_key=True, unique=True)
is_complete = BooleanField(default=False, index=True)
class Meta:
database = db
def __init__(self, *args, **kwargs):
kwargs['started'] = datetime.now()
kwargs['address'] = generate_address()
super(Transaction, self).__init__(*args, **kwargs)
@property
def expired(self):
return (datetime.now() - self.started).minutes > 4
@property
def seconds_left(self):
return (datetime.now() - self.started).total_seconds
|
Update what a transaction is
|
Update what a transaction is
|
Python
|
mit
|
chrisseto/dinosaurs.sexy,chrisseto/dinosaurs.sexy
|
+ from datetime import datetime
+
from peewee import *
+ from dinosaurs import settings
+ from dinosaurs.transaction.coin import generate_address
+
+
- db = SqliteDatabase('emails.db')
+ db = SqliteDatabase(settings.database)
class Transaction(Model):
cost = FloatField()
address = CharField()
+ started = DateField()
tempPass = CharField()
domain = CharField(index=True)
email = CharField(primary_key=True, unique=True)
is_complete = BooleanField(default=False, index=True)
class Meta:
database = db
+ def __init__(self, *args, **kwargs):
+ kwargs['started'] = datetime.now()
+ kwargs['address'] = generate_address()
+ super(Transaction, self).__init__(*args, **kwargs)
+
+ @property
+ def expired(self):
+ return (datetime.now() - self.started).minutes > 4
+
+ @property
+ def seconds_left(self):
+ return (datetime.now() - self.started).total_seconds
+
|
Update what a transaction is
|
## Code Before:
from peewee import *
db = SqliteDatabase('emails.db')
class Transaction(Model):
cost = FloatField()
address = CharField()
tempPass = CharField()
domain = CharField(index=True)
email = CharField(primary_key=True, unique=True)
is_complete = BooleanField(default=False, index=True)
class Meta:
database = db
## Instruction:
Update what a transaction is
## Code After:
from datetime import datetime
from peewee import *
from dinosaurs import settings
from dinosaurs.transaction.coin import generate_address
db = SqliteDatabase(settings.database)
class Transaction(Model):
cost = FloatField()
address = CharField()
started = DateField()
tempPass = CharField()
domain = CharField(index=True)
email = CharField(primary_key=True, unique=True)
is_complete = BooleanField(default=False, index=True)
class Meta:
database = db
def __init__(self, *args, **kwargs):
kwargs['started'] = datetime.now()
kwargs['address'] = generate_address()
super(Transaction, self).__init__(*args, **kwargs)
@property
def expired(self):
return (datetime.now() - self.started).minutes > 4
@property
def seconds_left(self):
return (datetime.now() - self.started).total_seconds
|
+ from datetime import datetime
+
from peewee import *
+ from dinosaurs import settings
+ from dinosaurs.transaction.coin import generate_address
+
+
- db = SqliteDatabase('emails.db')
? ^ ^^ ^ ^
+ db = SqliteDatabase(settings.database)
? ^ ^^ ^^ +++ ^^^
class Transaction(Model):
cost = FloatField()
address = CharField()
+ started = DateField()
tempPass = CharField()
domain = CharField(index=True)
email = CharField(primary_key=True, unique=True)
is_complete = BooleanField(default=False, index=True)
class Meta:
database = db
+
+ def __init__(self, *args, **kwargs):
+ kwargs['started'] = datetime.now()
+ kwargs['address'] = generate_address()
+ super(Transaction, self).__init__(*args, **kwargs)
+
+ @property
+ def expired(self):
+ return (datetime.now() - self.started).minutes > 4
+
+ @property
+ def seconds_left(self):
+ return (datetime.now() - self.started).total_seconds
|
4dc2bb7e2973f39dabb267fb8d6782fe61fe36a9
|
sample/utils.py
|
sample/utils.py
|
import os
def open_lastrun_file(mode='r'):
'''Open and return lastrun file.'''
# path to data directory
data_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data')
os.makedirs(data_dir, exist_ok=True)
# path to lastrun file
lastrun_path = os.path.join(data_dir, 'lastrun.txt')
return open(lastrun_path, mode)
|
import os
def open_lastrun_file(mode='r'):
'''Open and return lastrun file.'''
# path to data directory
data_dir = os.path.expanduser('~/.local/share/classer/')
os.makedirs(data_dir, exist_ok=True)
# path to lastrun file
lastrun_path = os.path.join(data_dir, 'lastrun.txt')
return open(lastrun_path, mode)
|
Change data dir to ~/.local/share/classer
|
Change data dir to ~/.local/share/classer
|
Python
|
mit
|
lqmanh/classer
|
import os
def open_lastrun_file(mode='r'):
'''Open and return lastrun file.'''
# path to data directory
- data_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data')
+ data_dir = os.path.expanduser('~/.local/share/classer/')
os.makedirs(data_dir, exist_ok=True)
# path to lastrun file
lastrun_path = os.path.join(data_dir, 'lastrun.txt')
return open(lastrun_path, mode)
|
Change data dir to ~/.local/share/classer
|
## Code Before:
import os
def open_lastrun_file(mode='r'):
'''Open and return lastrun file.'''
# path to data directory
data_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data')
os.makedirs(data_dir, exist_ok=True)
# path to lastrun file
lastrun_path = os.path.join(data_dir, 'lastrun.txt')
return open(lastrun_path, mode)
## Instruction:
Change data dir to ~/.local/share/classer
## Code After:
import os
def open_lastrun_file(mode='r'):
'''Open and return lastrun file.'''
# path to data directory
data_dir = os.path.expanduser('~/.local/share/classer/')
os.makedirs(data_dir, exist_ok=True)
# path to lastrun file
lastrun_path = os.path.join(data_dir, 'lastrun.txt')
return open(lastrun_path, mode)
|
import os
def open_lastrun_file(mode='r'):
'''Open and return lastrun file.'''
# path to data directory
- data_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data')
+ data_dir = os.path.expanduser('~/.local/share/classer/')
os.makedirs(data_dir, exist_ok=True)
# path to lastrun file
lastrun_path = os.path.join(data_dir, 'lastrun.txt')
return open(lastrun_path, mode)
|
90012f9fb9a256e6086a0b421661fd74cd8ef880
|
sedlex/AddCocoricoVoteVisitor.py
|
sedlex/AddCocoricoVoteVisitor.py
|
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
import requests
class AddCocoricoVoteVisitor(AbstractVisitor):
def __init__(self, args):
self.url = 'https://local.cocorico.cc'
r = requests.post(
self.url + '/api/oauth/token',
auth=(args.cocorico_app_id, args.cocorico_secret),
data={ 'grant_type': 'client_credentials' },
verify=self.url != 'https://local.cocorico.cc'
)
self.access_token = r.json()['access_token']
super(AddCocoricoVoteVisitor, self).__init__()
def visit_node(self, node):
if not self.access_token:
return
# if on root node
if 'parent' not in node and 'type' not in node:
r = requests.post(
self.url + '/api/vote',
headers={'Authorization': 'Bearer ' + self.access_token},
data={
'title': 'test de vote',
'description': 'ceci est un test',
'url': 'https://legilibre.fr/?test=49'
},
verify=self.url != 'https://local.cocorico.cc'
)
node['cocoricoVote'] = r.json()['vote']['id']
|
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
import requests
class AddCocoricoVoteVisitor(AbstractVisitor):
def __init__(self, args):
self.url = args.cocorico_url
if not self.url:
self.url = 'https://cocorico.cc'
r = requests.post(
self.url + '/api/oauth/token',
auth=(args.cocorico_app_id, args.cocorico_secret),
data={ 'grant_type': 'client_credentials' },
verify=self.url != 'https://local.cocorico.cc'
)
self.access_token = r.json()['access_token']
super(AddCocoricoVoteVisitor, self).__init__()
def visit_node(self, node):
if not self.access_token:
return
# if on root node
if 'parent' not in node and 'type' not in node:
r = requests.post(
self.url + '/api/vote',
headers={'Authorization': 'Bearer ' + self.access_token},
data={
'title': 'test de vote',
'description': 'ceci est un test',
'url': 'https://legilibre.fr/?test=49'
},
verify=self.url != 'https://local.cocorico.cc'
)
node['cocoricoVote'] = r.json()['vote']['id']
|
Handle the --cocorico-url command line option.
|
Handle the --cocorico-url command line option.
|
Python
|
agpl-3.0
|
Legilibre/SedLex
|
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
import requests
class AddCocoricoVoteVisitor(AbstractVisitor):
def __init__(self, args):
+ self.url = args.cocorico_url
+ if not self.url:
- self.url = 'https://local.cocorico.cc'
+ self.url = 'https://cocorico.cc'
r = requests.post(
self.url + '/api/oauth/token',
auth=(args.cocorico_app_id, args.cocorico_secret),
data={ 'grant_type': 'client_credentials' },
verify=self.url != 'https://local.cocorico.cc'
)
self.access_token = r.json()['access_token']
super(AddCocoricoVoteVisitor, self).__init__()
def visit_node(self, node):
if not self.access_token:
return
# if on root node
if 'parent' not in node and 'type' not in node:
r = requests.post(
self.url + '/api/vote',
headers={'Authorization': 'Bearer ' + self.access_token},
data={
'title': 'test de vote',
'description': 'ceci est un test',
'url': 'https://legilibre.fr/?test=49'
},
verify=self.url != 'https://local.cocorico.cc'
)
node['cocoricoVote'] = r.json()['vote']['id']
|
Handle the --cocorico-url command line option.
|
## Code Before:
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
import requests
class AddCocoricoVoteVisitor(AbstractVisitor):
def __init__(self, args):
self.url = 'https://local.cocorico.cc'
r = requests.post(
self.url + '/api/oauth/token',
auth=(args.cocorico_app_id, args.cocorico_secret),
data={ 'grant_type': 'client_credentials' },
verify=self.url != 'https://local.cocorico.cc'
)
self.access_token = r.json()['access_token']
super(AddCocoricoVoteVisitor, self).__init__()
def visit_node(self, node):
if not self.access_token:
return
# if on root node
if 'parent' not in node and 'type' not in node:
r = requests.post(
self.url + '/api/vote',
headers={'Authorization': 'Bearer ' + self.access_token},
data={
'title': 'test de vote',
'description': 'ceci est un test',
'url': 'https://legilibre.fr/?test=49'
},
verify=self.url != 'https://local.cocorico.cc'
)
node['cocoricoVote'] = r.json()['vote']['id']
## Instruction:
Handle the --cocorico-url command line option.
## Code After:
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
import requests
class AddCocoricoVoteVisitor(AbstractVisitor):
def __init__(self, args):
self.url = args.cocorico_url
if not self.url:
self.url = 'https://cocorico.cc'
r = requests.post(
self.url + '/api/oauth/token',
auth=(args.cocorico_app_id, args.cocorico_secret),
data={ 'grant_type': 'client_credentials' },
verify=self.url != 'https://local.cocorico.cc'
)
self.access_token = r.json()['access_token']
super(AddCocoricoVoteVisitor, self).__init__()
def visit_node(self, node):
if not self.access_token:
return
# if on root node
if 'parent' not in node and 'type' not in node:
r = requests.post(
self.url + '/api/vote',
headers={'Authorization': 'Bearer ' + self.access_token},
data={
'title': 'test de vote',
'description': 'ceci est un test',
'url': 'https://legilibre.fr/?test=49'
},
verify=self.url != 'https://local.cocorico.cc'
)
node['cocoricoVote'] = r.json()['vote']['id']
|
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
import requests
class AddCocoricoVoteVisitor(AbstractVisitor):
def __init__(self, args):
+ self.url = args.cocorico_url
+ if not self.url:
- self.url = 'https://local.cocorico.cc'
? ------
+ self.url = 'https://cocorico.cc'
? ++++
r = requests.post(
self.url + '/api/oauth/token',
auth=(args.cocorico_app_id, args.cocorico_secret),
data={ 'grant_type': 'client_credentials' },
verify=self.url != 'https://local.cocorico.cc'
)
self.access_token = r.json()['access_token']
super(AddCocoricoVoteVisitor, self).__init__()
def visit_node(self, node):
if not self.access_token:
return
# if on root node
if 'parent' not in node and 'type' not in node:
r = requests.post(
self.url + '/api/vote',
headers={'Authorization': 'Bearer ' + self.access_token},
data={
'title': 'test de vote',
'description': 'ceci est un test',
'url': 'https://legilibre.fr/?test=49'
},
verify=self.url != 'https://local.cocorico.cc'
)
node['cocoricoVote'] = r.json()['vote']['id']
|
7c8a256f5d87ae70ac3f187f0010a8d66d8b95d5
|
seabird/modules/metar.py
|
seabird/modules/metar.py
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = ('http://weather.noaa.gov/pub/data'
'/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
Fix a line too long lint error
|
Fix a line too long lint error
|
Python
|
mit
|
belak/python-seabird,belak/pyseabird
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
- METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
+ METAR_URL = ('http://weather.noaa.gov/pub/data'
+ '/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
Fix a line too long lint error
|
## Code Before:
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
## Instruction:
Fix a line too long lint error
## Code After:
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = ('http://weather.noaa.gov/pub/data'
'/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
- METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
+ METAR_URL = ('http://weather.noaa.gov/pub/data'
+ '/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
0b1d2a43e4f9858bcb9d9bf9edf3dfae417f133d
|
satchless/util/__init__.py
|
satchless/util/__init__.py
|
from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
def handle_decimal(self, o):
if isinstance(o, Decimal):
return float(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
|
from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
class UndercoverDecimal(float):
'''
A horrible hack that lets us encode Decimals as numbers.
Do not do this at home.
'''
def __init__(self, value):
self.value = value
def __repr__(self):
return str(self.value)
def handle_decimal(self, o):
if isinstance(o, Decimal):
return self.UndercoverDecimal(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
|
Add a huge hack to treat Decimals like floats
|
Add a huge hack to treat Decimals like floats
This commit provided to you by highly trained professional stuntmen,
do not try to reproduce any of this at home!
|
Python
|
bsd-3-clause
|
taedori81/satchless,fusionbox/satchless,fusionbox/satchless,fusionbox/satchless
|
from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
+ class UndercoverDecimal(float):
+ '''
+ A horrible hack that lets us encode Decimals as numbers.
+ Do not do this at home.
+ '''
+
+ def __init__(self, value):
+ self.value = value
+
+ def __repr__(self):
+ return str(self.value)
+
def handle_decimal(self, o):
if isinstance(o, Decimal):
- return float(o)
+ return self.UndercoverDecimal(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
|
Add a huge hack to treat Decimals like floats
|
## Code Before:
from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
def handle_decimal(self, o):
if isinstance(o, Decimal):
return float(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
## Instruction:
Add a huge hack to treat Decimals like floats
## Code After:
from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
class UndercoverDecimal(float):
'''
A horrible hack that lets us encode Decimals as numbers.
Do not do this at home.
'''
def __init__(self, value):
self.value = value
def __repr__(self):
return str(self.value)
def handle_decimal(self, o):
if isinstance(o, Decimal):
return self.UndercoverDecimal(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
|
from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
+ class UndercoverDecimal(float):
+ '''
+ A horrible hack that lets us encode Decimals as numbers.
+ Do not do this at home.
+ '''
+
+ def __init__(self, value):
+ self.value = value
+
+ def __repr__(self):
+ return str(self.value)
+
def handle_decimal(self, o):
if isinstance(o, Decimal):
- return float(o)
+ return self.UndercoverDecimal(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
|
d63509e0d68a1dceabbbcf58432a92f7a4cbfd77
|
robot/robot/src/autonomous/main.py
|
robot/robot/src/autonomous/main.py
|
try:
import wpilib
except ImportError:
from pyfrc import wpilib
# import components here
from components import drive, intake, catapult
class MyRobot(wpilib.SimpleRobot):
def __init__ (self):
super().__init__()
print("Team 1418 robot code for 2014")
#################################################################
# THIS CODE IS SHARED BETWEEN THE MAIN ROBOT AND THE ELECTRICAL #
# TEST CODE. WHEN CHANGING IT, CHANGE BOTH PLACES! #
#################################################################
wpilib.SmartDashboard.init()
|
try:
import wpilib
except ImportError:
from pyfrc import wpilib
# import components here
from components import drive, intake, catapult
class MyRobot(wpilib.SimpleRobot):
def __init__ (self, drive, intake, catapult):
super().__init__()
print("Team 1418 autonomous code for 2014")
#################################################################
# THIS CODE IS SHARED BETWEEN THE MAIN ROBOT AND THE ELECTRICAL #
# TEST CODE. WHEN CHANGING IT, CHANGE BOTH PLACES! #
#################################################################
wpilib.SmartDashboard.init()
def on_enable(self):
time = wpilib.Timer()
timer.Start()
update (self, timer)
def on_disable(self):
'''This function is called when autonomous mode is disabled'''
pass
def update(self, time_elapsed):
self.Compressor.Start()
self.intake.armDown()
self.catapult.pulldown()
self.robot.winch_motor.Set(0)
self.drive.move(self,0,-1,0)
self.catapult.launch()
self.catapult.pulldown()
self.robot.winch_motor.Set(0)
if self.robot.ball_sensor!=.4:
self.intake.wheels()
self.drive.move(self,0,1,0)
elif self.robot.ball_sensor==.4:
self.drive.move(self,0,-1,0)
self.catapult.launch()
'''Do not implement your own loop for autonomous mode. Instead,
assume that
this function is called over and over and over again during
autonomous
mode if this mode is active
time_elapsed is a number that tells you how many seconds
autonomous mode has
been running so far.
'''
|
Bring the autonomous mode back
|
Bring the autonomous mode back
|
Python
|
bsd-3-clause
|
frc1418/2014
|
try:
import wpilib
except ImportError:
from pyfrc import wpilib
# import components here
from components import drive, intake, catapult
class MyRobot(wpilib.SimpleRobot):
- def __init__ (self):
+ def __init__ (self, drive, intake, catapult):
super().__init__()
- print("Team 1418 robot code for 2014")
+ print("Team 1418 autonomous code for 2014")
#################################################################
# THIS CODE IS SHARED BETWEEN THE MAIN ROBOT AND THE ELECTRICAL #
# TEST CODE. WHEN CHANGING IT, CHANGE BOTH PLACES! #
#################################################################
- wpilib.SmartDashboard.init()
+ wpilib.SmartDashboard.init()
+
+
+
+ def on_enable(self):
+ time = wpilib.Timer()
+ timer.Start()
+ update (self, timer)
+ def on_disable(self):
+ '''This function is called when autonomous mode is disabled'''
+ pass
+
+ def update(self, time_elapsed):
+ self.Compressor.Start()
+ self.intake.armDown()
+ self.catapult.pulldown()
+ self.robot.winch_motor.Set(0)
+ self.drive.move(self,0,-1,0)
+ self.catapult.launch()
+ self.catapult.pulldown()
+ self.robot.winch_motor.Set(0)
+ if self.robot.ball_sensor!=.4:
+ self.intake.wheels()
+ self.drive.move(self,0,1,0)
+ elif self.robot.ball_sensor==.4:
+ self.drive.move(self,0,-1,0)
+ self.catapult.launch()
+
+
+
+ '''Do not implement your own loop for autonomous mode. Instead,
+ assume that
+ this function is called over and over and over again during
+ autonomous
+ mode if this mode is active
+
+ time_elapsed is a number that tells you how many seconds
+ autonomous mode has
+ been running so far.
+ '''
+
+
|
Bring the autonomous mode back
|
## Code Before:
try:
import wpilib
except ImportError:
from pyfrc import wpilib
# import components here
from components import drive, intake, catapult
class MyRobot(wpilib.SimpleRobot):
def __init__ (self):
super().__init__()
print("Team 1418 robot code for 2014")
#################################################################
# THIS CODE IS SHARED BETWEEN THE MAIN ROBOT AND THE ELECTRICAL #
# TEST CODE. WHEN CHANGING IT, CHANGE BOTH PLACES! #
#################################################################
wpilib.SmartDashboard.init()
## Instruction:
Bring the autonomous mode back
## Code After:
try:
import wpilib
except ImportError:
from pyfrc import wpilib
# import components here
from components import drive, intake, catapult
class MyRobot(wpilib.SimpleRobot):
def __init__ (self, drive, intake, catapult):
super().__init__()
print("Team 1418 autonomous code for 2014")
#################################################################
# THIS CODE IS SHARED BETWEEN THE MAIN ROBOT AND THE ELECTRICAL #
# TEST CODE. WHEN CHANGING IT, CHANGE BOTH PLACES! #
#################################################################
wpilib.SmartDashboard.init()
def on_enable(self):
time = wpilib.Timer()
timer.Start()
update (self, timer)
def on_disable(self):
'''This function is called when autonomous mode is disabled'''
pass
def update(self, time_elapsed):
self.Compressor.Start()
self.intake.armDown()
self.catapult.pulldown()
self.robot.winch_motor.Set(0)
self.drive.move(self,0,-1,0)
self.catapult.launch()
self.catapult.pulldown()
self.robot.winch_motor.Set(0)
if self.robot.ball_sensor!=.4:
self.intake.wheels()
self.drive.move(self,0,1,0)
elif self.robot.ball_sensor==.4:
self.drive.move(self,0,-1,0)
self.catapult.launch()
'''Do not implement your own loop for autonomous mode. Instead,
assume that
this function is called over and over and over again during
autonomous
mode if this mode is active
time_elapsed is a number that tells you how many seconds
autonomous mode has
been running so far.
'''
|
try:
import wpilib
except ImportError:
from pyfrc import wpilib
# import components here
from components import drive, intake, catapult
class MyRobot(wpilib.SimpleRobot):
- def __init__ (self):
+ def __init__ (self, drive, intake, catapult):
super().__init__()
- print("Team 1418 robot code for 2014")
? ^ ^ ^
+ print("Team 1418 autonomous code for 2014")
? ^^^ ^ ^^^^
#################################################################
# THIS CODE IS SHARED BETWEEN THE MAIN ROBOT AND THE ELECTRICAL #
# TEST CODE. WHEN CHANGING IT, CHANGE BOTH PLACES! #
#################################################################
wpilib.SmartDashboard.init()
+
+
+
+ def on_enable(self):
+ time = wpilib.Timer()
+ timer.Start()
+ update (self, timer)
+ def on_disable(self):
+ '''This function is called when autonomous mode is disabled'''
+ pass
+
+ def update(self, time_elapsed):
+ self.Compressor.Start()
+ self.intake.armDown()
+ self.catapult.pulldown()
+ self.robot.winch_motor.Set(0)
+ self.drive.move(self,0,-1,0)
+ self.catapult.launch()
+ self.catapult.pulldown()
+ self.robot.winch_motor.Set(0)
+ if self.robot.ball_sensor!=.4:
+ self.intake.wheels()
+ self.drive.move(self,0,1,0)
+ elif self.robot.ball_sensor==.4:
+ self.drive.move(self,0,-1,0)
+ self.catapult.launch()
+
+
+
+ '''Do not implement your own loop for autonomous mode. Instead,
+ assume that
+ this function is called over and over and over again during
+ autonomous
+ mode if this mode is active
+
+ time_elapsed is a number that tells you how many seconds
+ autonomous mode has
+ been running so far.
+ '''
+
+
|
e230837f473808b3c136862feefdd6660ebb77e8
|
scripts/examples/14-WiFi-Shield/mqtt.py
|
scripts/examples/14-WiFi-Shield/mqtt.py
|
import time, network
from mqtt import MQTTClient
SSID='mux' # Network SSID
KEY='j806fVnT7tObdCYE' # Network key
# Init wlan module and connect to network
print("Trying to connect... (may take a while)...")
wlan = network.WINC()
wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK)
# We should have a valid IP now via DHCP
print(wlan.ifconfig())
client = MQTTClient("openmv", "test.mosquitto.org", port=1883)
client.connect()
while (True):
client.publish("openmv/test", "Hello World!")
time.sleep(1000)
|
import time, network
from mqtt import MQTTClient
SSID='' # Network SSID
KEY='' # Network key
# Init wlan module and connect to network
print("Trying to connect... (may take a while)...")
wlan = network.WINC()
wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK)
# We should have a valid IP now via DHCP
print(wlan.ifconfig())
client = MQTTClient("openmv", "test.mosquitto.org", port=1883)
client.connect()
while (True):
client.publish("openmv/test", "Hello World!")
time.sleep(1000)
|
Remove ssid/key from example script.
|
Remove ssid/key from example script.
|
Python
|
mit
|
kwagyeman/openmv,iabdalkader/openmv,iabdalkader/openmv,openmv/openmv,iabdalkader/openmv,iabdalkader/openmv,kwagyeman/openmv,kwagyeman/openmv,openmv/openmv,openmv/openmv,openmv/openmv,kwagyeman/openmv
|
import time, network
from mqtt import MQTTClient
- SSID='mux' # Network SSID
+ SSID='' # Network SSID
- KEY='j806fVnT7tObdCYE' # Network key
+ KEY='' # Network key
# Init wlan module and connect to network
print("Trying to connect... (may take a while)...")
wlan = network.WINC()
wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK)
# We should have a valid IP now via DHCP
print(wlan.ifconfig())
client = MQTTClient("openmv", "test.mosquitto.org", port=1883)
client.connect()
while (True):
client.publish("openmv/test", "Hello World!")
time.sleep(1000)
|
Remove ssid/key from example script.
|
## Code Before:
import time, network
from mqtt import MQTTClient
SSID='mux' # Network SSID
KEY='j806fVnT7tObdCYE' # Network key
# Init wlan module and connect to network
print("Trying to connect... (may take a while)...")
wlan = network.WINC()
wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK)
# We should have a valid IP now via DHCP
print(wlan.ifconfig())
client = MQTTClient("openmv", "test.mosquitto.org", port=1883)
client.connect()
while (True):
client.publish("openmv/test", "Hello World!")
time.sleep(1000)
## Instruction:
Remove ssid/key from example script.
## Code After:
import time, network
from mqtt import MQTTClient
SSID='' # Network SSID
KEY='' # Network key
# Init wlan module and connect to network
print("Trying to connect... (may take a while)...")
wlan = network.WINC()
wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK)
# We should have a valid IP now via DHCP
print(wlan.ifconfig())
client = MQTTClient("openmv", "test.mosquitto.org", port=1883)
client.connect()
while (True):
client.publish("openmv/test", "Hello World!")
time.sleep(1000)
|
import time, network
from mqtt import MQTTClient
- SSID='mux' # Network SSID
? ---
+ SSID='' # Network SSID
- KEY='j806fVnT7tObdCYE' # Network key
+ KEY='' # Network key
# Init wlan module and connect to network
print("Trying to connect... (may take a while)...")
wlan = network.WINC()
wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK)
# We should have a valid IP now via DHCP
print(wlan.ifconfig())
client = MQTTClient("openmv", "test.mosquitto.org", port=1883)
client.connect()
while (True):
client.publish("openmv/test", "Hello World!")
time.sleep(1000)
|
1eedac5229e5a9128c4fbc09f7d7b97a3859e9b9
|
django_sse/views.py
|
django_sse/views.py
|
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import Sse
class BaseSseView(View):
"""
This is a base class for sse streaming.
"""
def get_last_id(self):
if "HTTP_LAST_EVENT_ID" in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
self.kwargs = kwargs
response = HttpResponse(self._iterator(), content_type="text/event-stream")
response['Cache-Control'] = 'no-cache'
response['Software'] = 'django-sse'
return response
def iterator(self):
"""
This is a source of stream.
Must be use sentence ``yield`` for flush
content fon sse object to the client.
Example:
def iterator(self):
counter = 0
while True:
self.sse.add_message('foo', 'bar')
self.sse.add_message('bar', 'foo')
yield
"""
raise NotImplementedError
|
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import Sse
class BaseSseView(View):
"""
This is a base class for sse streaming.
"""
def get_last_id(self):
if "HTTP_LAST_EVENT_ID" in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
self.kwargs = kwargs
response = HttpResponse(self._iterator(), content_type="text/event-stream")
response['Cache-Control'] = 'no-cache'
response['Software'] = 'django-sse'
return response
def iterator(self):
"""
This is a source of stream.
Must be use sentence ``yield`` for flush
content fon sse object to the client.
Example:
def iterator(self):
counter = 0
while True:
self.sse.add_message('foo', 'bar')
self.sse.add_message('bar', 'foo')
yield
"""
raise NotImplementedError
|
Remove duplicate import. (Thanks to MechanisM)
|
Remove duplicate import. (Thanks to MechanisM)
|
Python
|
bsd-3-clause
|
chadmiller/django-sse,niwinz/django-sse,chadmiller/django-sse
|
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
- from django.http import HttpResponse
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import Sse
class BaseSseView(View):
"""
This is a base class for sse streaming.
"""
def get_last_id(self):
if "HTTP_LAST_EVENT_ID" in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
self.kwargs = kwargs
response = HttpResponse(self._iterator(), content_type="text/event-stream")
response['Cache-Control'] = 'no-cache'
response['Software'] = 'django-sse'
return response
def iterator(self):
"""
This is a source of stream.
Must be use sentence ``yield`` for flush
content fon sse object to the client.
Example:
def iterator(self):
counter = 0
while True:
self.sse.add_message('foo', 'bar')
self.sse.add_message('bar', 'foo')
yield
"""
raise NotImplementedError
|
Remove duplicate import. (Thanks to MechanisM)
|
## Code Before:
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import Sse
class BaseSseView(View):
"""
This is a base class for sse streaming.
"""
def get_last_id(self):
if "HTTP_LAST_EVENT_ID" in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
self.kwargs = kwargs
response = HttpResponse(self._iterator(), content_type="text/event-stream")
response['Cache-Control'] = 'no-cache'
response['Software'] = 'django-sse'
return response
def iterator(self):
"""
This is a source of stream.
Must be use sentence ``yield`` for flush
content fon sse object to the client.
Example:
def iterator(self):
counter = 0
while True:
self.sse.add_message('foo', 'bar')
self.sse.add_message('bar', 'foo')
yield
"""
raise NotImplementedError
## Instruction:
Remove duplicate import. (Thanks to MechanisM)
## Code After:
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import Sse
class BaseSseView(View):
"""
This is a base class for sse streaming.
"""
def get_last_id(self):
if "HTTP_LAST_EVENT_ID" in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
self.kwargs = kwargs
response = HttpResponse(self._iterator(), content_type="text/event-stream")
response['Cache-Control'] = 'no-cache'
response['Software'] = 'django-sse'
return response
def iterator(self):
"""
This is a source of stream.
Must be use sentence ``yield`` for flush
content fon sse object to the client.
Example:
def iterator(self):
counter = 0
while True:
self.sse.add_message('foo', 'bar')
self.sse.add_message('bar', 'foo')
yield
"""
raise NotImplementedError
|
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
- from django.http import HttpResponse
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import Sse
class BaseSseView(View):
"""
This is a base class for sse streaming.
"""
def get_last_id(self):
if "HTTP_LAST_EVENT_ID" in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None
def _iterator(self):
for subiterator in self.iterator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
self.kwargs = kwargs
response = HttpResponse(self._iterator(), content_type="text/event-stream")
response['Cache-Control'] = 'no-cache'
response['Software'] = 'django-sse'
return response
def iterator(self):
"""
This is a source of stream.
Must be use sentence ``yield`` for flush
content fon sse object to the client.
Example:
def iterator(self):
counter = 0
while True:
self.sse.add_message('foo', 'bar')
self.sse.add_message('bar', 'foo')
yield
"""
raise NotImplementedError
|
47c50f9e3f8c0643e0e76cd60fa5694701e73afe
|
scanner/ScannerApplication.py
|
scanner/ScannerApplication.py
|
from Cura.Application import Application
class ScannerApplication(Application):
def __init__(self):
super(ScannerApplication, self).__init__()
self._plugin_registry.loadPlugin("STLReader")
self._plugin_registry.loadPlugin("STLWriter")
self._plugin_registry.loadPlugin("MeshView")
self._plugin_registry.loadPlugin("TransformTool")
def run(self):
print("Imma scanning ma laz0rs")
|
from Cura.WxApplication import WxApplication
class ScannerApplication(WxApplication):
def __init__(self):
super(ScannerApplication, self).__init__()
self._plugin_registry.loadPlugin("STLReader")
self._plugin_registry.loadPlugin("STLWriter")
self._plugin_registry.loadPlugin("MeshView")
self._plugin_registry.loadPlugin("TransformTool")
def run(self):
print("Imma scanning ma laz0rs")
super(ScannerApplication, self).run()
|
Use WxApplication as base class for the scanner
|
Use WxApplication as base class for the scanner
|
Python
|
agpl-3.0
|
onitake/Uranium,onitake/Uranium
|
- from Cura.Application import Application
+ from Cura.WxApplication import WxApplication
- class ScannerApplication(Application):
+ class ScannerApplication(WxApplication):
def __init__(self):
super(ScannerApplication, self).__init__()
self._plugin_registry.loadPlugin("STLReader")
self._plugin_registry.loadPlugin("STLWriter")
self._plugin_registry.loadPlugin("MeshView")
self._plugin_registry.loadPlugin("TransformTool")
def run(self):
print("Imma scanning ma laz0rs")
+ super(ScannerApplication, self).run()
|
Use WxApplication as base class for the scanner
|
## Code Before:
from Cura.Application import Application
class ScannerApplication(Application):
def __init__(self):
super(ScannerApplication, self).__init__()
self._plugin_registry.loadPlugin("STLReader")
self._plugin_registry.loadPlugin("STLWriter")
self._plugin_registry.loadPlugin("MeshView")
self._plugin_registry.loadPlugin("TransformTool")
def run(self):
print("Imma scanning ma laz0rs")
## Instruction:
Use WxApplication as base class for the scanner
## Code After:
from Cura.WxApplication import WxApplication
class ScannerApplication(WxApplication):
def __init__(self):
super(ScannerApplication, self).__init__()
self._plugin_registry.loadPlugin("STLReader")
self._plugin_registry.loadPlugin("STLWriter")
self._plugin_registry.loadPlugin("MeshView")
self._plugin_registry.loadPlugin("TransformTool")
def run(self):
print("Imma scanning ma laz0rs")
super(ScannerApplication, self).run()
|
- from Cura.Application import Application
+ from Cura.WxApplication import WxApplication
? ++ ++
- class ScannerApplication(Application):
+ class ScannerApplication(WxApplication):
? ++
def __init__(self):
super(ScannerApplication, self).__init__()
self._plugin_registry.loadPlugin("STLReader")
self._plugin_registry.loadPlugin("STLWriter")
self._plugin_registry.loadPlugin("MeshView")
self._plugin_registry.loadPlugin("TransformTool")
def run(self):
print("Imma scanning ma laz0rs")
+ super(ScannerApplication, self).run()
|
24b78a4d510606563106da24d568d5fb79ddca2b
|
IPython/__main__.py
|
IPython/__main__.py
|
#-----------------------------------------------------------------------------
# Copyright (c) 2012, IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
from IPython.terminal.ipapp import launch_new_instance
launch_new_instance()
|
#-----------------------------------------------------------------------------
# Copyright (c) 2012, IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
from IPython import start_ipython
start_ipython()
|
Use new entry point for python -m IPython
|
Use new entry point for python -m IPython
|
Python
|
bsd-3-clause
|
ipython/ipython,ipython/ipython
|
#-----------------------------------------------------------------------------
# Copyright (c) 2012, IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
- from IPython.terminal.ipapp import launch_new_instance
+ from IPython import start_ipython
- launch_new_instance()
+ start_ipython()
|
Use new entry point for python -m IPython
|
## Code Before:
#-----------------------------------------------------------------------------
# Copyright (c) 2012, IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
from IPython.terminal.ipapp import launch_new_instance
launch_new_instance()
## Instruction:
Use new entry point for python -m IPython
## Code After:
#-----------------------------------------------------------------------------
# Copyright (c) 2012, IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
from IPython import start_ipython
start_ipython()
|
#-----------------------------------------------------------------------------
# Copyright (c) 2012, IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
- from IPython.terminal.ipapp import launch_new_instance
+ from IPython import start_ipython
- launch_new_instance()
+ start_ipython()
|
d81c64f68aa47581aa8207f858aec8af1bb805d9
|
wallace/sources.py
|
wallace/sources.py
|
from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def create_information(self, what=None, to_whom=None):
"""Generate new information."""
raise NotImplementedError(
"You need to overwrite the default create_information.")
def transmit(self, what=None, to_whom=None):
self.create_information(what=what, to_whom=to_whom)
super(Source, self).transmit(to_whom=to_whom, what=what)
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
def create_information(self, what=None, to_whom=None):
Info(
origin=self,
origin_uuid=self.uuid,
contents=self._binary_string())
def _binary_string(self):
return "".join([str(random.randint(0, 1)) for i in range(2)])
|
from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def create_information(self):
"""Generate new information."""
raise NotImplementedError(
"You need to overwrite the default create_information.")
def transmit(self, what=None, to_whom=None):
info = self.create_information()
super(Source, self).transmit(to_whom=to_whom, what=info)
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
def create_information(self):
info = Info(
origin=self,
origin_uuid=self.uuid,
contents=self._binary_string())
return info
def _binary_string(self):
return "".join([str(random.randint(0, 1)) for i in range(2)])
|
Fix bug that arose through grammar tweaking
|
Fix bug that arose through grammar tweaking
|
Python
|
mit
|
jcpeterson/Dallinger,berkeley-cocosci/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,suchow/Wallace,suchow/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,suchow/Wallace,berkeley-cocosci/Wallace,Dallinger/Dallinger,berkeley-cocosci/Wallace
|
from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
- def create_information(self, what=None, to_whom=None):
+ def create_information(self):
"""Generate new information."""
raise NotImplementedError(
"You need to overwrite the default create_information.")
def transmit(self, what=None, to_whom=None):
- self.create_information(what=what, to_whom=to_whom)
+ info = self.create_information()
- super(Source, self).transmit(to_whom=to_whom, what=what)
+ super(Source, self).transmit(to_whom=to_whom, what=info)
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
- def create_information(self, what=None, to_whom=None):
+ def create_information(self):
- Info(
+ info = Info(
origin=self,
origin_uuid=self.uuid,
contents=self._binary_string())
+ return info
def _binary_string(self):
return "".join([str(random.randint(0, 1)) for i in range(2)])
|
Fix bug that arose through grammar tweaking
|
## Code Before:
from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def create_information(self, what=None, to_whom=None):
"""Generate new information."""
raise NotImplementedError(
"You need to overwrite the default create_information.")
def transmit(self, what=None, to_whom=None):
self.create_information(what=what, to_whom=to_whom)
super(Source, self).transmit(to_whom=to_whom, what=what)
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
def create_information(self, what=None, to_whom=None):
Info(
origin=self,
origin_uuid=self.uuid,
contents=self._binary_string())
def _binary_string(self):
return "".join([str(random.randint(0, 1)) for i in range(2)])
## Instruction:
Fix bug that arose through grammar tweaking
## Code After:
from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
def create_information(self):
"""Generate new information."""
raise NotImplementedError(
"You need to overwrite the default create_information.")
def transmit(self, what=None, to_whom=None):
info = self.create_information()
super(Source, self).transmit(to_whom=to_whom, what=info)
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
def create_information(self):
info = Info(
origin=self,
origin_uuid=self.uuid,
contents=self._binary_string())
return info
def _binary_string(self):
return "".join([str(random.randint(0, 1)) for i in range(2)])
|
from .models import Node, Info
from sqlalchemy import ForeignKey, Column, String
import random
class Source(Node):
__tablename__ = "source"
__mapper_args__ = {"polymorphic_identity": "generic_source"}
uuid = Column(String(32), ForeignKey("node.uuid"), primary_key=True)
- def create_information(self, what=None, to_whom=None):
+ def create_information(self):
"""Generate new information."""
raise NotImplementedError(
"You need to overwrite the default create_information.")
def transmit(self, what=None, to_whom=None):
- self.create_information(what=what, to_whom=to_whom)
+ info = self.create_information()
- super(Source, self).transmit(to_whom=to_whom, what=what)
? ^^^^
+ super(Source, self).transmit(to_whom=to_whom, what=info)
? ^^^^
class RandomBinaryStringSource(Source):
"""An agent whose genome and memome are random binary strings. The source
only transmits; it does not update.
"""
__mapper_args__ = {"polymorphic_identity": "random_binary_string_source"}
- def create_information(self, what=None, to_whom=None):
+ def create_information(self):
- Info(
+ info = Info(
? +++++++
origin=self,
origin_uuid=self.uuid,
contents=self._binary_string())
+ return info
def _binary_string(self):
return "".join([str(random.randint(0, 1)) for i in range(2)])
|
0ba44cc7a8e906be42d98599b59e28ad142648b7
|
blogApp/forms/upload_image.py
|
blogApp/forms/upload_image.py
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import FormActions, Div
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_class = 'form-horizontal'
helper.label_class = 'col-xs-3'
helper.field_class = 'col-xs-9'
title = forms.CharField(
label = "Alt. Title",
required = True,
max_length=50,
)
image = forms.FileField(
label = "Image",
required = True,
)
resize = forms.IntegerField(
label = "Resize to this width or height",
initial = 1000,
required = True,
)
helper.layout = Layout(
Field('title'),
Field('image'),
Field('resize'),
Div(
FormActions(
HTML('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'),
Submit('save', 'Upload'),
),
css_class="modal-footer"
),
)
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import FormActions, Div, AppendedText
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_class = 'form-horizontal'
helper.label_class = 'col-xs-3'
helper.field_class = 'col-xs-9'
title = forms.CharField(
label = "Alt. Title",
required = True,
max_length=50,
)
image = forms.FileField(
label = "Image",
required = True,
)
resize = forms.IntegerField(
label = "Resize to this width or height",
initial = 1000,
required = True,
)
helper.layout = Layout(
Field('title'),
Field('image'),
AppendedText('resize', 'px'),
Div(
FormActions(
HTML('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'),
Submit('save', 'Upload'),
),
css_class="modal-footer"
),
)
|
Append 'px' to end of image upload form resize field
|
Append 'px' to end of image upload form resize field
|
Python
|
mit
|
SPARLab/BikeMaps,SPARLab/BikeMaps,SPARLab/BikeMaps
|
from django import forms
from crispy_forms.helper import FormHelper
- from crispy_forms.bootstrap import FormActions, Div
+ from crispy_forms.bootstrap import FormActions, Div, AppendedText
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_class = 'form-horizontal'
helper.label_class = 'col-xs-3'
helper.field_class = 'col-xs-9'
title = forms.CharField(
label = "Alt. Title",
required = True,
max_length=50,
)
image = forms.FileField(
label = "Image",
required = True,
)
resize = forms.IntegerField(
label = "Resize to this width or height",
initial = 1000,
required = True,
)
helper.layout = Layout(
Field('title'),
Field('image'),
- Field('resize'),
+ AppendedText('resize', 'px'),
Div(
FormActions(
HTML('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'),
Submit('save', 'Upload'),
),
css_class="modal-footer"
),
)
|
Append 'px' to end of image upload form resize field
|
## Code Before:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import FormActions, Div
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_class = 'form-horizontal'
helper.label_class = 'col-xs-3'
helper.field_class = 'col-xs-9'
title = forms.CharField(
label = "Alt. Title",
required = True,
max_length=50,
)
image = forms.FileField(
label = "Image",
required = True,
)
resize = forms.IntegerField(
label = "Resize to this width or height",
initial = 1000,
required = True,
)
helper.layout = Layout(
Field('title'),
Field('image'),
Field('resize'),
Div(
FormActions(
HTML('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'),
Submit('save', 'Upload'),
),
css_class="modal-footer"
),
)
## Instruction:
Append 'px' to end of image upload form resize field
## Code After:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import FormActions, Div, AppendedText
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_class = 'form-horizontal'
helper.label_class = 'col-xs-3'
helper.field_class = 'col-xs-9'
title = forms.CharField(
label = "Alt. Title",
required = True,
max_length=50,
)
image = forms.FileField(
label = "Image",
required = True,
)
resize = forms.IntegerField(
label = "Resize to this width or height",
initial = 1000,
required = True,
)
helper.layout = Layout(
Field('title'),
Field('image'),
AppendedText('resize', 'px'),
Div(
FormActions(
HTML('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'),
Submit('save', 'Upload'),
),
css_class="modal-footer"
),
)
|
from django import forms
from crispy_forms.helper import FormHelper
- from crispy_forms.bootstrap import FormActions, Div
+ from crispy_forms.bootstrap import FormActions, Div, AppendedText
? ++++++++++++++
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_class = 'form-horizontal'
helper.label_class = 'col-xs-3'
helper.field_class = 'col-xs-9'
title = forms.CharField(
label = "Alt. Title",
required = True,
max_length=50,
)
image = forms.FileField(
label = "Image",
required = True,
)
resize = forms.IntegerField(
label = "Resize to this width or height",
initial = 1000,
required = True,
)
helper.layout = Layout(
Field('title'),
Field('image'),
- Field('resize'),
+ AppendedText('resize', 'px'),
Div(
FormActions(
HTML('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'),
Submit('save', 'Upload'),
),
css_class="modal-footer"
),
)
|
74f26f0c0a0cb014539212f5b7a703d436b29f29
|
backend/globaleaks/jobs/base.py
|
backend/globaleaks/jobs/base.py
|
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
try:
self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
def operation(self):
pass # dummy skel for GLJob objects
|
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
ret = None
try:
ret = self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
return ret
def operation(self):
pass # dummy skel for GLJob objects
|
Patch job scheduler avoiding possibilities for concurrent runs of the same
|
Patch job scheduler avoiding possibilities for concurrent runs of the same
|
Python
|
agpl-3.0
|
vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks
|
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
+ ret = None
+
try:
- self.operation()
+ ret = self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
+ return ret
+
def operation(self):
pass # dummy skel for GLJob objects
|
Patch job scheduler avoiding possibilities for concurrent runs of the same
|
## Code Before:
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
try:
self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
def operation(self):
pass # dummy skel for GLJob objects
## Instruction:
Patch job scheduler avoiding possibilities for concurrent runs of the same
## Code After:
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
ret = None
try:
ret = self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
return ret
def operation(self):
pass # dummy skel for GLJob objects
|
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
+ ret = None
+
try:
- self.operation()
+ ret = self.operation()
? ++++++
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
+ return ret
+
def operation(self):
pass # dummy skel for GLJob objects
|
788229f43eab992d6f4d79681604336e4d721b0c
|
gameserver/api/endpoints/players.py
|
gameserver/api/endpoints/players.py
|
import logging
from flask import request
from flask_restplus import Resource
from gameserver.game import Game
from gameserver.models import Player
from gameserver.api.restplus import api
from gameserver.api.serializers import player_get, player_post
from gameserver.database import db
db_session = db.session
log = logging.getLogger(__name__)
ns = api.namespace('players', description='Operations related to players')
game = Game()
@ns.route('/')
class PlayerCollection(Resource):
@api.response(200, 'Success')
@api.marshal_list_with(player_get)
def get(self):
"""
Returns list of players.
"""
players = game.get_players()
return players
@api.response(201, 'Player successfully created.')
@api.expect(player_post)
def post(self):
"""
Creates a new game player.
"""
data = request.json
player = game.create_player(data['name'])
db_session.commit()
return player.id, 201
@ns.route('/<string:id>')
@ns.param('id', 'The player id')
class Player(Resource):
@api.response(404, 'Player not found')
@api.response(200, 'Success')
@api.marshal_with(player_get)
def get(self, id):
"""
Returns the specified player.
"""
player = game.get_player(id)
if not player:
api.abort(404)
return player
|
import logging
from flask import request
from flask_restplus import Resource
from gameserver.game import Game
from gameserver.models import Player
from gameserver.api.restplus import api
from gameserver.api.serializers import player_get, player_post
from gameserver.database import db
db_session = db.session
log = logging.getLogger(__name__)
ns = api.namespace('players', description='Operations related to players')
game = Game()
@ns.route('/')
class PlayerCollection(Resource):
@api.response(200, 'Success')
@api.marshal_list_with(player_get)
def get(self):
"""
Returns list of players.
"""
players = game.get_players()
return players
@api.response(201, 'Player successfully created.')
@api.expect(player_post)
def post(self):
"""
Creates a new game player.
"""
data = request.json
player = game.create_player(data['name'])
db_session.commit()
return dict(id=player.id), 201
@ns.route('/<string:id>')
@ns.param('id', 'The player id')
class Player(Resource):
@api.response(404, 'Player not found')
@api.response(200, 'Success')
@api.marshal_with(player_get)
def get(self, id):
"""
Returns the specified player.
"""
player = game.get_player(id)
if not player:
api.abort(404)
return player
|
Return json, not just a string id
|
Return json, not just a string id
|
Python
|
apache-2.0
|
hammertoe/didactic-spork,hammertoe/didactic-spork,hammertoe/didactic-spork,hammertoe/didactic-spork
|
import logging
from flask import request
from flask_restplus import Resource
from gameserver.game import Game
from gameserver.models import Player
from gameserver.api.restplus import api
from gameserver.api.serializers import player_get, player_post
from gameserver.database import db
db_session = db.session
log = logging.getLogger(__name__)
ns = api.namespace('players', description='Operations related to players')
game = Game()
@ns.route('/')
class PlayerCollection(Resource):
@api.response(200, 'Success')
@api.marshal_list_with(player_get)
def get(self):
"""
Returns list of players.
"""
players = game.get_players()
return players
@api.response(201, 'Player successfully created.')
@api.expect(player_post)
def post(self):
"""
Creates a new game player.
"""
data = request.json
player = game.create_player(data['name'])
db_session.commit()
- return player.id, 201
+ return dict(id=player.id), 201
@ns.route('/<string:id>')
@ns.param('id', 'The player id')
class Player(Resource):
@api.response(404, 'Player not found')
@api.response(200, 'Success')
@api.marshal_with(player_get)
def get(self, id):
- """
- Returns the specified player.
+ """
+ Returns the specified player.
"""
player = game.get_player(id)
if not player:
api.abort(404)
return player
|
Return json, not just a string id
|
## Code Before:
import logging
from flask import request
from flask_restplus import Resource
from gameserver.game import Game
from gameserver.models import Player
from gameserver.api.restplus import api
from gameserver.api.serializers import player_get, player_post
from gameserver.database import db
db_session = db.session
log = logging.getLogger(__name__)
ns = api.namespace('players', description='Operations related to players')
game = Game()
@ns.route('/')
class PlayerCollection(Resource):
@api.response(200, 'Success')
@api.marshal_list_with(player_get)
def get(self):
"""
Returns list of players.
"""
players = game.get_players()
return players
@api.response(201, 'Player successfully created.')
@api.expect(player_post)
def post(self):
"""
Creates a new game player.
"""
data = request.json
player = game.create_player(data['name'])
db_session.commit()
return player.id, 201
@ns.route('/<string:id>')
@ns.param('id', 'The player id')
class Player(Resource):
@api.response(404, 'Player not found')
@api.response(200, 'Success')
@api.marshal_with(player_get)
def get(self, id):
"""
Returns the specified player.
"""
player = game.get_player(id)
if not player:
api.abort(404)
return player
## Instruction:
Return json, not just a string id
## Code After:
import logging
from flask import request
from flask_restplus import Resource
from gameserver.game import Game
from gameserver.models import Player
from gameserver.api.restplus import api
from gameserver.api.serializers import player_get, player_post
from gameserver.database import db
db_session = db.session
log = logging.getLogger(__name__)
ns = api.namespace('players', description='Operations related to players')
game = Game()
@ns.route('/')
class PlayerCollection(Resource):
@api.response(200, 'Success')
@api.marshal_list_with(player_get)
def get(self):
"""
Returns list of players.
"""
players = game.get_players()
return players
@api.response(201, 'Player successfully created.')
@api.expect(player_post)
def post(self):
"""
Creates a new game player.
"""
data = request.json
player = game.create_player(data['name'])
db_session.commit()
return dict(id=player.id), 201
@ns.route('/<string:id>')
@ns.param('id', 'The player id')
class Player(Resource):
@api.response(404, 'Player not found')
@api.response(200, 'Success')
@api.marshal_with(player_get)
def get(self, id):
"""
Returns the specified player.
"""
player = game.get_player(id)
if not player:
api.abort(404)
return player
|
import logging
from flask import request
from flask_restplus import Resource
from gameserver.game import Game
from gameserver.models import Player
from gameserver.api.restplus import api
from gameserver.api.serializers import player_get, player_post
from gameserver.database import db
db_session = db.session
log = logging.getLogger(__name__)
ns = api.namespace('players', description='Operations related to players')
game = Game()
@ns.route('/')
class PlayerCollection(Resource):
@api.response(200, 'Success')
@api.marshal_list_with(player_get)
def get(self):
"""
Returns list of players.
"""
players = game.get_players()
return players
@api.response(201, 'Player successfully created.')
@api.expect(player_post)
def post(self):
"""
Creates a new game player.
"""
data = request.json
player = game.create_player(data['name'])
db_session.commit()
- return player.id, 201
+ return dict(id=player.id), 201
? ++++++++ +
@ns.route('/<string:id>')
@ns.param('id', 'The player id')
class Player(Resource):
@api.response(404, 'Player not found')
@api.response(200, 'Success')
@api.marshal_with(player_get)
def get(self, id):
- """
- Returns the specified player.
+ """
+ Returns the specified player.
"""
player = game.get_player(id)
if not player:
api.abort(404)
return player
|
f4fdba652a1822698778c65df66a2639ec0fc5ad
|
tests/conftest.py
|
tests/conftest.py
|
import pytest
from .app import setup, teardown
@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
setup()
request.addfinalizer(teardown)
|
from __future__ import absolute_import
import pytest
from .app import setup, teardown
from app import create_app
from app.models import db, Framework
@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
setup()
request.addfinalizer(teardown)
@pytest.fixture(scope='session')
def app(request):
return create_app('test')
@pytest.fixture()
def live_framework(request, app, status='live'):
with app.app_context():
framework = Framework.query.filter(
Framework.slug == 'digital-outcomes-and-specialists'
).first()
original_framework_status = framework.status
framework.status = status
db.session.add(framework)
db.session.commit()
def teardown():
with app.app_context():
framework = Framework.query.filter(
Framework.slug == 'digital-outcomes-and-specialists'
).first()
framework.status = original_framework_status
db.session.add(framework)
db.session.commit()
request.addfinalizer(teardown)
@pytest.fixture()
def expired_framework(request, app):
return live_framework(request, app, status='expired')
|
Add live and expired framework pytest fixtures
|
Add live and expired framework pytest fixtures
This is a tiny attempt to move away from relying on database migrations
to set up framework records for tests. Using migration framework records
means we need to use actual (sometimes expired) frameworks to write tests
ties us to existing frameworks and require manual rollbacks for any record
changes since frameworks/lots tables are not reset between tests.
Using fixtures for frameworks makes it possible to depend explicitly
on database state required to run the test. This works better than
creating objects in setup/teardown since we can create more complicated
objects by using fixture dependencies (eg a service fixture relying on
framework and supplier fixtures etc.).
The fixture is still using DOS for now, but we could change it to create
a test framework with test lots as long as any additional test objects
are created using the fixture dependencies.
|
Python
|
mit
|
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
|
+ from __future__ import absolute_import
+
import pytest
from .app import setup, teardown
+
+ from app import create_app
+ from app.models import db, Framework
@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
setup()
request.addfinalizer(teardown)
+
+ @pytest.fixture(scope='session')
+ def app(request):
+ return create_app('test')
+
+
+ @pytest.fixture()
+ def live_framework(request, app, status='live'):
+ with app.app_context():
+ framework = Framework.query.filter(
+ Framework.slug == 'digital-outcomes-and-specialists'
+ ).first()
+ original_framework_status = framework.status
+ framework.status = status
+
+ db.session.add(framework)
+ db.session.commit()
+
+ def teardown():
+ with app.app_context():
+ framework = Framework.query.filter(
+ Framework.slug == 'digital-outcomes-and-specialists'
+ ).first()
+ framework.status = original_framework_status
+
+ db.session.add(framework)
+ db.session.commit()
+
+ request.addfinalizer(teardown)
+
+
+ @pytest.fixture()
+ def expired_framework(request, app):
+ return live_framework(request, app, status='expired')
+
|
Add live and expired framework pytest fixtures
|
## Code Before:
import pytest
from .app import setup, teardown
@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
setup()
request.addfinalizer(teardown)
## Instruction:
Add live and expired framework pytest fixtures
## Code After:
from __future__ import absolute_import
import pytest
from .app import setup, teardown
from app import create_app
from app.models import db, Framework
@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
setup()
request.addfinalizer(teardown)
@pytest.fixture(scope='session')
def app(request):
return create_app('test')
@pytest.fixture()
def live_framework(request, app, status='live'):
with app.app_context():
framework = Framework.query.filter(
Framework.slug == 'digital-outcomes-and-specialists'
).first()
original_framework_status = framework.status
framework.status = status
db.session.add(framework)
db.session.commit()
def teardown():
with app.app_context():
framework = Framework.query.filter(
Framework.slug == 'digital-outcomes-and-specialists'
).first()
framework.status = original_framework_status
db.session.add(framework)
db.session.commit()
request.addfinalizer(teardown)
@pytest.fixture()
def expired_framework(request, app):
return live_framework(request, app, status='expired')
|
+ from __future__ import absolute_import
+
import pytest
from .app import setup, teardown
+
+ from app import create_app
+ from app.models import db, Framework
@pytest.fixture(autouse=True, scope='session')
def db_migration(request):
setup()
request.addfinalizer(teardown)
+
+
+ @pytest.fixture(scope='session')
+ def app(request):
+ return create_app('test')
+
+
+ @pytest.fixture()
+ def live_framework(request, app, status='live'):
+ with app.app_context():
+ framework = Framework.query.filter(
+ Framework.slug == 'digital-outcomes-and-specialists'
+ ).first()
+ original_framework_status = framework.status
+ framework.status = status
+
+ db.session.add(framework)
+ db.session.commit()
+
+ def teardown():
+ with app.app_context():
+ framework = Framework.query.filter(
+ Framework.slug == 'digital-outcomes-and-specialists'
+ ).first()
+ framework.status = original_framework_status
+
+ db.session.add(framework)
+ db.session.commit()
+
+ request.addfinalizer(teardown)
+
+
+ @pytest.fixture()
+ def expired_framework(request, app):
+ return live_framework(request, app, status='expired')
|
38a2d86aed4ea1e94691993c5f49722f9a69ac8d
|
lisa/__init__.py
|
lisa/__init__.py
|
import warnings
import os
import sys
from lisa.version import __version__
# Raise an exception when a deprecated API is used from within a lisa.*
# submodule. This ensures that we don't use any deprecated APIs internally, so
# they are only kept for external backward compatibility purposes.
warnings.filterwarnings(
action='error',
category=DeprecationWarning,
module=r'{}\..*'.format(__name__),
)
# When the deprecated APIs are used from __main__ (script or notebook), always
# show the warning
warnings.filterwarnings(
action='always',
category=DeprecationWarning,
module=r'__main__',
)
# Prevent matplotlib from trying to connect to X11 server, for headless testing.
# Must be done before importing matplotlib.pyplot or pylab
try:
import matplotlib
except ImportError:
pass
else:
if not os.getenv('DISPLAY'):
matplotlib.use('Agg')
if sys.version_info < (3, 6):
warnings.warn(
'Python 3.6 will soon be required to run LISA, please upgrade from {} to any version higher than 3.6'.format(
'.'.join(
map(str, tuple(sys.version_info)[:3])
),
),
DeprecationWarning,
)
# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab
|
import warnings
import os
import sys
from lisa.version import __version__
# Raise an exception when a deprecated API is used from within a lisa.*
# submodule. This ensures that we don't use any deprecated APIs internally, so
# they are only kept for external backward compatibility purposes.
warnings.filterwarnings(
action='error',
category=DeprecationWarning,
module=r'{}\..*'.format(__name__),
)
# When the deprecated APIs are used from __main__ (script or notebook), always
# show the warning
warnings.filterwarnings(
action='always',
category=DeprecationWarning,
module=r'__main__',
)
# Prevent matplotlib from trying to connect to X11 server, for headless testing.
# Must be done before importing matplotlib.pyplot or pylab
try:
import matplotlib
except ImportError:
pass
else:
if not os.getenv('DISPLAY'):
matplotlib.use('Agg')
# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab
|
Remove Python < 3.6 version check
|
lisa: Remove Python < 3.6 version check
Since Python >= 3.6 is now mandatory, remove the check and the warning.
|
Python
|
apache-2.0
|
ARM-software/lisa,credp/lisa,credp/lisa,credp/lisa,credp/lisa,ARM-software/lisa,ARM-software/lisa,ARM-software/lisa
|
import warnings
import os
import sys
from lisa.version import __version__
# Raise an exception when a deprecated API is used from within a lisa.*
# submodule. This ensures that we don't use any deprecated APIs internally, so
# they are only kept for external backward compatibility purposes.
warnings.filterwarnings(
action='error',
category=DeprecationWarning,
module=r'{}\..*'.format(__name__),
)
# When the deprecated APIs are used from __main__ (script or notebook), always
# show the warning
warnings.filterwarnings(
action='always',
category=DeprecationWarning,
module=r'__main__',
)
# Prevent matplotlib from trying to connect to X11 server, for headless testing.
# Must be done before importing matplotlib.pyplot or pylab
try:
import matplotlib
except ImportError:
pass
else:
if not os.getenv('DISPLAY'):
matplotlib.use('Agg')
- if sys.version_info < (3, 6):
- warnings.warn(
- 'Python 3.6 will soon be required to run LISA, please upgrade from {} to any version higher than 3.6'.format(
- '.'.join(
- map(str, tuple(sys.version_info)[:3])
- ),
- ),
- DeprecationWarning,
- )
-
# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab
|
Remove Python < 3.6 version check
|
## Code Before:
import warnings
import os
import sys
from lisa.version import __version__
# Raise an exception when a deprecated API is used from within a lisa.*
# submodule. This ensures that we don't use any deprecated APIs internally, so
# they are only kept for external backward compatibility purposes.
warnings.filterwarnings(
action='error',
category=DeprecationWarning,
module=r'{}\..*'.format(__name__),
)
# When the deprecated APIs are used from __main__ (script or notebook), always
# show the warning
warnings.filterwarnings(
action='always',
category=DeprecationWarning,
module=r'__main__',
)
# Prevent matplotlib from trying to connect to X11 server, for headless testing.
# Must be done before importing matplotlib.pyplot or pylab
try:
import matplotlib
except ImportError:
pass
else:
if not os.getenv('DISPLAY'):
matplotlib.use('Agg')
if sys.version_info < (3, 6):
warnings.warn(
'Python 3.6 will soon be required to run LISA, please upgrade from {} to any version higher than 3.6'.format(
'.'.join(
map(str, tuple(sys.version_info)[:3])
),
),
DeprecationWarning,
)
# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab
## Instruction:
Remove Python < 3.6 version check
## Code After:
import warnings
import os
import sys
from lisa.version import __version__
# Raise an exception when a deprecated API is used from within a lisa.*
# submodule. This ensures that we don't use any deprecated APIs internally, so
# they are only kept for external backward compatibility purposes.
warnings.filterwarnings(
action='error',
category=DeprecationWarning,
module=r'{}\..*'.format(__name__),
)
# When the deprecated APIs are used from __main__ (script or notebook), always
# show the warning
warnings.filterwarnings(
action='always',
category=DeprecationWarning,
module=r'__main__',
)
# Prevent matplotlib from trying to connect to X11 server, for headless testing.
# Must be done before importing matplotlib.pyplot or pylab
try:
import matplotlib
except ImportError:
pass
else:
if not os.getenv('DISPLAY'):
matplotlib.use('Agg')
# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab
|
import warnings
import os
import sys
from lisa.version import __version__
# Raise an exception when a deprecated API is used from within a lisa.*
# submodule. This ensures that we don't use any deprecated APIs internally, so
# they are only kept for external backward compatibility purposes.
warnings.filterwarnings(
action='error',
category=DeprecationWarning,
module=r'{}\..*'.format(__name__),
)
# When the deprecated APIs are used from __main__ (script or notebook), always
# show the warning
warnings.filterwarnings(
action='always',
category=DeprecationWarning,
module=r'__main__',
)
# Prevent matplotlib from trying to connect to X11 server, for headless testing.
# Must be done before importing matplotlib.pyplot or pylab
try:
import matplotlib
except ImportError:
pass
else:
if not os.getenv('DISPLAY'):
matplotlib.use('Agg')
- if sys.version_info < (3, 6):
- warnings.warn(
- 'Python 3.6 will soon be required to run LISA, please upgrade from {} to any version higher than 3.6'.format(
- '.'.join(
- map(str, tuple(sys.version_info)[:3])
- ),
- ),
- DeprecationWarning,
- )
-
# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab
|
0be3b5bf33a3e0254297eda664c85fd249bce2fe
|
amostra/tests/test_jsonschema.py
|
amostra/tests/test_jsonschema.py
|
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
@given(samples_list=st.lists(st_sample, unique_by=lambda x: x['name'], min_size=3, max_size=5),
containers_list=st.lists(st_container, unique_by=lambda x: x['name'], min_size=3, max_size=5))
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
|
from operator import itemgetter
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
@given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5),
containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5))
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
|
Use itemgetter instead of lambda
|
TST: Use itemgetter instead of lambda
|
Python
|
bsd-3-clause
|
NSLS-II/amostra
|
+ from operator import itemgetter
+
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
- @given(samples_list=st.lists(st_sample, unique_by=lambda x: x['name'], min_size=3, max_size=5),
+ @given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5),
- containers_list=st.lists(st_container, unique_by=lambda x: x['name'], min_size=3, max_size=5))
+ containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5))
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
|
Use itemgetter instead of lambda
|
## Code Before:
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
@given(samples_list=st.lists(st_sample, unique_by=lambda x: x['name'], min_size=3, max_size=5),
containers_list=st.lists(st_container, unique_by=lambda x: x['name'], min_size=3, max_size=5))
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
## Instruction:
Use itemgetter instead of lambda
## Code After:
from operator import itemgetter
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
@given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5),
containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5))
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
|
+ from operator import itemgetter
+
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['properties'].pop('revision')
sample_dict['required'].remove('uuid')
sample_dict['required'].remove('revision')
st_sample = hypothesis_jsonschema.from_schema(sample_dict)
container_dict = load_schema("container.json")
container_dict['properties'].pop('uuid')
container_dict['properties'].pop('revision')
container_dict['required'].remove('uuid')
container_dict['required'].remove('revision')
st_container = hypothesis_jsonschema.from_schema(container_dict)
- @given(samples_list=st.lists(st_sample, unique_by=lambda x: x['name'], min_size=3, max_size=5),
? ^^ ^^^^^^^^^ ^
+ @given(samples_list=st.lists(st_sample, unique_by=itemgetter('name'), min_size=3, max_size=5),
? ^^^ ^^^^^^^ ^
- containers_list=st.lists(st_container, unique_by=lambda x: x['name'], min_size=3, max_size=5))
? ^^ ^^^^^^^^^ ^
+ containers_list=st.lists(st_container, unique_by=itemgetter('name'), min_size=3, max_size=5))
? ^^^ ^^^^^^^ ^
@settings(max_examples=5, suppress_health_check=[HealthCheck.too_slow])
def test_new(client, samples_list, containers_list):
for sample in samples_list:
client.samples.new(**sample)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.