commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
c2bb7f0461599cc7624b8d844be93b6912fc0b1d
examples/test_filter_strings.py
examples/test_filter_strings.py
def test_filter_strings(wish): accept_names = wish names = ['has MARK', 'does not have'] accept_pattern = '.*MARK.*'
def test_filter_strings_basic(wish): filter_strings = wish input = ['has MARK', 'does not have'] expected_ouput = ['has MARK'] accept_pattern = '.*MARK.*' assert list(filter_strings(input, accept_pattern)) == expected_ouput
Complete unfinished code committed by mistake.
Complete unfinished code committed by mistake.
Python
mit
nodev-io/pytest-nodev,alexamici/pytest-wish,alexamici/pytest-nodev
def test_filter_strings(wish): accept_names = wish names = ['has MARK', 'does not have'] accept_pattern = '.*MARK.*'Complete unfinished code committed by mistake.
def test_filter_strings_basic(wish): filter_strings = wish input = ['has MARK', 'does not have'] expected_ouput = ['has MARK'] accept_pattern = '.*MARK.*' assert list(filter_strings(input, accept_pattern)) == expected_ouput
<commit_before> def test_filter_strings(wish): accept_names = wish names = ['has MARK', 'does not have'] accept_pattern = '.*MARK.*'<commit_msg>Complete unfinished code committed by mistake.<commit_after>
def test_filter_strings_basic(wish): filter_strings = wish input = ['has MARK', 'does not have'] expected_ouput = ['has MARK'] accept_pattern = '.*MARK.*' assert list(filter_strings(input, accept_pattern)) == expected_ouput
def test_filter_strings(wish): accept_names = wish names = ['has MARK', 'does not have'] accept_pattern = '.*MARK.*'Complete unfinished code committed by mistake. def test_filter_strings_basic(wish): filter_strings = wish input = ['has MARK', 'does not have'] expected_ouput = ['has MARK'] accept_pattern = '.*MARK.*' assert list(filter_strings(input, accept_pattern)) == expected_ouput
<commit_before> def test_filter_strings(wish): accept_names = wish names = ['has MARK', 'does not have'] accept_pattern = '.*MARK.*'<commit_msg>Complete unfinished code committed by mistake.<commit_after> def test_filter_strings_basic(wish): filter_strings = wish input = ['has MARK', 'does not have'] expected_ouput = ['has MARK'] accept_pattern = '.*MARK.*' assert list(filter_strings(input, accept_pattern)) == expected_ouput
dcecdbae798e0a83afb17911ec459224790e51cd
launch_control/dashboard_app/tests.py
launch_control/dashboard_app/tests.py
""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase): def test_creation_1(self): sw_package = SoftwarePackage.objects.create(name='libfoo', version='1.2.0') self.assertEqual(sw_package.name, 'libfoo') self.assertEqual(sw_package.version, '1.2.0') def test_uniqueness(self): SoftwarePackage.objects.create(name='a', version='0') self.assertRaises(IntegrityError, SoftwarePackage.objects.create, name='a', version='0')
""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.utils.call_helper import ObjectFactoryMixIn from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn): class Dummy: class SoftwarePackage: name = 'libfoo' version = '1.2.0' def test_creation_1(self): dummy, sw_package = self.make_and_get_dummy(SoftwarePackage) self.assertEqual(sw_package.name, dummy.name) self.assertEqual(sw_package.version, dummy.version) def test_uniqueness(self): pkg1 = self.make(SoftwarePackage) pkg1.save() pkg2 = self.make(SoftwarePackage) self.assertRaises(IntegrityError, pkg2.save)
Update SoftwarePackageTestCase to use ObjectFactoryMixIn
Update SoftwarePackageTestCase to use ObjectFactoryMixIn
Python
agpl-3.0
OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server
""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase): def test_creation_1(self): sw_package = SoftwarePackage.objects.create(name='libfoo', version='1.2.0') self.assertEqual(sw_package.name, 'libfoo') self.assertEqual(sw_package.version, '1.2.0') def test_uniqueness(self): SoftwarePackage.objects.create(name='a', version='0') self.assertRaises(IntegrityError, SoftwarePackage.objects.create, name='a', version='0') Update SoftwarePackageTestCase to use ObjectFactoryMixIn
""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.utils.call_helper import ObjectFactoryMixIn from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn): class Dummy: class SoftwarePackage: name = 'libfoo' version = '1.2.0' def test_creation_1(self): dummy, sw_package = self.make_and_get_dummy(SoftwarePackage) self.assertEqual(sw_package.name, dummy.name) self.assertEqual(sw_package.version, dummy.version) def test_uniqueness(self): pkg1 = self.make(SoftwarePackage) pkg1.save() pkg2 = self.make(SoftwarePackage) self.assertRaises(IntegrityError, pkg2.save)
<commit_before>""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase): def test_creation_1(self): sw_package = SoftwarePackage.objects.create(name='libfoo', version='1.2.0') self.assertEqual(sw_package.name, 'libfoo') self.assertEqual(sw_package.version, '1.2.0') def test_uniqueness(self): SoftwarePackage.objects.create(name='a', version='0') self.assertRaises(IntegrityError, SoftwarePackage.objects.create, name='a', version='0') <commit_msg>Update SoftwarePackageTestCase to use ObjectFactoryMixIn<commit_after>
""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.utils.call_helper import ObjectFactoryMixIn from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn): class Dummy: class SoftwarePackage: name = 'libfoo' version = '1.2.0' def test_creation_1(self): dummy, sw_package = self.make_and_get_dummy(SoftwarePackage) self.assertEqual(sw_package.name, dummy.name) self.assertEqual(sw_package.version, dummy.version) def test_uniqueness(self): pkg1 = self.make(SoftwarePackage) pkg1.save() pkg2 = self.make(SoftwarePackage) self.assertRaises(IntegrityError, pkg2.save)
""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase): def test_creation_1(self): sw_package = SoftwarePackage.objects.create(name='libfoo', version='1.2.0') self.assertEqual(sw_package.name, 'libfoo') self.assertEqual(sw_package.version, '1.2.0') def test_uniqueness(self): SoftwarePackage.objects.create(name='a', version='0') self.assertRaises(IntegrityError, SoftwarePackage.objects.create, name='a', version='0') Update SoftwarePackageTestCase to use ObjectFactoryMixIn""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.utils.call_helper import ObjectFactoryMixIn from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn): class Dummy: class SoftwarePackage: name = 'libfoo' version = '1.2.0' def test_creation_1(self): dummy, sw_package = self.make_and_get_dummy(SoftwarePackage) self.assertEqual(sw_package.name, dummy.name) self.assertEqual(sw_package.version, dummy.version) def test_uniqueness(self): pkg1 = self.make(SoftwarePackage) pkg1.save() pkg2 = self.make(SoftwarePackage) self.assertRaises(IntegrityError, pkg2.save)
<commit_before>""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase): def test_creation_1(self): sw_package = SoftwarePackage.objects.create(name='libfoo', version='1.2.0') self.assertEqual(sw_package.name, 'libfoo') self.assertEqual(sw_package.version, '1.2.0') def test_uniqueness(self): SoftwarePackage.objects.create(name='a', version='0') self.assertRaises(IntegrityError, SoftwarePackage.objects.create, name='a', version='0') <commit_msg>Update SoftwarePackageTestCase to use ObjectFactoryMixIn<commit_after>""" Unit tests of the Dashboard application """ from django.test import TestCase from django.db import IntegrityError from launch_control.utils.call_helper import ObjectFactoryMixIn from launch_control.dashboard_app.models import ( SoftwarePackage, ) class SoftwarePackageTestCase(TestCase, ObjectFactoryMixIn): class Dummy: class SoftwarePackage: name = 'libfoo' version = '1.2.0' def test_creation_1(self): dummy, sw_package = self.make_and_get_dummy(SoftwarePackage) self.assertEqual(sw_package.name, dummy.name) self.assertEqual(sw_package.version, dummy.version) def test_uniqueness(self): pkg1 = self.make(SoftwarePackage) pkg1.save() pkg2 = self.make(SoftwarePackage) self.assertRaises(IntegrityError, pkg2.save)
057ca5e187b2f8e7604318a4e82efed76548e0f8
falmer/studentgroups/queries.py
falmer/studentgroups/queries.py
import graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, groupId=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id)
import graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, group_id=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id)
Fix group id query case
Fix group id query case
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
import graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, groupId=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id) Fix group id query case
import graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, group_id=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id)
<commit_before>import graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, groupId=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id) <commit_msg>Fix group id query case<commit_after>
import graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, group_id=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id)
import graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, groupId=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id) Fix group id query caseimport graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, group_id=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id)
<commit_before>import graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, groupId=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id) <commit_msg>Fix group id query case<commit_after>import graphene from falmer.schema.schema import DjangoConnectionField from falmer.studentgroups.types import StudentGroup from . import types from . import models class Query(graphene.ObjectType): all_groups = DjangoConnectionField(StudentGroup) group = graphene.Field(types.StudentGroup, group_id=graphene.Int()) def resolve_all_groups(self, info): qs = models.StudentGroup.objects \ .order_by('name') \ .select_related('msl_group', 'logo') return qs def resolve_group(self, info, **kwargs): group_id = kwargs.get('group_id') return models.StudentGroup.objects \ .select_related('logo').get(pk=group_id)
210a1a2387a048f8ff6ac650ce66543923ece860
pythonforandroid/recipes/pymunk/__init__.py
pythonforandroid/recipes/pymunk/__init__.py
from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" return env recipe = PymunkRecipe()
from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" # Used by Chipmunk cpMessage env["LDFLAGS"] += " -lm" # For older versions of Android return env recipe = PymunkRecipe()
Fix Pymunk crash on older versions of Android
Fix Pymunk crash on older versions of Android Seems to be required to link -lm on at least 5.1, but not on 8.0
Python
mit
kronenpj/python-for-android,PKRoma/python-for-android,kivy/python-for-android,kronenpj/python-for-android,kronenpj/python-for-android,kivy/python-for-android,PKRoma/python-for-android,PKRoma/python-for-android,PKRoma/python-for-android,kivy/python-for-android,kronenpj/python-for-android,PKRoma/python-for-android,kivy/python-for-android,kivy/python-for-android,kronenpj/python-for-android
from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" return env recipe = PymunkRecipe() Fix Pymunk crash on older versions of Android Seems to be required to link -lm on at least 5.1, but not on 8.0
from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" # Used by Chipmunk cpMessage env["LDFLAGS"] += " -lm" # For older versions of Android return env recipe = PymunkRecipe()
<commit_before>from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" return env recipe = PymunkRecipe() <commit_msg>Fix Pymunk crash on older versions of Android Seems to be required to link -lm on at least 5.1, but not on 8.0<commit_after>
from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" # Used by Chipmunk cpMessage env["LDFLAGS"] += " -lm" # For older versions of Android return env recipe = PymunkRecipe()
from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" return env recipe = PymunkRecipe() Fix Pymunk crash on older versions of Android Seems to be required to link -lm on at least 5.1, but not on 8.0from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" # Used by Chipmunk cpMessage env["LDFLAGS"] += " -lm" # For older versions of Android return env recipe = PymunkRecipe()
<commit_before>from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" return env recipe = PymunkRecipe() <commit_msg>Fix Pymunk crash on older versions of Android Seems to be required to link -lm on at least 5.1, but not on 8.0<commit_after>from pythonforandroid.recipe import CompiledComponentsPythonRecipe class PymunkRecipe(CompiledComponentsPythonRecipe): name = "pymunk" version = "6.0.0" url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip" depends = ["cffi", "setuptools"] call_hostpython_via_targetpython = False def get_recipe_env(self, arch): env = super().get_recipe_env(arch) env["LDFLAGS"] += " -llog" # Used by Chipmunk cpMessage env["LDFLAGS"] += " -lm" # For older versions of Android return env recipe = PymunkRecipe()
0e754fe4ea8ddee4bb952b483c4da2d8bf5970ed
core/context_processors.py
core/context_processors.py
from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": _("People's Archive of Rural India") }
from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": django_settings.SITE_TITLE }
Remove the hardcode from the settings.
Remove the hardcode from the settings.
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": _("People's Archive of Rural India") } Remove the hardcode from the settings.
from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": django_settings.SITE_TITLE }
<commit_before>from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": _("People's Archive of Rural India") } <commit_msg>Remove the hardcode from the settings.<commit_after>
from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": django_settings.SITE_TITLE }
from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": _("People's Archive of Rural India") } Remove the hardcode from the settings.from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": django_settings.SITE_TITLE }
<commit_before>from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": _("People's Archive of Rural India") } <commit_msg>Remove the hardcode from the settings.<commit_after>from django.conf import settings as django_settings from django.utils.translation import ugettext_lazy as _ def settings(request): if not getattr(django_settings, "SOCIAL", None): return {} return { "SOCIAL_FACEBOOK": django_settings.SOCIAL.get("FACEBOOK", ""), "SOCIAL_TWITTER": django_settings.SOCIAL.get("TWITTER", ""), "SOCIAL_GITHUB_REPO": django_settings.SOCIAL.get("GITHUB_REPO", ""), "GOOGLE_ANALYTICS_ID": django_settings.SOCIAL.get("GOOGLE_ANALYTICS_ID", ""), "SITE_TITLE": django_settings.SITE_TITLE }
970d296cd4344fbbde28552dbf2aa5fbbb329c9d
gh_user_download.py
gh_user_download.py
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download <who> <where> gh_user_download -h | --help """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="testing") who = arguments['<who>'] where = arguments['<where>'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: url = repo.git_url print(url, 'to', os.path.join(where, repo.name)) os.system('git clone ' + url + ' ' + os.path.join(where, repo.name)) if __name__ == '__main__': main()
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download [-s] <who> <where> gh_user_download -h | --help Options: -s, --ssh Checks out via ssh """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="1.0") who = arguments['<who>'] where = arguments['<where>'] ssh = arguments['--ssh'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: if ssh: url = 'git@github.com:' + who + '/' + repo.name else: url = repo.git_url path = os.path.join(where, repo.name) print(url, 'to', path) os.system('git clone ' + url + ' ' + path) if __name__ == '__main__': main()
Add option to download via SSH
Add option to download via SSH
Python
mit
JackMc/git_tools
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download <who> <where> gh_user_download -h | --help """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="testing") who = arguments['<who>'] where = arguments['<where>'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: url = repo.git_url print(url, 'to', os.path.join(where, repo.name)) os.system('git clone ' + url + ' ' + os.path.join(where, repo.name)) if __name__ == '__main__': main() Add option to download via SSH
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download [-s] <who> <where> gh_user_download -h | --help Options: -s, --ssh Checks out via ssh """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="1.0") who = arguments['<who>'] where = arguments['<where>'] ssh = arguments['--ssh'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: if ssh: url = 'git@github.com:' + who + '/' + repo.name else: url = repo.git_url path = os.path.join(where, repo.name) print(url, 'to', path) os.system('git clone ' + url + ' ' + path) if __name__ == '__main__': main()
<commit_before># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download <who> <where> gh_user_download -h | --help """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="testing") who = arguments['<who>'] where = arguments['<where>'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: url = repo.git_url print(url, 'to', os.path.join(where, repo.name)) os.system('git clone ' + url + ' ' + os.path.join(where, repo.name)) if __name__ == '__main__': main() <commit_msg>Add option to download via SSH<commit_after>
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download [-s] <who> <where> gh_user_download -h | --help Options: -s, --ssh Checks out via ssh """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="1.0") who = arguments['<who>'] where = arguments['<where>'] ssh = arguments['--ssh'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: if ssh: url = 'git@github.com:' + who + '/' + repo.name else: url = repo.git_url path = os.path.join(where, repo.name) print(url, 'to', path) os.system('git clone ' + url + ' ' + path) if __name__ == '__main__': main()
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download <who> <where> gh_user_download -h | --help """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="testing") who = arguments['<who>'] where = arguments['<where>'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: url = repo.git_url print(url, 'to', os.path.join(where, repo.name)) os.system('git clone ' + url + ' ' + os.path.join(where, repo.name)) if __name__ == '__main__': main() Add option to download via SSH# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download [-s] <who> <where> gh_user_download -h | --help Options: -s, --ssh Checks out via ssh """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="1.0") who = arguments['<who>'] where = arguments['<where>'] ssh = arguments['--ssh'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: if ssh: url = 'git@github.com:' + who + '/' + repo.name else: url = repo.git_url path = os.path.join(where, repo.name) print(url, 'to', path) os.system('git clone ' + url + ' ' + path) if __name__ == '__main__': main()
<commit_before># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download <who> <where> gh_user_download -h | --help """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="testing") who = arguments['<who>'] where = arguments['<where>'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: url = repo.git_url print(url, 'to', os.path.join(where, repo.name)) os.system('git clone ' + url + ' ' + os.path.join(where, repo.name)) if __name__ == '__main__': main() <commit_msg>Add option to download via SSH<commit_after># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """\ Usage: gh_user_download [-s] <who> <where> gh_user_download -h | --help Options: -s, --ssh Checks out via ssh """ from __future__ import print_function import os from pygithub3 import Github from docopt import docopt def main(): arguments = docopt(__doc__, version="1.0") who = arguments['<who>'] where = arguments['<where>'] ssh = arguments['--ssh'] gh = Github() repos = gh.repos.list(who).all() for repo in repos: if ssh: url = 'git@github.com:' + who + '/' + repo.name else: url = repo.git_url path = os.path.join(where, repo.name) print(url, 'to', path) os.system('git clone ' + url + ' ' + path) if __name__ == '__main__': main()
6039fd841bdddaa8fc35dcf11c2e1c71d95da66d
evaluation/packages/io.py
evaluation/packages/io.py
"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement
"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement def readPrimitiveCorrespondancesFromFiles(path, primset1, primset2): f = open(path, 'r') corresp = {} correspUid = {} for line in f: if line[0] != '#': fline = np.int16(line.split(',')[0:6]) p1 = None p2 = None for p in primset1: if p.uid == fline[0] and p.did == fline[2]: p1 = p break for p in primset2: if p.uid == fline[3] and p.did == fline[5]: p2 = p break if (p1 != None and p2 != None): corresp[p1] = p2 correspUid[p1.uid] = p2.uid else: print "Cannot find ",fline f return corresp, correspUid
Add new method to read correspondances files
Add new method to read correspondances files
Python
apache-2.0
amonszpart/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,amonszpart/globOpt
"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement Add new method to read correspondances files
"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement def readPrimitiveCorrespondancesFromFiles(path, primset1, primset2): f = open(path, 'r') corresp = {} correspUid = {} for line in f: if line[0] != '#': fline = np.int16(line.split(',')[0:6]) p1 = None p2 = None for p in primset1: if p.uid == fline[0] and p.did == fline[2]: p1 = p break for p in primset2: if p.uid == fline[3] and p.did == fline[5]: p2 = p break if (p1 != None and p2 != None): corresp[p1] = p2 correspUid[p1.uid] = p2.uid else: print "Cannot find ",fline f return corresp, correspUid
<commit_before>"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement <commit_msg>Add new method to read correspondances files<commit_after>
"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement def readPrimitiveCorrespondancesFromFiles(path, primset1, primset2): f = open(path, 'r') corresp = {} correspUid = {} for line in f: if line[0] != '#': fline = np.int16(line.split(',')[0:6]) p1 = None p2 = None for p in primset1: if p.uid == fline[0] and p.did == fline[2]: p1 = p break for p in primset2: if p.uid == fline[3] and p.did == fline[5]: p2 = p break if (p1 != None and p2 != None): corresp[p1] = p2 correspUid[p1.uid] = p2.uid else: print "Cannot find ",fline f return corresp, correspUid
"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement Add new method to read correspondances files"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement def readPrimitiveCorrespondancesFromFiles(path, primset1, primset2): f = open(path, 'r') corresp = {} correspUid = {} for line in f: if line[0] != '#': fline = np.int16(line.split(',')[0:6]) p1 = None p2 = None for p in primset1: if p.uid == fline[0] and p.did == fline[2]: p1 = p break for p in primset2: if p.uid == fline[3] and p.did == fline[5]: p2 = p break if (p1 != None and p2 != None): corresp[p1] = p2 correspUid[p1.uid] = p2.uid else: print "Cannot find ",fline f return corresp, correspUid
<commit_before>"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement <commit_msg>Add new method to read correspondances files<commit_after>"""@package IO Generic input/output functions """ import numpy as np def readPointCloudFromPly(path): f = open(path, 'r') points = [] headerSkipped = False for line in f: if headerSkipped: points.append(np.float32(np.array(line.split(' ')[0:3]))) else: headerSkipped = line.find('end_header') != -1 return points def readPointAssignementFromFiles(path): f = open(path, 'r') assignement = [] for line in f: if line[0] != '#': assignement.append(np.int16(line.split(',')[0:2])) return assignement def readPrimitiveCorrespondancesFromFiles(path, primset1, primset2): f = open(path, 'r') corresp = {} correspUid = {} for line in f: if line[0] != '#': fline = np.int16(line.split(',')[0:6]) p1 = None p2 = None for p in primset1: if p.uid == fline[0] and p.did == fline[2]: p1 = p break for p in primset2: if p.uid == fline[3] and p.did == fline[5]: p2 = p break if (p1 != None and p2 != None): corresp[p1] = p2 correspUid[p1.uid] = p2.uid else: print "Cannot find ",fline f return corresp, correspUid
cbc681933fd6e2899f38dd9759bb9a188b66bbd4
tests/run.py
tests/run.py
import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( # Core environmental settings INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, # LoginRequiredMiddleware data LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), # BasicAuthenticationMiddleware data BASIC_WWW_AUTHENTICATION_USERNAME = 'user', BASIC_WWW_AUTHENTICATION_PASSWORD = 'pass', BASIC_WWW_AUTHENTICATION = True, ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
Add environmental settings for basic authentication.
Add environmental settings for basic authentication.
Python
bsd-2-clause
ghickman/incuna-auth,incuna/incuna-auth,incuna/incuna-auth,ghickman/incuna-auth
import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1) Add environmental settings for basic authentication.
import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( # Core environmental settings INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, # LoginRequiredMiddleware data LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), # BasicAuthenticationMiddleware data BASIC_WWW_AUTHENTICATION_USERNAME = 'user', BASIC_WWW_AUTHENTICATION_PASSWORD = 'pass', BASIC_WWW_AUTHENTICATION = True, ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
<commit_before>import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1) <commit_msg>Add environmental settings for basic authentication.<commit_after>
import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( # Core environmental settings INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, # LoginRequiredMiddleware data LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), # BasicAuthenticationMiddleware data BASIC_WWW_AUTHENTICATION_USERNAME = 'user', BASIC_WWW_AUTHENTICATION_PASSWORD = 'pass', BASIC_WWW_AUTHENTICATION = True, ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1) Add environmental settings for basic authentication.import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( # Core environmental settings INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, # LoginRequiredMiddleware data LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), # BasicAuthenticationMiddleware data BASIC_WWW_AUTHENTICATION_USERNAME = 'user', BASIC_WWW_AUTHENTICATION_PASSWORD = 'pass', BASIC_WWW_AUTHENTICATION = True, ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
<commit_before>import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1) <commit_msg>Add environmental settings for basic authentication.<commit_after>import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( # Core environmental settings INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, # LoginRequiredMiddleware data LOGIN_REQUIRED_SEND_MESSAGE=False, LOGIN_EXEMPT_URLS = ( '^exempt-url/$', '^exempt-and-protected-url/$', ), LOGIN_PROTECTED_URLS = ( '^exempt-and-protected-url/$', '^protected-url/$', ), # BasicAuthenticationMiddleware data BASIC_WWW_AUTHENTICATION_USERNAME = 'user', BASIC_WWW_AUTHENTICATION_PASSWORD = 'pass', BASIC_WWW_AUTHENTICATION = True, ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
bb11252c277d40c8ec8c579100c04a6a676accfe
tests/run.py
tests/run.py
#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings from django.test.runner import DiscoverRunner settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
Reorder imports to dodge a settings problem.
Reorder imports to dodge a settings problem.
Python
bsd-2-clause
incuna/incuna-auth,ghickman/incuna-auth,incuna/incuna-auth,ghickman/incuna-auth
#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings from django.test.runner import DiscoverRunner settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1) Reorder imports to dodge a settings problem.
#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
<commit_before>#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings from django.test.runner import DiscoverRunner settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1) <commit_msg>Reorder imports to dodge a settings problem.<commit_after>
#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings from django.test.runner import DiscoverRunner settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1) Reorder imports to dodge a settings problem.#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
<commit_before>#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings from django.test.runner import DiscoverRunner settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1) <commit_msg>Reorder imports to dodge a settings problem.<commit_after>#! /usr/bin/env python3 from os import path import sys from colour_runner.django_runner import ColourRunnerMixin from django.conf import settings settings.configure( INSTALLED_APPS=( # Put contenttypes before auth to work around test issue. # See: https://code.djangoproject.com/ticket/10827#comment:12 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django-admin-sso', 'django-crispy-forms', 'incuna_auth', ), PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',), AUTH_USER_MODEL='tests.User', ROOT_URLCONF='incuna_auth.urls', REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), }, TEST_DISCOVER_TOP_LEVEL=path.dirname(path.dirname(__file__)), ) from django.test.runner import DiscoverRunner class Runner(ColourRunnerMixin, DiscoverRunner): pass test_runner = Runner(verbosity=1) failures = test_runner.run_tests(['tests']) if failures: sys.exit(1)
7821681829008dfe1c933551656c1604a24b491b
cla_frontend/apps/status/views.py
cla_frontend/apps/status/views.py
import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent infra changes """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data)
import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent move to Kubernetes, obviating this view """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data)
Clarify docstring from previous PR suggestion
Clarify docstring from previous PR suggestion
Python
mit
ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend,ministryofjustice/cla_frontend
import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent infra changes """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data) Clarify docstring from previous PR suggestion
import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent move to Kubernetes, obviating this view """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data)
<commit_before>import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent infra changes """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data) <commit_msg>Clarify docstring from previous PR suggestion<commit_after>
import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent move to Kubernetes, obviating this view """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data)
import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent infra changes """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data) Clarify docstring from previous PR suggestionimport datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent move to Kubernetes, obviating this view """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data)
<commit_before>import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent infra changes """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data) <commit_msg>Clarify docstring from previous PR suggestion<commit_after>import datetime from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View from cla_common.smoketest import smoketest from .smoketests import smoketests def status(request): results = list(smoketests.execute()) passed = reduce(lambda acc, curr: acc and curr['status'], results, True) return render(request, 'status/status_page.html', { 'passed': passed, 'last_updated': datetime.datetime.now(), 'smoketests': results }) def smoketests_json(request): """ Run smoke tests and return results as JSON datastructure """ from cla_frontend.apps.status.tests.smoketests import SmokeTests return JsonResponse(smoketest(SmokeTests)) class PingJsonView(View): """ Stub IRaT PingJsonView for compatibility with current and imminent move to Kubernetes, obviating this view """ def get(self, request): response_data = {"build_tag": None, "build_date": None, "version_number": None, "commit_id": None} return JsonResponse(response_data)
b47821b4fce6ab969fab3c7c5a1ef1a8fb58764c
jacquard/storage/tests/test_dummy.py
jacquard/storage/tests/test_dummy.py
import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('')
import pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') def test_transaction_raises_error_for_bad_commit(self): store = self.open_storage() transaction = store.transaction(read_only=True) transaction_map = transaction.__enter__() transaction_map['new_key'] = 'new_value' with pytest.raises(RuntimeError): transaction.__exit__(None, None, None) assert 'new_key' not in store.data
Cover this exception with a test
Cover this exception with a test
Python
mit
prophile/jacquard,prophile/jacquard
import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') Cover this exception with a test
import pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') def test_transaction_raises_error_for_bad_commit(self): store = self.open_storage() transaction = store.transaction(read_only=True) transaction_map = transaction.__enter__() transaction_map['new_key'] = 'new_value' with pytest.raises(RuntimeError): transaction.__exit__(None, None, None) assert 'new_key' not in store.data
<commit_before>import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') <commit_msg>Cover this exception with a test<commit_after>
import pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') def test_transaction_raises_error_for_bad_commit(self): store = self.open_storage() transaction = store.transaction(read_only=True) transaction_map = transaction.__enter__() transaction_map['new_key'] = 'new_value' with pytest.raises(RuntimeError): transaction.__exit__(None, None, None) assert 'new_key' not in store.data
import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') Cover this exception with a testimport pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') def test_transaction_raises_error_for_bad_commit(self): store = self.open_storage() transaction = store.transaction(read_only=True) transaction_map = transaction.__enter__() transaction_map['new_key'] = 'new_value' with pytest.raises(RuntimeError): transaction.__exit__(None, None, None) assert 'new_key' not in store.data
<commit_before>import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') <commit_msg>Cover this exception with a test<commit_after>import pytest import unittest from jacquard.storage.dummy import DummyStore from jacquard.storage.testing_utils import StorageGauntlet class DummyGauntletTest(StorageGauntlet, unittest.TestCase): def open_storage(self): return DummyStore('') def test_transaction_raises_error_for_bad_commit(self): store = self.open_storage() transaction = store.transaction(read_only=True) transaction_map = transaction.__enter__() transaction_map['new_key'] = 'new_value' with pytest.raises(RuntimeError): transaction.__exit__(None, None, None) assert 'new_key' not in store.data
3cee41ff8a7af405fe3a6bfda214e4fe1a6d3c0f
oneflow/settings/snippets/db_production.py
oneflow/settings/snippets/db_production.py
DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 REDIS_TEST_DB = 9 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
Add the test REDIS database.
Add the test REDIS database.
Python
agpl-3.0
1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow
DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2 Add the test REDIS database.
DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 REDIS_TEST_DB = 9 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
<commit_before> DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2 <commit_msg>Add the test REDIS database.<commit_after>
DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 REDIS_TEST_DB = 9 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2 Add the test REDIS database. DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 REDIS_TEST_DB = 9 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
<commit_before> DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2 <commit_msg>Add the test REDIS database.<commit_after> DATABASES['default'] = dj_database_url.config( default='postgres://oneflow:8jxcWaAfPJT3mV@{0}' '/oneflow'.format(MAIN_SERVER)) mongoengine.connect('oneflow', host=MAIN_SERVER) REDIS_DB = 0 REDIS_TEST_DB = 9 CONSTANCE_REDIS_CONNECTION = 'redis://{0}:6379/{1}'.format( MAIN_SERVER, REDIS_DB) SESSION_REDIS_HOST = MAIN_SERVER SESSION_REDIS_DB = 2
3ede283ed3f656dc8f73c962eb452ce4b849dfd9
guardhouse/main/forms.py
guardhouse/main/forms.py
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('verified',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('belongs_to', 'verification_state',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
Remove internal fields form from
Remove internal fields form from
Python
bsd-3-clause
ulope/guardhouse,ulope/guardhouse
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('verified',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates') Remove internal fields form from
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('belongs_to', 'verification_state',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
<commit_before>from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('verified',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates') <commit_msg>Remove internal fields form from<commit_after>
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('belongs_to', 'verification_state',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('verified',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates') Remove internal fields form fromfrom django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('belongs_to', 'verification_state',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
<commit_before>from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('verified',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates') <commit_msg>Remove internal fields form from<commit_after>from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('belongs_to', 'verification_state',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
033e017d05807b0b827e54c722a9f9a98327af87
kolibri/__init__.py
kolibri/__init__.py
""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "beta", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION))
""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "final", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION))
Update VERSION to 0.12.6 final
Update VERSION to 0.12.6 final
Python
mit
learningequality/kolibri,indirectlylit/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,mrpau/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri
""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "beta", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION)) Update VERSION to 0.12.6 final
""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "final", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION))
<commit_before>""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "beta", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION)) <commit_msg>Update VERSION to 0.12.6 final<commit_after>
""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "final", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION))
""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "beta", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION)) Update VERSION to 0.12.6 final""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "final", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION))
<commit_before>""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "beta", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION)) <commit_msg>Update VERSION to 0.12.6 final<commit_after>""" CAUTION! Keep everything here at at minimum. Do not import stuff. This module is imported in setup.py, so you cannot for instance import a dependency. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from .utils import env from .utils.version import get_version # Setup the environment before loading anything else from the application env.set_env() #: This may not be the exact version as it's subject to modification with #: get_version() - use ``kolibri.__version__`` for the exact version string. VERSION = (0, 12, 6, "final", 0) __author__ = "Learning Equality" __email__ = "info@learningequality.org" __version__ = str(get_version(VERSION))
2784738167145ef0226679df21b205d033737b29
optimization/simple.py
optimization/simple.py
#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) coef=[1,2] var=[x1,x2] s=[] for c,v in zip(coef,var): print(c,v) s.append(c*v) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x))
#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) class Power: def __init__(self): self.coef=None self.var =None def __repr__(self): return "<%s %s>" % (self.coef,self.var) p1=Power() p2=Power() print(p1) p1.coef=1 p2.coef=2 p1.var=x1 p2.var=x2 p=[p1,p2] print(p) s=[] for i in p: print(i.coef,i.var) s.append(i.coef*i.var) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x))
Use classes to create constraints.
Use classes to create constraints.
Python
apache-2.0
MiddelkoopT/CompOpt-2014-Fall,MiddelkoopT/CompOpt-2014-Fall
#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) coef=[1,2] var=[x1,x2] s=[] for c,v in zip(coef,var): print(c,v) s.append(c*v) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x)) Use classes to create constraints.
#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) class Power: def __init__(self): self.coef=None self.var =None def __repr__(self): return "<%s %s>" % (self.coef,self.var) p1=Power() p2=Power() print(p1) p1.coef=1 p2.coef=2 p1.var=x1 p2.var=x2 p=[p1,p2] print(p) s=[] for i in p: print(i.coef,i.var) s.append(i.coef*i.var) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x))
<commit_before>#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) coef=[1,2] var=[x1,x2] s=[] for c,v in zip(coef,var): print(c,v) s.append(c*v) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x)) <commit_msg>Use classes to create constraints.<commit_after>
#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) class Power: def __init__(self): self.coef=None self.var =None def __repr__(self): return "<%s %s>" % (self.coef,self.var) p1=Power() p2=Power() print(p1) p1.coef=1 p2.coef=2 p1.var=x1 p2.var=x2 p=[p1,p2] print(p) s=[] for i in p: print(i.coef,i.var) s.append(i.coef*i.var) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x))
#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) coef=[1,2] var=[x1,x2] s=[] for c,v in zip(coef,var): print(c,v) s.append(c*v) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x)) Use classes to create constraints.#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) class Power: def __init__(self): self.coef=None self.var =None def __repr__(self): return "<%s %s>" % (self.coef,self.var) p1=Power() p2=Power() print(p1) p1.coef=1 p2.coef=2 p1.var=x1 p2.var=x2 p=[p1,p2] print(p) s=[] for i in p: print(i.coef,i.var) s.append(i.coef*i.var) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x))
<commit_before>#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) coef=[1,2] var=[x1,x2] s=[] for c,v in zip(coef,var): print(c,v) s.append(c*v) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x)) <commit_msg>Use classes to create constraints.<commit_after>#!/usr/bin/python3 """ Maximize 1 x1 + 2 x2 Subject To C1: x1 + x2 <= 40 Nickel: 2 x1 + 1 x2 <= 60 Bounds x1 >= 0 x2 >= 0 End """ from gurobipy import * m = Model("simple") x1 = m.addVar(name="x1") x2 = m.addVar(name="x2") m.update() print("x1:%s x2:%s" % (x1,x2)) #m.setObjective(x1 + 2*x2, GRB.MAXIMIZE) class Power: def __init__(self): self.coef=None self.var =None def __repr__(self): return "<%s %s>" % (self.coef,self.var) p1=Power() p2=Power() print(p1) p1.coef=1 p2.coef=2 p1.var=x1 p2.var=x2 p=[p1,p2] print(p) s=[] for i in p: print(i.coef,i.var) s.append(i.coef*i.var) m.setObjective(sum(s),GRB.MAXIMIZE) m.addConstr(x1 + x2 <= 40, "C1") m.addConstr(2*x1 + x2 <= 60, "C2") m.optimize() print("Solution: %f" % (m.objVal,)) for v in m.getVars(): print("%s:%f" % (v.varName, v.x))
8869eba1f74e677d1802aad0cc2592344ab81000
podium/talks/models.py
podium/talks/models.py
from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): sets = [ self.talks_available.filter(status=status) for status in ('A', 'C') ] return sets[0].union(sets[1]) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id])
from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): return self.talks_available.filter(status__in=('A', 'C')) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id])
Use a filter field lookup
Use a filter field lookup Looks like I forgot to do this when JR suggested it.
Python
mit
pyatl/podium-django,pyatl/podium-django,pyatl/podium-django
from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): sets = [ self.talks_available.filter(status=status) for status in ('A', 'C') ] return sets[0].union(sets[1]) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id]) Use a filter field lookup Looks like I forgot to do this when JR suggested it.
from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): return self.talks_available.filter(status__in=('A', 'C')) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id])
<commit_before>from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): sets = [ self.talks_available.filter(status=status) for status in ('A', 'C') ] return sets[0].union(sets[1]) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id]) <commit_msg>Use a filter field lookup Looks like I forgot to do this when JR suggested it.<commit_after>
from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): return self.talks_available.filter(status__in=('A', 'C')) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id])
from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): sets = [ self.talks_available.filter(status=status) for status in ('A', 'C') ] return sets[0].union(sets[1]) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id]) Use a filter field lookup Looks like I forgot to do this when JR suggested it.from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): return self.talks_available.filter(status__in=('A', 'C')) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id])
<commit_before>from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): sets = [ self.talks_available.filter(status=status) for status in ('A', 'C') ] return sets[0].union(sets[1]) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id]) <commit_msg>Use a filter field lookup Looks like I forgot to do this when JR suggested it.<commit_after>from django.db import models from django.urls import reverse TALK_STATUS_CHOICES = ( ('S', 'Submitted'), ('A', 'Approved'), ('R', 'Rejected'), ('C', 'Confirmed'), ) class Talk(models.Model): speaker_name = models.CharField(max_length=1000) speaker_email = models.CharField(max_length=1000) title = models.CharField(max_length=1000) description = models.TextField() sessions_available = models.ManyToManyField( 'Session', related_name='talks_available') status = models.CharField( max_length=1, choices=TALK_STATUS_CHOICES, default='S') def get_absolute_url(self): return reverse('talks-talks-id', args=[self.id]) def __str__(self): return self.speaker_name class Session(models.Model): date = models.DateField() description = models.TextField( blank=True, help_text='Any special theme or info about the session.') def __str__(self): return '{} - {} '.format(self.date, self.description) def approved_talks(self): return self.talks_available.filter(status__in=('A', 'C')) def get_absolute_url(self): return reverse('talks-sessions-id', args=[self.id])
9c34c9cfca30104d5bd17b38df5fa50cb24ee9ae
tests/write_abort_test.py
tests/write_abort_test.py
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value')
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 try: # set when running full test suite if any earlier tests # failed in Python code called from C del sys.last_value except AttributeError: pass # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value')
Handle the possibility of other tests failing in Python code called from C
Handle the possibility of other tests failing in Python code called from C
Python
lgpl-2.1
pycurl/pycurl,pycurl/pycurl,pycurl/pycurl
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value') Handle the possibility of other tests failing in Python code called from C
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 try: # set when running full test suite if any earlier tests # failed in Python code called from C del sys.last_value except AttributeError: pass # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value')
<commit_before>#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value') <commit_msg>Handle the possibility of other tests failing in Python code called from C<commit_after>
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 try: # set when running full test suite if any earlier tests # failed in Python code called from C del sys.last_value except AttributeError: pass # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value')
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value') Handle the possibility of other tests failing in Python code called from C#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 try: # set when running full test suite if any earlier tests # failed in Python code called from C del sys.last_value except AttributeError: pass # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value')
<commit_before>#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value') <commit_msg>Handle the possibility of other tests failing in Python code called from C<commit_after>#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # vi:ts=4:et import os.path import pycurl import sys import unittest class WriteAbortTest(unittest.TestCase): def setUp(self): self.curl = pycurl.Curl() def tearDown(self): self.curl.close() def test_write_abort(self): def write_cb(_): # this should cause pycurl.WRITEFUNCTION (without any range errors) return -1 try: # set when running full test suite if any earlier tests # failed in Python code called from C del sys.last_value except AttributeError: pass # download the script itself through the file:// protocol into write_cb self.curl.setopt(pycurl.URL, 'file://' + os.path.abspath(sys.argv[0])) self.curl.setopt(pycurl.WRITEFUNCTION, write_cb) try: self.curl.perform() except pycurl.error: err, msg = sys.exc_info()[1] # we expect pycurl.E_WRITE_ERROR as the response assert pycurl.E_WRITE_ERROR == err # no additional errors should be reported assert not hasattr(sys, 'last_value')
bf2cc432261394a2134c0fe889f28085e9679771
requests_cache/__init__.py
requests_cache/__init__.py
#!/usr/bin/env python # flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass
# flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass
Remove shebang from top-level init file
Remove shebang from top-level init file
Python
bsd-2-clause
reclosedev/requests-cache
#!/usr/bin/env python # flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass Remove shebang from top-level init file
# flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass
<commit_before>#!/usr/bin/env python # flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass <commit_msg>Remove shebang from top-level init file<commit_after>
# flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass
#!/usr/bin/env python # flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass Remove shebang from top-level init file# flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass
<commit_before>#!/usr/bin/env python # flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass <commit_msg>Remove shebang from top-level init file<commit_after># flake8: noqa: E402,F401 __version__ = '0.6.1' try: from .response import AnyResponse, CachedHTTPResponse, CachedResponse, ExpirationTime from .session import ALL_METHODS, CachedSession, CacheMixin from .patcher import ( clear, disabled, enabled, get_cache, install_cache, is_installed, remove_expired_responses, uninstall_cache, ) # Quietly ignore ImportError, if setup.py is invoked outside a virtualenv except ImportError: pass
ef55de7907fa84ccc9da7bee7aae650a8c82eecf
fileupload/serialize.py
fileupload/serialize.py
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub (r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub(r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
Remove extra space for method call.
Remove extra space for method call.
Python
mit
sigurdga/django-jquery-file-upload,extremoburo/django-jquery-file-upload,Imaginashion/cloud-vision,vaniakov/django-jquery-file-upload,minhlongdo/django-jquery-file-upload,minhlongdo/django-jquery-file-upload,vaniakov/django-jquery-file-upload,Imaginashion/cloud-vision,extremoburo/django-jquery-file-upload,sigurdga/django-jquery-file-upload,vaniakov/django-jquery-file-upload,minhlongdo/django-jquery-file-upload,Imaginashion/cloud-vision,Imaginashion/cloud-vision,extremoburo/django-jquery-file-upload,Imaginashion/cloud-vision,indrajithi/mgc-django,indrajithi/mgc-django,sigurdga/django-jquery-file-upload,Imaginashion/cloud-vision
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub (r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', } Remove extra space for method call.
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub(r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
<commit_before># encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub (r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', } <commit_msg>Remove extra space for method call.<commit_after>
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub(r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub (r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', } Remove extra space for method call.# encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub(r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
<commit_before># encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub (r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', } <commit_msg>Remove extra space for method call.<commit_after># encoding: utf-8 import mimetypes import re from django.core.urlresolvers import reverse def order_name(name): """order_name -- Limit the name to 20 chars length, and convert to a ellipsed string. name -- text to be limited. """ name = re.sub(r'^.*/', '', name) if len(name)>20: return name[:10] + "..." + name[-7:] else: return name def serialize(instance): """serialize -- Serialize a Picture instance into a `json` object. instance -- Picture instance """ return { 'url': instance.file.url, 'name': order_name(instance.file.name), 'type': mimetypes.guess_type(instance.file.path)[0] or 'image/png', 'thumbnailUrl': instance.file.url, 'size': instance.file.size, 'deleteUrl': reverse('upload-delete', args=[instance.pk]), 'deleteType': 'DELETE', }
2e2a0f403b748015574cdbb96a6135ac28c074c0
fortdepend/smartopen.py
fortdepend/smartopen.py
import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename is not "-": fh.close()
import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename != "-": fh.close()
Fix syntax warning in `smart_open`
Fix syntax warning in `smart_open` Fixes #20
Python
mit
ZedThree/fort_depend.py,ZedThree/fort_depend.py
import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename is not "-": fh.close() Fix syntax warning in `smart_open` Fixes #20
import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename != "-": fh.close()
<commit_before>import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename is not "-": fh.close() <commit_msg>Fix syntax warning in `smart_open` Fixes #20<commit_after>
import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename != "-": fh.close()
import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename is not "-": fh.close() Fix syntax warning in `smart_open` Fixes #20import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename != "-": fh.close()
<commit_before>import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename is not "-": fh.close() <commit_msg>Fix syntax warning in `smart_open` Fixes #20<commit_after>import sys import contextlib @contextlib.contextmanager def smart_open(filename, mode="Ur"): """Open stdin or stdout using a contextmanager From: http://stackoverflow.com/a/29824059/2043465 Args: filename (str): name of file to open. Can be '-' for stdin/stdout mode (str): usual mode string for :py:func:`open` """ if filename == "-": if mode is None or mode == "" or "r" in mode: fh = sys.stdin else: fh = sys.stdout else: fh = open(filename, mode) try: yield fh finally: if filename != "-": fh.close()
ca20aacb5a862fa46fbdf5b8de1c6c77dc6cbb18
problems/problem_22.py
problems/problem_22.py
# Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()
# Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()
Add whitespace on problem 22
Add whitespace on problem 22
Python
mit
edmondkotowski/project-euler
# Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()Add whitespace on problem 22
# Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()
<commit_before># Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()<commit_msg>Add whitespace on problem 22<commit_after>
# Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()
# Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()Add whitespace on problem 22# Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()
<commit_before># Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()<commit_msg>Add whitespace on problem 22<commit_after># Names scores # Total names scores from names.txt def get_names(): f = open('files/names.txt', 'r') names = f.read() return sorted(names.split(',')) def names_scores(): total_name_score = 0 count = 1 names = get_names() for name in names: name = name.replace('"', "") name_sum = 0 for char in name: name_sum += ord(char) - ord('A') + 1 total_name_score += count * name_sum count += 1 return total_name_score print names_scores()
dd31ff9372f587cf2fd7e634f3c6886fa9beedc0
examples/pywapi-example.py
examples/pywapi-example.py
#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York.\n\n" print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.")
#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York." print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.")
Fix error in example script
Fix error in example script
Python
mit
kheuton/python-weather-api
#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York.\n\n" print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.") Fix error in example script
#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York." print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.")
<commit_before>#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York.\n\n" print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.") <commit_msg>Fix error in example script<commit_after>
#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York." print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.")
#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York.\n\n" print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.") Fix error in example script#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York." print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.")
<commit_before>#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + string.lower(weather_com_result['current_conditions']['text']) + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York.\n\n" print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.") <commit_msg>Fix error in example script<commit_after>#!/usr/bin/env python import pywapi weather_com_result = pywapi.get_weather_from_weather_com('10001') yahoo_result = pywapi.get_weather_from_yahoo('10001') noaa_result = pywapi.get_weather_from_noaa('KJFK') print "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['temperature'] + "C now in New York." print("Yahoo says: It is " + yahoo_result['condition']['text'].lower() + " and " + yahoo_result['condition']['temp'] + "C now in New York.") print("NOAA says: It is " + noaa_result['weather'].lower() + " and " + noaa_result['temp_c'] + "C now in New York.")
3b7ec69c538da079d3a30db7f518aff32e20d614
coffeeraspi/coffeeraspi.py
coffeeraspi/coffeeraspi.py
#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) def main(): asyncio.get_event_loop().run_until_complete(contact_server()) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) args = parser.parse_args() server = args.server name = args.name main()
#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(server, name, coffee_queue): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) # TODO: Actually get real orders... coffee_queue.put_nowait(messages.DrinkOrder(8, {'sugar': 2}, 'coffee')) async def serial_consumer(serial_device_name, coffee_queue, mock=False): with teensy.Interface(serial_device_name, mock=mock) as interface: while True: order = await coffee_queue.get() # TODO: Process order... def main(args): loop = asyncio.get_event_loop() coffee_queue = asyncio.Queue(loop=loop) loop.run_until_complete(asyncio.gather( contact_server(args.server, args.name, coffee_queue), serial_consumer(args.serial, coffee_queue, mock=args.mock))) loop.close() if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) parser.add_argument('-s', '--serial', default=None, help='The serial device to use, or the first one detected') parser.add_argument('-S', '--mock', action='store_true', help='Mock the socket device instead of using a real one') main(parser.parse_args())
Add drink order passing in Raspberry Pi code
Add drink order passing in Raspberry Pi code
Python
apache-2.0
umbc-hackafe/htcpcp,umbc-hackafe/htcpcp,umbc-hackafe/htcpcp,umbc-hackafe/htcpcp
#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) def main(): asyncio.get_event_loop().run_until_complete(contact_server()) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) args = parser.parse_args() server = args.server name = args.name main() Add drink order passing in Raspberry Pi code
#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(server, name, coffee_queue): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) # TODO: Actually get real orders... coffee_queue.put_nowait(messages.DrinkOrder(8, {'sugar': 2}, 'coffee')) async def serial_consumer(serial_device_name, coffee_queue, mock=False): with teensy.Interface(serial_device_name, mock=mock) as interface: while True: order = await coffee_queue.get() # TODO: Process order... def main(args): loop = asyncio.get_event_loop() coffee_queue = asyncio.Queue(loop=loop) loop.run_until_complete(asyncio.gather( contact_server(args.server, args.name, coffee_queue), serial_consumer(args.serial, coffee_queue, mock=args.mock))) loop.close() if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) parser.add_argument('-s', '--serial', default=None, help='The serial device to use, or the first one detected') parser.add_argument('-S', '--mock', action='store_true', help='Mock the socket device instead of using a real one') main(parser.parse_args())
<commit_before>#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) def main(): asyncio.get_event_loop().run_until_complete(contact_server()) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) args = parser.parse_args() server = args.server name = args.name main() <commit_msg>Add drink order passing in Raspberry Pi code<commit_after>
#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(server, name, coffee_queue): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) # TODO: Actually get real orders... coffee_queue.put_nowait(messages.DrinkOrder(8, {'sugar': 2}, 'coffee')) async def serial_consumer(serial_device_name, coffee_queue, mock=False): with teensy.Interface(serial_device_name, mock=mock) as interface: while True: order = await coffee_queue.get() # TODO: Process order... def main(args): loop = asyncio.get_event_loop() coffee_queue = asyncio.Queue(loop=loop) loop.run_until_complete(asyncio.gather( contact_server(args.server, args.name, coffee_queue), serial_consumer(args.serial, coffee_queue, mock=args.mock))) loop.close() if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) parser.add_argument('-s', '--serial', default=None, help='The serial device to use, or the first one detected') parser.add_argument('-S', '--mock', action='store_true', help='Mock the socket device instead of using a real one') main(parser.parse_args())
#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) def main(): asyncio.get_event_loop().run_until_complete(contact_server()) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) args = parser.parse_args() server = args.server name = args.name main() Add drink order passing in Raspberry Pi code#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(server, name, coffee_queue): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) # TODO: Actually get real orders... coffee_queue.put_nowait(messages.DrinkOrder(8, {'sugar': 2}, 'coffee')) async def serial_consumer(serial_device_name, coffee_queue, mock=False): with teensy.Interface(serial_device_name, mock=mock) as interface: while True: order = await coffee_queue.get() # TODO: Process order... def main(args): loop = asyncio.get_event_loop() coffee_queue = asyncio.Queue(loop=loop) loop.run_until_complete(asyncio.gather( contact_server(args.server, args.name, coffee_queue), serial_consumer(args.serial, coffee_queue, mock=args.mock))) loop.close() if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) parser.add_argument('-s', '--serial', default=None, help='The serial device to use, or the first one detected') parser.add_argument('-S', '--mock', action='store_true', help='Mock the socket device instead of using a real one') main(parser.parse_args())
<commit_before>#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) def main(): asyncio.get_event_loop().run_until_complete(contact_server()) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) args = parser.parse_args() server = args.server name = args.name main() <commit_msg>Add drink order passing in Raspberry Pi code<commit_after>#!env/bin/python3 import argparse import asyncio import json import socket import websockets import teensy import messages async def contact_server(server, name, coffee_queue): async with websockets.connect(server) as sock: await sock.send(json.dumps(dict( message='Hello', name=name, id=None, # In theory we would provide a unique ID for each machine, but we only have one... ))) resp = await sock.recv() # Handle new response print(json.loads(resp)) # TODO: Actually get real orders... coffee_queue.put_nowait(messages.DrinkOrder(8, {'sugar': 2}, 'coffee')) async def serial_consumer(serial_device_name, coffee_queue, mock=False): with teensy.Interface(serial_device_name, mock=mock) as interface: while True: order = await coffee_queue.get() # TODO: Process order... def main(args): loop = asyncio.get_event_loop() coffee_queue = asyncio.Queue(loop=loop) loop.run_until_complete(asyncio.gather( contact_server(args.server, args.name, coffee_queue), serial_consumer(args.serial, coffee_queue, mock=args.mock))) loop.close() if __name__ == "__main__": parser = argparse.ArgumentParser(description='Client for connecting to AWS') parser.add_argument('server', help='The server to connect to') parser.add_argument( '-n', '--name', default=socket.gethostname(), help='The name of this client coffee machine' ) parser.add_argument('-s', '--serial', default=None, help='The serial device to use, or the first one detected') parser.add_argument('-S', '--mock', action='store_true', help='Mock the socket device instead of using a real one') main(parser.parse_args())
54ee71dbc3526886f0fd44fa182c18c1fb1e3ffb
mysite/missions/irc/ircmissionbot.py
mysite/missions/irc/ircmissionbot.py
from django.conf import settings from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel)
from django.conf import settings from mysite.missions.models import IrcMissionSession from mysite.missions.base import controllers from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel) IrcMissionSession.objects.all().delete() def setup_session(self, nick, conn): # Someone has joined the channel. password = controllers.make_password() IrcMissionSession(nick=nick, password=password).save() conn.notice(nick, 'Hello, %(nick)s! To start the mission, here are the words to type into the mission page: %(password)s' % {'nick': nick, 'password': password}) def on_join(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel and nick != conn.get_nickname(): self.setup_session(nick, conn) def on_namreply(self, conn, event): channel = event.arguments()[1] nicks = event.arguments()[2].split() for nick in nicks: if nick[0] in '@+': nick = nick[1:] # remove op/voice prefix self.setup_session(nick, conn) def on_part(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete() def on_kick(self, conn, event): nick = event.arguments()[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete()
Make the bot track nicks in the channel and maintain exactly one IrcMissionSession per nick.
Make the bot track nicks in the channel and maintain exactly one IrcMissionSession per nick.
Python
agpl-3.0
sudheesh001/oh-mainline,willingc/oh-mainline,moijes12/oh-mainline,waseem18/oh-mainline,nirmeshk/oh-mainline,openhatch/oh-mainline,openhatch/oh-mainline,vipul-sharma20/oh-mainline,sudheesh001/oh-mainline,willingc/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,SnappleCap/oh-mainline,onceuponatimeforever/oh-mainline,vipul-sharma20/oh-mainline,waseem18/oh-mainline,moijes12/oh-mainline,Changaco/oh-mainline,onceuponatimeforever/oh-mainline,Changaco/oh-mainline,SnappleCap/oh-mainline,sudheesh001/oh-mainline,onceuponatimeforever/oh-mainline,vipul-sharma20/oh-mainline,onceuponatimeforever/oh-mainline,moijes12/oh-mainline,moijes12/oh-mainline,sudheesh001/oh-mainline,openhatch/oh-mainline,ojengwa/oh-mainline,nirmeshk/oh-mainline,SnappleCap/oh-mainline,eeshangarg/oh-mainline,waseem18/oh-mainline,willingc/oh-mainline,ehashman/oh-mainline,ehashman/oh-mainline,eeshangarg/oh-mainline,waseem18/oh-mainline,nirmeshk/oh-mainline,vipul-sharma20/oh-mainline,ehashman/oh-mainline,waseem18/oh-mainline,openhatch/oh-mainline,onceuponatimeforever/oh-mainline,sudheesh001/oh-mainline,ehashman/oh-mainline,ehashman/oh-mainline,nirmeshk/oh-mainline,ojengwa/oh-mainline,willingc/oh-mainline,vipul-sharma20/oh-mainline,moijes12/oh-mainline,eeshangarg/oh-mainline,SnappleCap/oh-mainline,Changaco/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,willingc/oh-mainline,SnappleCap/oh-mainline,eeshangarg/oh-mainline,eeshangarg/oh-mainline,ojengwa/oh-mainline
from django.conf import settings from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel) Make the bot track nicks in the channel and maintain exactly one IrcMissionSession per nick.
from django.conf import settings from mysite.missions.models import IrcMissionSession from mysite.missions.base import controllers from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel) IrcMissionSession.objects.all().delete() def setup_session(self, nick, conn): # Someone has joined the channel. password = controllers.make_password() IrcMissionSession(nick=nick, password=password).save() conn.notice(nick, 'Hello, %(nick)s! To start the mission, here are the words to type into the mission page: %(password)s' % {'nick': nick, 'password': password}) def on_join(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel and nick != conn.get_nickname(): self.setup_session(nick, conn) def on_namreply(self, conn, event): channel = event.arguments()[1] nicks = event.arguments()[2].split() for nick in nicks: if nick[0] in '@+': nick = nick[1:] # remove op/voice prefix self.setup_session(nick, conn) def on_part(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete() def on_kick(self, conn, event): nick = event.arguments()[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete()
<commit_before>from django.conf import settings from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel) <commit_msg>Make the bot track nicks in the channel and maintain exactly one IrcMissionSession per nick.<commit_after>
from django.conf import settings from mysite.missions.models import IrcMissionSession from mysite.missions.base import controllers from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel) IrcMissionSession.objects.all().delete() def setup_session(self, nick, conn): # Someone has joined the channel. password = controllers.make_password() IrcMissionSession(nick=nick, password=password).save() conn.notice(nick, 'Hello, %(nick)s! To start the mission, here are the words to type into the mission page: %(password)s' % {'nick': nick, 'password': password}) def on_join(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel and nick != conn.get_nickname(): self.setup_session(nick, conn) def on_namreply(self, conn, event): channel = event.arguments()[1] nicks = event.arguments()[2].split() for nick in nicks: if nick[0] in '@+': nick = nick[1:] # remove op/voice prefix self.setup_session(nick, conn) def on_part(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete() def on_kick(self, conn, event): nick = event.arguments()[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete()
from django.conf import settings from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel) Make the bot track nicks in the channel and maintain exactly one IrcMissionSession per nick.from django.conf import settings from mysite.missions.models import IrcMissionSession from mysite.missions.base import controllers from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel) IrcMissionSession.objects.all().delete() def setup_session(self, nick, conn): # Someone has joined the channel. password = controllers.make_password() IrcMissionSession(nick=nick, password=password).save() conn.notice(nick, 'Hello, %(nick)s! To start the mission, here are the words to type into the mission page: %(password)s' % {'nick': nick, 'password': password}) def on_join(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel and nick != conn.get_nickname(): self.setup_session(nick, conn) def on_namreply(self, conn, event): channel = event.arguments()[1] nicks = event.arguments()[2].split() for nick in nicks: if nick[0] in '@+': nick = nick[1:] # remove op/voice prefix self.setup_session(nick, conn) def on_part(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete() def on_kick(self, conn, event): nick = event.arguments()[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete()
<commit_before>from django.conf import settings from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel) <commit_msg>Make the bot track nicks in the channel and maintain exactly one IrcMissionSession per nick.<commit_after>from django.conf import settings from mysite.missions.models import IrcMissionSession from mysite.missions.base import controllers from ircbot import SingleServerIRCBot class IrcMissionBot(SingleServerIRCBot): def __init__(self): SingleServerIRCBot.__init__(self, [settings.IRC_MISSION_SERVER], settings.IRC_MISSIONBOT_NICK, settings.IRC_MISSIONBOT_REALNAME) self.channel = settings.IRC_MISSION_CHANNEL def on_nicknameinuse(self, conn, event): conn.nick(conn.get_nickname() + '_') def on_welcome(self, conn, event): conn.join(self.channel) IrcMissionSession.objects.all().delete() def setup_session(self, nick, conn): # Someone has joined the channel. password = controllers.make_password() IrcMissionSession(nick=nick, password=password).save() conn.notice(nick, 'Hello, %(nick)s! To start the mission, here are the words to type into the mission page: %(password)s' % {'nick': nick, 'password': password}) def on_join(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel and nick != conn.get_nickname(): self.setup_session(nick, conn) def on_namreply(self, conn, event): channel = event.arguments()[1] nicks = event.arguments()[2].split() for nick in nicks: if nick[0] in '@+': nick = nick[1:] # remove op/voice prefix self.setup_session(nick, conn) def on_part(self, conn, event): nick = event.source().split('!')[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete() def on_kick(self, conn, event): nick = event.arguments()[0] channel = event.target() if channel == self.channel: IrcMissionSession.objects.filter(nick=nick).delete()
796d74c5b666ee237afa95a18e1dc91a51b0cc7c
django_cron/management/commands/cronjobs.py
django_cron/management/commands/cronjobs.py
# # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "cronjobs for %s finished" % settings.SITE_NAME
# # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from datetime import datetime from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "%s cronjobs for %s finished" % (datetime.now(), settings.SITE_NAME)
Change crontab finished message to include the current time.
Change crontab finished message to include the current time.
Python
mit
Ixxy-Open-Source/django-cron,peterbe/django-cron
# # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "cronjobs for %s finished" % settings.SITE_NAME Change crontab finished message to include the current time.
# # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from datetime import datetime from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "%s cronjobs for %s finished" % (datetime.now(), settings.SITE_NAME)
<commit_before># # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "cronjobs for %s finished" % settings.SITE_NAME <commit_msg>Change crontab finished message to include the current time.<commit_after>
# # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from datetime import datetime from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "%s cronjobs for %s finished" % (datetime.now(), settings.SITE_NAME)
# # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "cronjobs for %s finished" % settings.SITE_NAME Change crontab finished message to include the current time.# # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from datetime import datetime from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "%s cronjobs for %s finished" % (datetime.now(), settings.SITE_NAME)
<commit_before># # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "cronjobs for %s finished" % settings.SITE_NAME <commit_msg>Change crontab finished message to include the current time.<commit_after># # run the cron service (intended to be executed from a cron job) # # usage: manage.py cronjobs from datetime import datetime from django.conf import settings from django.core.management.base import NoArgsCommand import django_cron class Command(NoArgsCommand): help = "run the cron services (intended to be executed from a cron job)" def handle_noargs(self, **options): django_cron.autodiscover(start_timer=False, registering=False) print "%s cronjobs for %s finished" % (datetime.now(), settings.SITE_NAME)
a1f9399657c3b874e53d2c7e54df8960350c83f1
lib/reinteract/custom_result.py
lib/reinteract/custom_result.py
# Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time)
# Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu.attach_to_widget(widget, None) menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time)
Attach custom result popup menu to widget
Attach custom result popup menu to widget Call gtk.Menu.attach_to_widget() on the popup menu for custom results. This should have little practical result one way or the other, though it is theoretically "right", but it has the useful side-effect of getting the menu into the right GtkWindowGroup. Again that should have little practical effect, but importantly it works around a gtk-quartz bug that otherwise causes the menu not to pop down when clicking away. (http://bugzilla.gnome.org/show_bug.cgi?id=557894)
Python
bsd-2-clause
alexey4petrov/reinteract,rschroll/reinteract,johnrizzo1/reinteract,jbaayen/reinteract,johnrizzo1/reinteract,alexey4petrov/reinteract,jbaayen/reinteract,jbaayen/reinteract,rschroll/reinteract,rschroll/reinteract,johnrizzo1/reinteract,alexey4petrov/reinteract
# Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time) Attach custom result popup menu to widget Call gtk.Menu.attach_to_widget() on the popup menu for custom results. This should have little practical result one way or the other, though it is theoretically "right", but it has the useful side-effect of getting the menu into the right GtkWindowGroup. Again that should have little practical effect, but importantly it works around a gtk-quartz bug that otherwise causes the menu not to pop down when clicking away. (http://bugzilla.gnome.org/show_bug.cgi?id=557894)
# Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu.attach_to_widget(widget, None) menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time)
<commit_before># Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time) <commit_msg>Attach custom result popup menu to widget Call gtk.Menu.attach_to_widget() on the popup menu for custom results. This should have little practical result one way or the other, though it is theoretically "right", but it has the useful side-effect of getting the menu into the right GtkWindowGroup. Again that should have little practical effect, but importantly it works around a gtk-quartz bug that otherwise causes the menu not to pop down when clicking away. (http://bugzilla.gnome.org/show_bug.cgi?id=557894)<commit_after>
# Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu.attach_to_widget(widget, None) menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time)
# Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time) Attach custom result popup menu to widget Call gtk.Menu.attach_to_widget() on the popup menu for custom results. This should have little practical result one way or the other, though it is theoretically "right", but it has the useful side-effect of getting the menu into the right GtkWindowGroup. Again that should have little practical effect, but importantly it works around a gtk-quartz bug that otherwise causes the menu not to pop down when clicking away. (http://bugzilla.gnome.org/show_bug.cgi?id=557894)# Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu.attach_to_widget(widget, None) menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time)
<commit_before># Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time) <commit_msg>Attach custom result popup menu to widget Call gtk.Menu.attach_to_widget() on the popup menu for custom results. This should have little practical result one way or the other, though it is theoretically "right", but it has the useful side-effect of getting the menu into the right GtkWindowGroup. Again that should have little practical effect, but importantly it works around a gtk-quartz bug that otherwise causes the menu not to pop down when clicking away. (http://bugzilla.gnome.org/show_bug.cgi?id=557894)<commit_after># Copyright 2007 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import gtk class CustomResult(object): def create_widget(self): raise NotImplementedError() def show_menu(widget, event, save_callback=None): """Convenience function to create a right-click menu with a Save As option""" toplevel = widget.get_toplevel() menu = gtk.Menu() menu.attach_to_widget(widget, None) menu_item = gtk.ImageMenuItem(stock_id=gtk.STOCK_SAVE_AS) menu_item.show() menu.add(menu_item) def on_selection_done(menu): menu.destroy() menu.connect('selection-done', on_selection_done) def on_activate(menu): chooser = gtk.FileChooserDialog("Save As...", toplevel, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_default_response(gtk.RESPONSE_OK) response = chooser.run() filename = None if response == gtk.RESPONSE_OK: filename = chooser.get_filename() chooser.destroy() if filename != None: save_callback(filename) menu_item.connect('activate', on_activate) menu.popup(None, None, None, event.button, event.time)
ee4ebc441927a4060d38d702891c1a171bd3932c
pytask/urls.py
pytask/urls.py
from django.conf.urls.defaults import * from registration.views import register from registration.backends.default import DefaultBackend import pytask.profile.regbackend from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.shortcuts import redirect # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), )
from django.conf import settings from django.conf.urls.defaults import * from registration.views import register from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), ) # Serve static files in DEVELOPMENT = True mode if settings.DEVELOPMENT: urlpatterns += patterns('', (r'^pytask/media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), (r'^pytask/static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), )
Add a DEVELOPMENT settings for URL mapping for static and media files.
Add a DEVELOPMENT settings for URL mapping for static and media files.
Python
agpl-3.0
madhusudancs/pytask,madhusudancs/pytask,madhusudancs/pytask
from django.conf.urls.defaults import * from registration.views import register from registration.backends.default import DefaultBackend import pytask.profile.regbackend from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.shortcuts import redirect # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), ) Add a DEVELOPMENT settings for URL mapping for static and media files.
from django.conf import settings from django.conf.urls.defaults import * from registration.views import register from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), ) # Serve static files in DEVELOPMENT = True mode if settings.DEVELOPMENT: urlpatterns += patterns('', (r'^pytask/media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), (r'^pytask/static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), )
<commit_before>from django.conf.urls.defaults import * from registration.views import register from registration.backends.default import DefaultBackend import pytask.profile.regbackend from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.shortcuts import redirect # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), ) <commit_msg>Add a DEVELOPMENT settings for URL mapping for static and media files.<commit_after>
from django.conf import settings from django.conf.urls.defaults import * from registration.views import register from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), ) # Serve static files in DEVELOPMENT = True mode if settings.DEVELOPMENT: urlpatterns += patterns('', (r'^pytask/media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), (r'^pytask/static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), )
from django.conf.urls.defaults import * from registration.views import register from registration.backends.default import DefaultBackend import pytask.profile.regbackend from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.shortcuts import redirect # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), ) Add a DEVELOPMENT settings for URL mapping for static and media files.from django.conf import settings from django.conf.urls.defaults import * from registration.views import register from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), ) # Serve static files in DEVELOPMENT = True mode if settings.DEVELOPMENT: urlpatterns += patterns('', (r'^pytask/media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), (r'^pytask/static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), )
<commit_before>from django.conf.urls.defaults import * from registration.views import register from registration.backends.default import DefaultBackend import pytask.profile.regbackend from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.shortcuts import redirect # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), ) <commit_msg>Add a DEVELOPMENT settings for URL mapping for static and media files.<commit_after>from django.conf import settings from django.conf.urls.defaults import * from registration.views import register from pytask.profile.forms import CustomRegistrationForm from pytask.views import home_page from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^pytask/', include('pytask.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './pytask/static/'}), url(r'^accounts/register/$', register, {'form_class': CustomRegistrationForm, 'backend': 'registration.backends.default.DefaultBackend'}, name='registration_register'), (r'^accounts/', include('registration.urls')), (r'^profile/', include('pytask.profile.urls')), (r'^task/', include('pytask.taskapp.urls')), (r'^$', home_page), ) # Serve static files in DEVELOPMENT = True mode if settings.DEVELOPMENT: urlpatterns += patterns('', (r'^pytask/media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), (r'^pytask/static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), )
a9176b1fc9116601a98c53a84cff57d9692e1fa4
query/forms.py
query/forms.py
""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField(max_length=100)
""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField( label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'IPv4/6 address'}) )
Remove label and add placeholder to Query field.
Remove label and add placeholder to Query field.
Python
mit
cdubz/rdap-explorer,cdubz/rdap-explorer
""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField(max_length=100) Remove label and add placeholder to Query field.
""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField( label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'IPv4/6 address'}) )
<commit_before>""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField(max_length=100) <commit_msg>Remove label and add placeholder to Query field.<commit_after>
""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField( label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'IPv4/6 address'}) )
""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField(max_length=100) Remove label and add placeholder to Query field.""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField( label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'IPv4/6 address'}) )
<commit_before>""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField(max_length=100) <commit_msg>Remove label and add placeholder to Query field.<commit_after>""" Forms for the rdap_explorer project, query app. """ from django import forms class QueryForm(forms.Form): query = forms.CharField( label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'IPv4/6 address'}) )
5d90dfc56423ccd65a7123b6c37e9ec869010d4b
django_foodbot/api/serializers.py
django_foodbot/api/serializers.py
from rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week')
from rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'rate', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week')
Add rating to api serializer
Add rating to api serializer
Python
mit
andela-kanyanwu/food-bot-review
from rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week') Add rating to api serializer
from rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'rate', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week')
<commit_before>from rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week') <commit_msg>Add rating to api serializer<commit_after>
from rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'rate', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week')
from rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week') Add rating to api serializerfrom rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'rate', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week')
<commit_before>from rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week') <commit_msg>Add rating to api serializer<commit_after>from rest_framework import serializers from api.models import Menu, Rating class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('id', 'date', 'user_id', 'menu', 'rate', 'comment') class MenuSerializer(serializers.ModelSerializer): rating = RatingSerializer(many=True, read_only=True) class Meta: model = Menu fields = ('id', 'day', 'rating', 'food', 'meal', 'option', 'week')
183d6ac13a38877a9b7b1396d98529f0ecf5e5a5
pocs/state/states/default/analyzing.py
pocs/state/states/default/analyzing.py
def on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if (observation.current_exp - observation.min_nexp) % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking'
def on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if observation.current_exp >= observation.min_nexp: if observation.current_exp % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking'
Fix the scheduling / tracking check
Fix the scheduling / tracking check
Python
mit
panoptes/POCS,AstroHuntsman/POCS,panoptes/POCS,joshwalawender/POCS,AstroHuntsman/POCS,AstroHuntsman/POCS,joshwalawender/POCS,panoptes/POCS,panoptes/POCS,AstroHuntsman/POCS,joshwalawender/POCS
def on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if (observation.current_exp - observation.min_nexp) % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking' Fix the scheduling / tracking check
def on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if observation.current_exp >= observation.min_nexp: if observation.current_exp % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking'
<commit_before>def on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if (observation.current_exp - observation.min_nexp) % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking' <commit_msg>Fix the scheduling / tracking check<commit_after>
def on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if observation.current_exp >= observation.min_nexp: if observation.current_exp % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking'
def on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if (observation.current_exp - observation.min_nexp) % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking' Fix the scheduling / tracking checkdef on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if observation.current_exp >= observation.min_nexp: if observation.current_exp % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking'
<commit_before>def on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if (observation.current_exp - observation.min_nexp) % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking' <commit_msg>Fix the scheduling / tracking check<commit_after>def on_enter(event_data): """ """ pocs = event_data.model pocs.say("Analyzing image...") try: observation = pocs.observatory.current_observation image_info = pocs.observatory.analyze_recent() pocs.logger.debug("Image information: {}".format(image_info)) pocs.logger.debug("Observation exposure: {} / {}".format(observation.current_exp, observation.min_nexp)) if observation.current_exp >= observation.min_nexp: if observation.current_exp % observation.exp_set_size == 0: pocs.next_state = 'scheduling' else: pocs.next_state = 'tracking' except Exception as e: pocs.logger.error("Problem in analyzing: {}".format(e)) pocs.next_state = 'parking'
21c1cf2d920aebe704c478380e4e8e8974dc148e
python2.7libs/CacheManager/define.py
python2.7libs/CacheManager/define.py
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache" "alembic", # "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #-------------------------------------------------------------------------------
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache", "alembic", "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #-------------------------------------------------------------------------------
Include "filecache" and "alembicarchive" selection.
Include "filecache" and "alembicarchive" selection.
Python
mit
takavfx/Bento
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache" "alembic", # "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #------------------------------------------------------------------------------- Include "filecache" and "alembicarchive" selection.
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache", "alembic", "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #-------------------------------------------------------------------------------
<commit_before># -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache" "alembic", # "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #------------------------------------------------------------------------------- <commit_msg>Include "filecache" and "alembicarchive" selection.<commit_after>
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache", "alembic", "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #-------------------------------------------------------------------------------
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache" "alembic", # "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #------------------------------------------------------------------------------- Include "filecache" and "alembicarchive" selection.# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache", "alembic", "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #-------------------------------------------------------------------------------
<commit_before># -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache" "alembic", # "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #------------------------------------------------------------------------------- <commit_msg>Include "filecache" and "alembicarchive" selection.<commit_after># -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- # Define Cache Nodes to deal with this script CACHE_NODES = [ "file", "filecache", "alembic", "alembicarchive" ] # Define Houdini Environment Varialbes. This will also be used for displaying. ENV_TYPE = [ '-', 'HIP', 'JOB' ] # Define Header Items CACHE_ITEMS = [ { "key": "name", "display": "Name", "width": 100, "visible": False}, { "key": "node", "display": "Node", "width": 200, "visible": True}, { "key": "cache_path", "display": "Cache Path", "width": 500, "visible": True}, { "key": "srcStatus", "display": "Status", "width": 50, "visible": True}, { "key": "env", "display": "Env", "width": 50, "visible": False}, { "key": "expanded_path", "display": "Expanded path", "width": 200, "visible": False}, { "key": "color", "display": "Color", "width": None, "visible": False} ] # Menu Items MENU_HELP = "Help" MENU_RELOAD = "Reload" #------------------------------------------------------------------------------- # EOF #-------------------------------------------------------------------------------
c932b8ff7b48c30c6fae70d22f16a551c50ffd6b
regserver/regulations/views/utils.py
regserver/regulations/views/utils.py
from django.conf import settings from regulations.generator import generator from django.core.urlresolvers import get_script_prefix def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' context['APP_PREFIX'] = get_script_prefix() context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context
from django.conf import settings from regulations.generator import generator from django.core.urlresolvers import reverse def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' prefix = reverse('regulation_landing_view', kwargs={'label_id': '9999'}) prefix = prefix.replace('9999', '') if prefix != '/': # Strip final slash prefix = prefix[:-1] context['APP_PREFIX'] = prefix context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context
Fix error with app prefix. We will assume all urls fall under the same root as the landing page
Fix error with app prefix. We will assume all urls fall under the same root as the landing page
Python
cc0-1.0
18F/regulations-site,grapesmoker/regulations-site,grapesmoker/regulations-site,tadhg-ohiggins/regulations-site,18F/regulations-site,willbarton/regulations-site,jeremiak/regulations-site,18F/regulations-site,eregs/regulations-site,EricSchles/regulations-site,18F/regulations-site,ascott1/regulations-site,adderall/regulations-site,ascott1/regulations-site,EricSchles/regulations-site,willbarton/regulations-site,adderall/regulations-site,tadhg-ohiggins/regulations-site,EricSchles/regulations-site,jeremiak/regulations-site,jeremiak/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,adderall/regulations-site,adderall/regulations-site,eregs/regulations-site,grapesmoker/regulations-site,ascott1/regulations-site,willbarton/regulations-site,EricSchles/regulations-site,willbarton/regulations-site,ascott1/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,jeremiak/regulations-site,grapesmoker/regulations-site
from django.conf import settings from regulations.generator import generator from django.core.urlresolvers import get_script_prefix def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' context['APP_PREFIX'] = get_script_prefix() context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context Fix error with app prefix. We will assume all urls fall under the same root as the landing page
from django.conf import settings from regulations.generator import generator from django.core.urlresolvers import reverse def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' prefix = reverse('regulation_landing_view', kwargs={'label_id': '9999'}) prefix = prefix.replace('9999', '') if prefix != '/': # Strip final slash prefix = prefix[:-1] context['APP_PREFIX'] = prefix context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context
<commit_before>from django.conf import settings from regulations.generator import generator from django.core.urlresolvers import get_script_prefix def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' context['APP_PREFIX'] = get_script_prefix() context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context <commit_msg>Fix error with app prefix. We will assume all urls fall under the same root as the landing page<commit_after>
from django.conf import settings from regulations.generator import generator from django.core.urlresolvers import reverse def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' prefix = reverse('regulation_landing_view', kwargs={'label_id': '9999'}) prefix = prefix.replace('9999', '') if prefix != '/': # Strip final slash prefix = prefix[:-1] context['APP_PREFIX'] = prefix context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context
from django.conf import settings from regulations.generator import generator from django.core.urlresolvers import get_script_prefix def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' context['APP_PREFIX'] = get_script_prefix() context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context Fix error with app prefix. We will assume all urls fall under the same root as the landing pagefrom django.conf import settings from regulations.generator import generator from django.core.urlresolvers import reverse def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' prefix = reverse('regulation_landing_view', kwargs={'label_id': '9999'}) prefix = prefix.replace('9999', '') if prefix != '/': # Strip final slash prefix = prefix[:-1] context['APP_PREFIX'] = prefix context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context
<commit_before>from django.conf import settings from regulations.generator import generator from django.core.urlresolvers import get_script_prefix def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' context['APP_PREFIX'] = get_script_prefix() context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context <commit_msg>Fix error with app prefix. We will assume all urls fall under the same root as the landing page<commit_after>from django.conf import settings from regulations.generator import generator from django.core.urlresolvers import reverse def get_layer_list(names): layer_names = generator.LayerCreator.LAYERS return set(l.lower() for l in names.split(',') if l.lower() in layer_names) def handle_specified_layers( layer_names, regulation_id, version, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.LayerCreator() layer_creator.add_layers(layer_list, regulation_id, version, sectional) return layer_creator.get_appliers() def handle_diff_layers( layer_names, regulation_id, older, newer, sectional=False): layer_list = get_layer_list(layer_names) layer_creator = generator.DiffLayerCreator(newer) layer_creator.add_layers(layer_list, regulation_id, older, sectional) return layer_creator.get_appliers() def add_extras(context): context['env'] = 'source' if settings.DEBUG else 'built' prefix = reverse('regulation_landing_view', kwargs={'label_id': '9999'}) prefix = prefix.replace('9999', '') if prefix != '/': # Strip final slash prefix = prefix[:-1] context['APP_PREFIX'] = prefix context['GOOGLE_ANALYTICS_SITE'] = settings.GOOGLE_ANALYTICS_SITE context['GOOGLE_ANALYTICS_ID'] = settings.GOOGLE_ANALYTICS_ID return context
b9dfbb17512b270103444d972af17c43ddbba26b
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines() print propertyList
Create documentation of DataSource Settings
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines() print propertyList
<commit_before>###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()<commit_msg>8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8<commit_after>
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines() print propertyList
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines() print propertyList
<commit_before>###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines()<commit_msg>8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8<commit_after>###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions cell = AdminControl.getCell() cellname = "/Cell:" + cell + "/" # Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines() dsidlist = [] # remove unwanted databases for db in dbs: dbname = db.split('(') n = 0 for i in dbname: # i is only the name of the DataSource, db is DataSource ID! if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource': dsidlist.append(str(db).replace('"','')) n += 1 dsidlist.sort() for dsid in dsidlist: propertySet = AdminConfig.showAttribute(dsid,"propertySet") propertyList = AdminConfig.list("J2EEResourceProperty", propertySet).splitlines() print propertyList
134bc5f48fd8a80f84ae91531b40263fcbaedfe1
serrano/urls.py
serrano/urls.py
import time from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), )
from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), )
Remove intentional unused import to clean branch
Remove intentional unused import to clean branch
Python
bsd-2-clause
chop-dbhi/serrano,rv816/serrano_night,chop-dbhi/serrano,rv816/serrano_night
import time from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), ) Remove intentional unused import to clean branch
from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), )
<commit_before>import time from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), ) <commit_msg>Remove intentional unused import to clean branch<commit_after>
from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), )
import time from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), ) Remove intentional unused import to clean branchfrom django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), )
<commit_before>import time from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), ) <commit_msg>Remove intentional unused import to clean branch<commit_after>from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), )
2c0b25a4d978999617a22f33c8109fd35cfe657a
natasha/data/__init__.py
natasha/data/__init__.py
# coding: utf-8 from __future__ import unicode_literals import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: line = line.rstrip('\n') line = maybe_strip_comment(line) yield line
# coding: utf-8 from __future__ import unicode_literals from yargy.compat import RUNNING_ON_PYTHON_2_VERSION import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: if RUNNING_ON_PYTHON_2_VERSION: line = line.decode('utf-8') line = line.rstrip('\n') line = maybe_strip_comment(line) yield line
Fix encoding problems with py2
Fix encoding problems with py2
Python
mit
natasha/natasha
# coding: utf-8 from __future__ import unicode_literals import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: line = line.rstrip('\n') line = maybe_strip_comment(line) yield line Fix encoding problems with py2
# coding: utf-8 from __future__ import unicode_literals from yargy.compat import RUNNING_ON_PYTHON_2_VERSION import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: if RUNNING_ON_PYTHON_2_VERSION: line = line.decode('utf-8') line = line.rstrip('\n') line = maybe_strip_comment(line) yield line
<commit_before># coding: utf-8 from __future__ import unicode_literals import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: line = line.rstrip('\n') line = maybe_strip_comment(line) yield line <commit_msg>Fix encoding problems with py2<commit_after>
# coding: utf-8 from __future__ import unicode_literals from yargy.compat import RUNNING_ON_PYTHON_2_VERSION import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: if RUNNING_ON_PYTHON_2_VERSION: line = line.decode('utf-8') line = line.rstrip('\n') line = maybe_strip_comment(line) yield line
# coding: utf-8 from __future__ import unicode_literals import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: line = line.rstrip('\n') line = maybe_strip_comment(line) yield line Fix encoding problems with py2# coding: utf-8 from __future__ import unicode_literals from yargy.compat import RUNNING_ON_PYTHON_2_VERSION import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: if RUNNING_ON_PYTHON_2_VERSION: line = line.decode('utf-8') line = line.rstrip('\n') line = maybe_strip_comment(line) yield line
<commit_before># coding: utf-8 from __future__ import unicode_literals import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: line = line.rstrip('\n') line = maybe_strip_comment(line) yield line <commit_msg>Fix encoding problems with py2<commit_after># coding: utf-8 from __future__ import unicode_literals from yargy.compat import RUNNING_ON_PYTHON_2_VERSION import os def get_path(filename): return os.path.join(os.path.dirname(__file__), filename) def maybe_strip_comment(line): if '#' in line: line = line[:line.index('#')] line = line.rstrip() return line def load_lines(filename): path = get_path(filename) with open(path) as file: for line in file: if RUNNING_ON_PYTHON_2_VERSION: line = line.decode('utf-8') line = line.rstrip('\n') line = maybe_strip_comment(line) yield line
1e601fb99259c346497db1b5392d3d79ad6dbd8e
gmt/utils.py
gmt/utils.py
""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_mod}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def psconvert(**kwargs): ... "Full docs at {gmt_mod}" ... pass >>> print(psconvert.__doc__) Full docs at http://gmt.soest.hawaii.edu/doc/latest/psconvert.html """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) module_func.__doc__ = module_func.__doc__.format(gmt_mod=url) return module_func
""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_module_docs}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def gmtinfo(**kwargs): ... ''' ... My nice module. ... {gmt_module_docs} ... ''' ... pass >>> print(gmtinfo.__doc__) <BLANKLINE> My nice module. Full option list at http://gmt.soest.hawaii.edu/doc/latest/gmtinfo.html <BLANKLINE> """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) text = "Full option list at" full_text = ' '.join([text, url]) module_func.__doc__ = module_func.__doc__.format(gmt_module_docs=full_text) return module_func
Fix issue with spacing when inserting gmt link
Fix issue with spacing when inserting gmt link Make the entry a single line to avoid leading white space problems.
Python
bsd-3-clause
GenericMappingTools/gmt-python,GenericMappingTools/gmt-python
""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_mod}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def psconvert(**kwargs): ... "Full docs at {gmt_mod}" ... pass >>> print(psconvert.__doc__) Full docs at http://gmt.soest.hawaii.edu/doc/latest/psconvert.html """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) module_func.__doc__ = module_func.__doc__.format(gmt_mod=url) return module_func Fix issue with spacing when inserting gmt link Make the entry a single line to avoid leading white space problems.
""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_module_docs}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def gmtinfo(**kwargs): ... ''' ... My nice module. ... {gmt_module_docs} ... ''' ... pass >>> print(gmtinfo.__doc__) <BLANKLINE> My nice module. Full option list at http://gmt.soest.hawaii.edu/doc/latest/gmtinfo.html <BLANKLINE> """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) text = "Full option list at" full_text = ' '.join([text, url]) module_func.__doc__ = module_func.__doc__.format(gmt_module_docs=full_text) return module_func
<commit_before>""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_mod}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def psconvert(**kwargs): ... "Full docs at {gmt_mod}" ... pass >>> print(psconvert.__doc__) Full docs at http://gmt.soest.hawaii.edu/doc/latest/psconvert.html """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) module_func.__doc__ = module_func.__doc__.format(gmt_mod=url) return module_func <commit_msg>Fix issue with spacing when inserting gmt link Make the entry a single line to avoid leading white space problems.<commit_after>
""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_module_docs}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def gmtinfo(**kwargs): ... ''' ... My nice module. ... {gmt_module_docs} ... ''' ... pass >>> print(gmtinfo.__doc__) <BLANKLINE> My nice module. Full option list at http://gmt.soest.hawaii.edu/doc/latest/gmtinfo.html <BLANKLINE> """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) text = "Full option list at" full_text = ' '.join([text, url]) module_func.__doc__ = module_func.__doc__.format(gmt_module_docs=full_text) return module_func
""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_mod}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def psconvert(**kwargs): ... "Full docs at {gmt_mod}" ... pass >>> print(psconvert.__doc__) Full docs at http://gmt.soest.hawaii.edu/doc/latest/psconvert.html """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) module_func.__doc__ = module_func.__doc__.format(gmt_mod=url) return module_func Fix issue with spacing when inserting gmt link Make the entry a single line to avoid leading white space problems.""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_module_docs}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def gmtinfo(**kwargs): ... ''' ... My nice module. ... {gmt_module_docs} ... ''' ... pass >>> print(gmtinfo.__doc__) <BLANKLINE> My nice module. Full option list at http://gmt.soest.hawaii.edu/doc/latest/gmtinfo.html <BLANKLINE> """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) text = "Full option list at" full_text = ' '.join([text, url]) module_func.__doc__ = module_func.__doc__.format(gmt_module_docs=full_text) return module_func
<commit_before>""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_mod}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def psconvert(**kwargs): ... "Full docs at {gmt_mod}" ... pass >>> print(psconvert.__doc__) Full docs at http://gmt.soest.hawaii.edu/doc/latest/psconvert.html """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) module_func.__doc__ = module_func.__doc__.format(gmt_mod=url) return module_func <commit_msg>Fix issue with spacing when inserting gmt link Make the entry a single line to avoid leading white space problems.<commit_after>""" Utilities and common tasks for wrapping the GMT modules. """ GMT_DOCS = 'http://gmt.soest.hawaii.edu/doc/latest' def gmt_docs_link(module_func): """ Add to a module docstring a link to the GMT docs for that module. The docstring must have the placeholder ``{gmt_module_docs}`` where you want the link to appear. Assumes that the name of the GMT module is the same as the function name. Use this function as a decorator for the module functions. Parameters ---------- module_func : function The module function. Must have the same name as the GMT module. Returns ------- module_func The same *module_func* but with the link inserted into the docstring. Examples -------- >>> @gmt_docs_link ... def gmtinfo(**kwargs): ... ''' ... My nice module. ... {gmt_module_docs} ... ''' ... pass >>> print(gmtinfo.__doc__) <BLANKLINE> My nice module. Full option list at http://gmt.soest.hawaii.edu/doc/latest/gmtinfo.html <BLANKLINE> """ url = "{}/{}.html".format(GMT_DOCS, module_func.__name__) text = "Full option list at" full_text = ' '.join([text, url]) module_func.__doc__ = module_func.__doc__.format(gmt_module_docs=full_text) return module_func
207af9278a6e1ee54d640e24eee8bd35ced0920e
byceps/services/newsletter/transfer/models.py
byceps/services/newsletter/transfer/models.py
""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from datetime import datetime from typing import NewType from ....typing import UserID ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str @dataclass(frozen=True) class Subscription: user_id: UserID list_id: ListID expressed_at: datetime
""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from typing import NewType ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str
Remove unused newsletter DTO `Subscription`
Remove unused newsletter DTO `Subscription`
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from datetime import datetime from typing import NewType from ....typing import UserID ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str @dataclass(frozen=True) class Subscription: user_id: UserID list_id: ListID expressed_at: datetime Remove unused newsletter DTO `Subscription`
""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from typing import NewType ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str
<commit_before>""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from datetime import datetime from typing import NewType from ....typing import UserID ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str @dataclass(frozen=True) class Subscription: user_id: UserID list_id: ListID expressed_at: datetime <commit_msg>Remove unused newsletter DTO `Subscription`<commit_after>
""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from typing import NewType ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str
""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from datetime import datetime from typing import NewType from ....typing import UserID ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str @dataclass(frozen=True) class Subscription: user_id: UserID list_id: ListID expressed_at: datetime Remove unused newsletter DTO `Subscription`""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from typing import NewType ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str
<commit_before>""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from datetime import datetime from typing import NewType from ....typing import UserID ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str @dataclass(frozen=True) class Subscription: user_id: UserID list_id: ListID expressed_at: datetime <commit_msg>Remove unused newsletter DTO `Subscription`<commit_after>""" byceps.services.newsletter.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from typing import NewType ListID = NewType('ListID', str) @dataclass(frozen=True) class List: id: ListID title: str
c6aaa9b09c58cc964c5ec4877b43d014d1ae4566
examples/jinja_example.py
examples/jinja_example.py
## To use this example: # curl -d '{"name": "John Doe"}' localhost:8000 from sanic import Sanic from sanic import response from jinja2 import Template template = Template('Hello {{ name }}!') app = Sanic(__name__) @app.route('/') async def test(request): data = request.json return response.html(template.render(**data)) app.run(host="0.0.0.0", port=8080, debug=True)
# Render templates in a Flask like way from a "template" directory in the project from sanic import Sanic from sanic import response from jinja2 import Evironment, PackageLoader, select_autoescape app = Sanic(__name__) # Load the template environment with async support template_env = Environment( loader=jinja2.PackageLoader('yourapplication', 'templates'), autoescape=jinja2.select_autoescape(['html', 'xml']), enable_async=True ) # Load the template from file template = template_env.get_template("example_template.html") @app.route('/') async def test(request): data = request.json rendered_template = await template.render_async(**data) return response.html(rendered_template) app.run(host="0.0.0.0", port=8080, debug=True)
Use render_async and a template env with jinja2
Use render_async and a template env with jinja2
Python
mit
lixxu/sanic,ashleysommer/sanic,lixxu/sanic,channelcat/sanic,jrocketfingers/sanic,yunstanford/sanic,r0fls/sanic,ashleysommer/sanic,yunstanford/sanic,ashleysommer/sanic,lixxu/sanic,channelcat/sanic,jrocketfingers/sanic,yunstanford/sanic,channelcat/sanic,yunstanford/sanic,r0fls/sanic,lixxu/sanic,Tim-Erwin/sanic,channelcat/sanic,Tim-Erwin/sanic
## To use this example: # curl -d '{"name": "John Doe"}' localhost:8000 from sanic import Sanic from sanic import response from jinja2 import Template template = Template('Hello {{ name }}!') app = Sanic(__name__) @app.route('/') async def test(request): data = request.json return response.html(template.render(**data)) app.run(host="0.0.0.0", port=8080, debug=True)Use render_async and a template env with jinja2
# Render templates in a Flask like way from a "template" directory in the project from sanic import Sanic from sanic import response from jinja2 import Evironment, PackageLoader, select_autoescape app = Sanic(__name__) # Load the template environment with async support template_env = Environment( loader=jinja2.PackageLoader('yourapplication', 'templates'), autoescape=jinja2.select_autoescape(['html', 'xml']), enable_async=True ) # Load the template from file template = template_env.get_template("example_template.html") @app.route('/') async def test(request): data = request.json rendered_template = await template.render_async(**data) return response.html(rendered_template) app.run(host="0.0.0.0", port=8080, debug=True)
<commit_before>## To use this example: # curl -d '{"name": "John Doe"}' localhost:8000 from sanic import Sanic from sanic import response from jinja2 import Template template = Template('Hello {{ name }}!') app = Sanic(__name__) @app.route('/') async def test(request): data = request.json return response.html(template.render(**data)) app.run(host="0.0.0.0", port=8080, debug=True)<commit_msg>Use render_async and a template env with jinja2<commit_after>
# Render templates in a Flask like way from a "template" directory in the project from sanic import Sanic from sanic import response from jinja2 import Evironment, PackageLoader, select_autoescape app = Sanic(__name__) # Load the template environment with async support template_env = Environment( loader=jinja2.PackageLoader('yourapplication', 'templates'), autoescape=jinja2.select_autoescape(['html', 'xml']), enable_async=True ) # Load the template from file template = template_env.get_template("example_template.html") @app.route('/') async def test(request): data = request.json rendered_template = await template.render_async(**data) return response.html(rendered_template) app.run(host="0.0.0.0", port=8080, debug=True)
## To use this example: # curl -d '{"name": "John Doe"}' localhost:8000 from sanic import Sanic from sanic import response from jinja2 import Template template = Template('Hello {{ name }}!') app = Sanic(__name__) @app.route('/') async def test(request): data = request.json return response.html(template.render(**data)) app.run(host="0.0.0.0", port=8080, debug=True)Use render_async and a template env with jinja2# Render templates in a Flask like way from a "template" directory in the project from sanic import Sanic from sanic import response from jinja2 import Evironment, PackageLoader, select_autoescape app = Sanic(__name__) # Load the template environment with async support template_env = Environment( loader=jinja2.PackageLoader('yourapplication', 'templates'), autoescape=jinja2.select_autoescape(['html', 'xml']), enable_async=True ) # Load the template from file template = template_env.get_template("example_template.html") @app.route('/') async def test(request): data = request.json rendered_template = await template.render_async(**data) return response.html(rendered_template) app.run(host="0.0.0.0", port=8080, debug=True)
<commit_before>## To use this example: # curl -d '{"name": "John Doe"}' localhost:8000 from sanic import Sanic from sanic import response from jinja2 import Template template = Template('Hello {{ name }}!') app = Sanic(__name__) @app.route('/') async def test(request): data = request.json return response.html(template.render(**data)) app.run(host="0.0.0.0", port=8080, debug=True)<commit_msg>Use render_async and a template env with jinja2<commit_after># Render templates in a Flask like way from a "template" directory in the project from sanic import Sanic from sanic import response from jinja2 import Evironment, PackageLoader, select_autoescape app = Sanic(__name__) # Load the template environment with async support template_env = Environment( loader=jinja2.PackageLoader('yourapplication', 'templates'), autoescape=jinja2.select_autoescape(['html', 'xml']), enable_async=True ) # Load the template from file template = template_env.get_template("example_template.html") @app.route('/') async def test(request): data = request.json rendered_template = await template.render_async(**data) return response.html(rendered_template) app.run(host="0.0.0.0", port=8080, debug=True)
7a8b041ce9e0f115f3c5daad159a03c13c5cd72d
python/pycandela/pycandela/__init__.py
python/pycandela/pycandela/__init__.py
import IPython.core.displaypub as displaypub import json import DataFrame from pandas class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { new candela.components['%s'](element.get(0), %s) }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js})
import IPython.core.displaypub as displaypub import json from pandas import DataFrame class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { var vis = new candela.components['%s'](element.get(0), %s); vis.render(); }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js})
Fix import and call render() on vis
Fix import and call render() on vis
Python
apache-2.0
Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela
import IPython.core.displaypub as displaypub import json import DataFrame from pandas class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { new candela.components['%s'](element.get(0), %s) }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js}) Fix import and call render() on vis
import IPython.core.displaypub as displaypub import json from pandas import DataFrame class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { var vis = new candela.components['%s'](element.get(0), %s); vis.render(); }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js})
<commit_before>import IPython.core.displaypub as displaypub import json import DataFrame from pandas class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { new candela.components['%s'](element.get(0), %s) }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js}) <commit_msg>Fix import and call render() on vis<commit_after>
import IPython.core.displaypub as displaypub import json from pandas import DataFrame class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { var vis = new candela.components['%s'](element.get(0), %s); vis.render(); }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js})
import IPython.core.displaypub as displaypub import json import DataFrame from pandas class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { new candela.components['%s'](element.get(0), %s) }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js}) Fix import and call render() on visimport IPython.core.displaypub as displaypub import json from pandas import DataFrame class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { var vis = new candela.components['%s'](element.get(0), %s); vis.render(); }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js})
<commit_before>import IPython.core.displaypub as displaypub import json import DataFrame from pandas class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { new candela.components['%s'](element.get(0), %s) }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js}) <commit_msg>Fix import and call render() on vis<commit_after>import IPython.core.displaypub as displaypub import json from pandas import DataFrame class DataFrameEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, DataFrame): return obj.to_records() return json.JSONEncoder.default(self, obj) def publish_display_data(data): try: displaypub.publish_display_data('pycandela', data) except TypeError: displaypub.publish_display_data(data) def component(name, options): js = (""" require(['candela'], function (candela) { var vis = new candela.components['%s'](element.get(0), %s); vis.render(); }); """ % (name, json.dumps(options, cls=DataFrameEncoder))) publish_display_data({'application/javascript': js}) def init(): js = """ require.config({ paths: { candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6' } }); var outputElement = element; require(['candela'], function (candela) { if (candela) { outputElement.append('<div>Candela loaded successfully.</div>'); } else { outputElement.append('<div>Error loading Candela.</div>'); } }); """ publish_display_data({'application/javascript': js})
e37aa73f998e17c707d3c288ccc989f49aeeab3c
input_mask/contrib/localflavor/br/fields.py
input_mask/contrib/localflavor/br/fields.py
from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.')-1) return Decimal(value)
from django.forms import ValidationError from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal, DecimalException class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.') - 1) try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid'])
Fix a bug while handling invalid values
Fix a bug while handling invalid values
Python
mit
caioariede/django-input-mask,luzfcb/django-input-mask,caioariede/django-input-mask,luzfcb/django-input-mask,caioariede/django-input-mask,luzfcb/django-input-mask
from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.')-1) return Decimal(value) Fix a bug while handling invalid values
from django.forms import ValidationError from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal, DecimalException class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.') - 1) try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid'])
<commit_before>from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.')-1) return Decimal(value) <commit_msg>Fix a bug while handling invalid values<commit_after>
from django.forms import ValidationError from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal, DecimalException class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.') - 1) try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid'])
from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.')-1) return Decimal(value) Fix a bug while handling invalid valuesfrom django.forms import ValidationError from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal, DecimalException class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.') - 1) try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid'])
<commit_before>from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.')-1) return Decimal(value) <commit_msg>Fix a bug while handling invalid values<commit_after>from django.forms import ValidationError from ....fields import DecimalField from .widgets import BRDecimalInput from decimal import Decimal, DecimalException class BRDecimalField(DecimalField): widget = BRDecimalInput def to_python(self, value): value = value.replace(',', '.') value = value.replace('.', '', value.count('.') - 1) try: value = Decimal(value) except DecimalException: raise ValidationError(self.error_messages['invalid'])
40fa309ebf1cd56bc7846f007f186cf7f94cadde
osfoffline/settings/defaults.py
osfoffline/settings/defaults.py
# Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 20 * 365 * 24 * 60 * 60 # 20 years in seconds # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
# Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 24 * 60 * 60 # Once per day # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
Use max polling delay to avoid OSErrors
Use max polling delay to avoid OSErrors
Python
apache-2.0
chennan47/OSF-Offline,chennan47/OSF-Offline
# Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 20 * 365 * 24 * 60 * 60 # 20 years in seconds # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s' Use max polling delay to avoid OSErrors
# Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 24 * 60 * 60 # Once per day # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
<commit_before># Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 20 * 365 * 24 * 60 * 60 # 20 years in seconds # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s' <commit_msg>Use max polling delay to avoid OSErrors<commit_after>
# Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 24 * 60 * 60 # Once per day # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
# Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 20 * 365 * 24 * 60 * 60 # 20 years in seconds # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s' Use max polling delay to avoid OSErrors# Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 24 * 60 * 60 # Once per day # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
<commit_before># Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 20 * 365 * 24 * 60 * 60 # 20 years in seconds # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s' <commit_msg>Use max polling delay to avoid OSErrors<commit_after># Just to insure requirement import colorlog # noqa # Development mode: use a local OSF dev version and more granular logging DEV_MODE = False # TODO (abought): auto-set flag when using `inv start_for_tests` # General settings PROJECT_NAME = 'osf-offline' PROJECT_AUTHOR = 'cos' APPLICATION_SCOPES = 'osf.full_write' # Base URL for API server; used to fetch data API_BASE = 'https://staging-api.osf.io' FILE_BASE = 'https://staging-files.osf.io' # Interval (in seconds) to poll the OSF for server-side file changes # YEARS * DAYS * HOURS * MIN * SECONDS POLL_DELAY = 24 * 60 * 60 # Once per day # Time to keep alert messages on screen (in milliseconds); may not be configurable on all platforms ALERT_TIME = 1000 # ms LOG_LEVEL = 'INFO' # Logging configuration CONSOLE_FORMATTER = { '()': 'colorlog.ColoredFormatter', 'format': '%(cyan)s[%(asctime)s]%(log_color)s[%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(reset)s%(message)s' } FILE_FORMATTER = '[%(asctime)s][%(threadName)s][%(filename)s][%(levelname)s][%(name)s]: %(message)s'
212ce8f67495be81d5ecdc97b6765d2759e56d8d
streamparse/storm/component.py
streamparse/storm/component.py
""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code from ..dsl.component import ComponentSpec class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, name=None, inputs=None, par=None, config=None): """Create a :class:`~streamparse.dsl.component.ComponentSpec`. This spec represents this Component in a :class:`~streamparse.Topology`. :param name: Name of this component. Defaults to name of class. :type name: `str` :param inputs: Streams that feed into this Component. Only makes sense for :class:`~streamparse.Bolt`, as :class:`~streamparse.Spout` instances do not receive tuples. Two forms of this are acceptable: 1. A `dict` mapping from `ComponentSpec`s to tuple groupings. 2. A `list` of :class:`streamparse.Stream`s or `ComponentSpec`s . :param par: Parallelism hint for this Component. For Python Components, this works out to be the number of Python processes running it in the the topology (across all machines). See :ref:`parallelism`. :type par: `int` :param config: Component-specific config settings to pass to Storm. :type config: `dict` """ return ComponentSpec(cls, name=name, inputs=inputs, par=par, config=config, outputs=cls.outputs)
""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, *args, **kwargs): """This method exists only to give a more informative error message.""" raise TypeError('Specifications should either be bolts or spouts. ' 'Given: {!r}'.format(cls))
Make Component.spec calls raise TypeError directly
Make Component.spec calls raise TypeError directly
Python
apache-2.0
codywilbourn/streamparse,Parsely/streamparse,codywilbourn/streamparse,Parsely/streamparse
""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code from ..dsl.component import ComponentSpec class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, name=None, inputs=None, par=None, config=None): """Create a :class:`~streamparse.dsl.component.ComponentSpec`. This spec represents this Component in a :class:`~streamparse.Topology`. :param name: Name of this component. Defaults to name of class. :type name: `str` :param inputs: Streams that feed into this Component. Only makes sense for :class:`~streamparse.Bolt`, as :class:`~streamparse.Spout` instances do not receive tuples. Two forms of this are acceptable: 1. A `dict` mapping from `ComponentSpec`s to tuple groupings. 2. A `list` of :class:`streamparse.Stream`s or `ComponentSpec`s . :param par: Parallelism hint for this Component. For Python Components, this works out to be the number of Python processes running it in the the topology (across all machines). See :ref:`parallelism`. :type par: `int` :param config: Component-specific config settings to pass to Storm. :type config: `dict` """ return ComponentSpec(cls, name=name, inputs=inputs, par=par, config=config, outputs=cls.outputs) Make Component.spec calls raise TypeError directly
""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, *args, **kwargs): """This method exists only to give a more informative error message.""" raise TypeError('Specifications should either be bolts or spouts. ' 'Given: {!r}'.format(cls))
<commit_before>""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code from ..dsl.component import ComponentSpec class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, name=None, inputs=None, par=None, config=None): """Create a :class:`~streamparse.dsl.component.ComponentSpec`. This spec represents this Component in a :class:`~streamparse.Topology`. :param name: Name of this component. Defaults to name of class. :type name: `str` :param inputs: Streams that feed into this Component. Only makes sense for :class:`~streamparse.Bolt`, as :class:`~streamparse.Spout` instances do not receive tuples. Two forms of this are acceptable: 1. A `dict` mapping from `ComponentSpec`s to tuple groupings. 2. A `list` of :class:`streamparse.Stream`s or `ComponentSpec`s . :param par: Parallelism hint for this Component. For Python Components, this works out to be the number of Python processes running it in the the topology (across all machines). See :ref:`parallelism`. :type par: `int` :param config: Component-specific config settings to pass to Storm. :type config: `dict` """ return ComponentSpec(cls, name=name, inputs=inputs, par=par, config=config, outputs=cls.outputs) <commit_msg>Make Component.spec calls raise TypeError directly<commit_after>
""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, *args, **kwargs): """This method exists only to give a more informative error message.""" raise TypeError('Specifications should either be bolts or spouts. ' 'Given: {!r}'.format(cls))
""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code from ..dsl.component import ComponentSpec class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, name=None, inputs=None, par=None, config=None): """Create a :class:`~streamparse.dsl.component.ComponentSpec`. This spec represents this Component in a :class:`~streamparse.Topology`. :param name: Name of this component. Defaults to name of class. :type name: `str` :param inputs: Streams that feed into this Component. Only makes sense for :class:`~streamparse.Bolt`, as :class:`~streamparse.Spout` instances do not receive tuples. Two forms of this are acceptable: 1. A `dict` mapping from `ComponentSpec`s to tuple groupings. 2. A `list` of :class:`streamparse.Stream`s or `ComponentSpec`s . :param par: Parallelism hint for this Component. For Python Components, this works out to be the number of Python processes running it in the the topology (across all machines). See :ref:`parallelism`. :type par: `int` :param config: Component-specific config settings to pass to Storm. :type config: `dict` """ return ComponentSpec(cls, name=name, inputs=inputs, par=par, config=config, outputs=cls.outputs) Make Component.spec calls raise TypeError directly""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, *args, **kwargs): """This method exists only to give a more informative error message.""" raise TypeError('Specifications should either be bolts or spouts. ' 'Given: {!r}'.format(cls))
<commit_before>""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code from ..dsl.component import ComponentSpec class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, name=None, inputs=None, par=None, config=None): """Create a :class:`~streamparse.dsl.component.ComponentSpec`. This spec represents this Component in a :class:`~streamparse.Topology`. :param name: Name of this component. Defaults to name of class. :type name: `str` :param inputs: Streams that feed into this Component. Only makes sense for :class:`~streamparse.Bolt`, as :class:`~streamparse.Spout` instances do not receive tuples. Two forms of this are acceptable: 1. A `dict` mapping from `ComponentSpec`s to tuple groupings. 2. A `list` of :class:`streamparse.Stream`s or `ComponentSpec`s . :param par: Parallelism hint for this Component. For Python Components, this works out to be the number of Python processes running it in the the topology (across all machines). See :ref:`parallelism`. :type par: `int` :param config: Component-specific config settings to pass to Storm. :type config: `dict` """ return ComponentSpec(cls, name=name, inputs=inputs, par=par, config=config, outputs=cls.outputs) <commit_msg>Make Component.spec calls raise TypeError directly<commit_after>""" Module to add streamparse-specific extensions to pystorm Component classes """ import pystorm from pystorm.component import StormHandler # This is used by other code class Component(pystorm.component.Component): """pystorm Component with streamparse-specific additions :ivar outputs: The outputs :ivar config: Component-specific config settings to pass to Storm. """ outputs = None par = 1 config = None @classmethod def spec(cls, *args, **kwargs): """This method exists only to give a more informative error message.""" raise TypeError('Specifications should either be bolts or spouts. ' 'Given: {!r}'.format(cls))
a6d8b7b6592cb8b7f49584817e13f7a55f679960
project/library/models.py
project/library/models.py
from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ":" + self.book_id
from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ": " + str(self.book_id)
Fix error where book id wasn't cast to string
Fix error where book id wasn't cast to string
Python
mit
DUCSS/ducss-site-old,DUCSS/ducss-site-old,DUCSS/ducss-site-old
from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ":" + self.book_id Fix error where book id wasn't cast to string
from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ": " + str(self.book_id)
<commit_before>from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ":" + self.book_id <commit_msg>Fix error where book id wasn't cast to string<commit_after>
from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ": " + str(self.book_id)
from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ":" + self.book_id Fix error where book id wasn't cast to stringfrom datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ": " + str(self.book_id)
<commit_before>from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ":" + self.book_id <commit_msg>Fix error where book id wasn't cast to string<commit_after>from datetime import datetime from django.db import models class Author(models.Model): '''Object for book author''' first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) def __unicode__(self): return self.last_name + ", " + self.first_name class Book(models.Model): '''Object for library books''' title = models.CharField(max_length=128) isbn = models.CharField(max_length=13) isbn13 = models.CharField(max_length=13) description = models.TextField() authors = models.ManyToManyField(Author) year_published = models.SmallIntegerField(null=True) status = models.TextField(default="In") def __unicode__(self): return self.title class Reservation(models.Model): '''Object for book reservations''' book_id = models.ForeignKey('Book') member_name = models.CharField(max_length=128) email = models.EmailField() date_created = models.DateTimeField(default=datetime.now()) def __unicode__(self): return self.member_name + ": " + str(self.book_id)
8298f0b04380f7391e613a758576e4093fc9f09c
symposion/proposals/lookups.py
symposion/proposals/lookups.py
from django.contrib.auth.models import User from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
import operator from django.contrib.auth.models import User from django.db.models import Q from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_query(self, request, term): qs = self.get_queryset() if term: search_filters = [] if len(term.split(' ')) == 1: if self.search_fields: for field in self.search_fields: search_filters.append(Q(**{field: term})) qs = qs.filter(reduce(operator.or_, search_filters)) else: # Accounts for 'John Doe' term; will compare against get_full_name qs = [x for x in qs if term in x.get_full_name()] return qs def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
Customize lookup get_query to account for looking up a portion of User.get_full_name
Customize lookup get_query to account for looking up a portion of User.get_full_name
Python
bsd-3-clause
smellman/sotmjp-website,smellman/sotmjp-website,pyconjp/pyconjp-website,osmfj/sotmjp-website,pyconjp/pyconjp-website,njl/pycon,osmfj/sotmjp-website,pyconjp/pyconjp-website,PyCon/pycon,smellman/sotmjp-website,Diwahars/pycon,njl/pycon,Diwahars/pycon,PyCon/pycon,osmfj/sotmjp-website,pyconjp/pyconjp-website,Diwahars/pycon,Diwahars/pycon,smellman/sotmjp-website,osmfj/sotmjp-website,njl/pycon,PyCon/pycon,njl/pycon,PyCon/pycon
from django.contrib.auth.models import User from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup) Customize lookup get_query to account for looking up a portion of User.get_full_name
import operator from django.contrib.auth.models import User from django.db.models import Q from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_query(self, request, term): qs = self.get_queryset() if term: search_filters = [] if len(term.split(' ')) == 1: if self.search_fields: for field in self.search_fields: search_filters.append(Q(**{field: term})) qs = qs.filter(reduce(operator.or_, search_filters)) else: # Accounts for 'John Doe' term; will compare against get_full_name qs = [x for x in qs if term in x.get_full_name()] return qs def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
<commit_before>from django.contrib.auth.models import User from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup) <commit_msg>Customize lookup get_query to account for looking up a portion of User.get_full_name<commit_after>
import operator from django.contrib.auth.models import User from django.db.models import Q from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_query(self, request, term): qs = self.get_queryset() if term: search_filters = [] if len(term.split(' ')) == 1: if self.search_fields: for field in self.search_fields: search_filters.append(Q(**{field: term})) qs = qs.filter(reduce(operator.or_, search_filters)) else: # Accounts for 'John Doe' term; will compare against get_full_name qs = [x for x in qs if term in x.get_full_name()] return qs def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
from django.contrib.auth.models import User from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup) Customize lookup get_query to account for looking up a portion of User.get_full_nameimport operator from django.contrib.auth.models import User from django.db.models import Q from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_query(self, request, term): qs = self.get_queryset() if term: search_filters = [] if len(term.split(' ')) == 1: if self.search_fields: for field in self.search_fields: search_filters.append(Q(**{field: term})) qs = qs.filter(reduce(operator.or_, search_filters)) else: # Accounts for 'John Doe' term; will compare against get_full_name qs = [x for x in qs if term in x.get_full_name()] return qs def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
<commit_before>from django.contrib.auth.models import User from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup) <commit_msg>Customize lookup get_query to account for looking up a portion of User.get_full_name<commit_after>import operator from django.contrib.auth.models import User from django.db.models import Q from selectable.base import ModelLookup from selectable.registry import registry class UserLookup(ModelLookup): model = User search_fields = ( 'first_name__icontains', 'last_name__icontains', 'email__icontains', ) def get_query(self, request, term): qs = self.get_queryset() if term: search_filters = [] if len(term.split(' ')) == 1: if self.search_fields: for field in self.search_fields: search_filters.append(Q(**{field: term})) qs = qs.filter(reduce(operator.or_, search_filters)) else: # Accounts for 'John Doe' term; will compare against get_full_name qs = [x for x in qs if term in x.get_full_name()] return qs def get_item_value(self, item): return item.email def get_item_label(self, item): return u"%s (%s)" % (item.get_full_name(), item.email) def create_item(self, value): """We aren't actually creating a new user, we just need to supply the email to the form processor """ return value registry.register(UserLookup)
472325bdb9ad46ae2466d5be7ecfae009b8518ae
test/copies/gyptest-attribs.py
test/copies/gyptest-attribs.py
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() test = TestGyp.TestGyp() test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() # Doesn't pass with the android generator, see gyp bug 379. test = TestGyp.TestGyp(formats=['!android']) test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
Disable new test from r1779 for the android generator.
Disable new test from r1779 for the android generator. BUG=gyp:379 TBR=torne@chromium.org Review URL: https://codereview.chromium.org/68333002
Python
bsd-3-clause
old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() test = TestGyp.TestGyp() test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test() Disable new test from r1779 for the android generator. BUG=gyp:379 TBR=torne@chromium.org Review URL: https://codereview.chromium.org/68333002
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() # Doesn't pass with the android generator, see gyp bug 379. test = TestGyp.TestGyp(formats=['!android']) test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
<commit_before>#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() test = TestGyp.TestGyp() test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test() <commit_msg>Disable new test from r1779 for the android generator. BUG=gyp:379 TBR=torne@chromium.org Review URL: https://codereview.chromium.org/68333002<commit_after>
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() # Doesn't pass with the android generator, see gyp bug 379. test = TestGyp.TestGyp(formats=['!android']) test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() test = TestGyp.TestGyp() test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test() Disable new test from r1779 for the android generator. BUG=gyp:379 TBR=torne@chromium.org Review URL: https://codereview.chromium.org/68333002#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() # Doesn't pass with the android generator, see gyp bug 379. test = TestGyp.TestGyp(formats=['!android']) test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
<commit_before>#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() test = TestGyp.TestGyp() test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test() <commit_msg>Disable new test from r1779 for the android generator. BUG=gyp:379 TBR=torne@chromium.org Review URL: https://codereview.chromium.org/68333002<commit_after>#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() # Doesn't pass with the android generator, see gyp bug 379. test = TestGyp.TestGyp(formats=['!android']) test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
6bbafa2e9102840768ee875407be1878f2aa05ca
tests/pytests/unit/engines/test_script.py
tests/pytests/unit/engines/test_script.py
""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test"
""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock))
Test iteration stops at empty bytes
Test iteration stops at empty bytes
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" Test iteration stops at empty bytes
""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock))
<commit_before>""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" <commit_msg>Test iteration stops at empty bytes<commit_after>
""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock))
""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" Test iteration stops at empty bytes""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock))
<commit_before>""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" <commit_msg>Test iteration stops at empty bytes<commit_after>""" unit tests for the script engine """ import pytest import salt.config import salt.engines.script as script from salt.exceptions import CommandExecutionError from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): opts = salt.config.DEFAULT_MASTER_OPTS return {script: {"__opts__": opts}} def test__get_serializer(): """ Test known serializer is returned or exception is raised if unknown serializer """ for serializers in ("json", "yaml", "msgpack"): assert script._get_serializer(serializers) with pytest.raises(CommandExecutionError): script._get_serializer("bad") def test__read_stdout(): """ Test we can yield stdout """ with patch("subprocess.Popen") as popen_mock: popen_mock.stdout.readline.return_value = "test" assert next(script._read_stdout(popen_mock)) == "test" def test__read_stdout_terminates_properly(): """ Test that _read_stdout terminates with the sentinel """ with patch("subprocess.Popen", autospec=True) as popen_mock: popen_mock.stdout.readline.return_value = b"" with pytest.raises(StopIteration): next(script._read_stdout(popen_mock))
68a61404105bff4e08a7d20a148da1107a8f27f0
learnwithpeople/urls.py
learnwithpeople/urls.py
from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^', include('studygroups.urls')), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')), url(r'^', include('studygroups.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
Fix custom URLs masking admin URL
Fix custom URLs masking admin URL
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^', include('studygroups.urls')), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ) Fix custom URLs masking admin URL
from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')), url(r'^', include('studygroups.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
<commit_before>from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^', include('studygroups.urls')), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ) <commit_msg>Fix custom URLs masking admin URL<commit_after>
from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')), url(r'^', include('studygroups.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^', include('studygroups.urls')), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ) Fix custom URLs masking admin URLfrom django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')), url(r'^', include('studygroups.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
<commit_before>from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^', include('studygroups.urls')), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ) <commit_msg>Fix custom URLs masking admin URL<commit_after>from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^interest/', include('interest.urls', namespace='interest')), url(r'^about/$', TemplateView.as_view(template_name="about.html"), name="about"), url(r'^accounts/', include('django.contrib.auth.urls')), url(r'^ux/', include('uxhelpers.urls')), url(r'^', include('studygroups.urls')) ) if settings.DEBUG: media_url = settings.MEDIA_URL.lstrip('/').rstrip('/') urlpatterns += patterns('', (r'^%s/(?P<path>.*)$' % media_url, 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
9658033dab279828975183f94f8c8641891f4ea9
froide/helper/api_utils.py
froide/helper/api_utils.py
from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret
from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): max_limit = 50 def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret
Add max limit to api pagination
Add max limit to api pagination
Python
mit
fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide
from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret Add max limit to api pagination
from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): max_limit = 50 def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret
<commit_before>from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret <commit_msg>Add max limit to api pagination<commit_after>
from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): max_limit = 50 def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret
from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret Add max limit to api paginationfrom collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): max_limit = 50 def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret
<commit_before>from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret <commit_msg>Add max limit to api pagination<commit_after>from collections import OrderedDict from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response from rest_framework.serializers import ListSerializer from rest_framework.utils.serializer_helpers import ReturnDict class CustomLimitOffsetPagination(LimitOffsetPagination): max_limit = 50 def get_paginated_response(self, data): return Response(OrderedDict([ ('meta', OrderedDict([ ('limit', self.limit), ('next', self.get_next_link()), ('offset', self.offset), ('previous', self.get_previous_link()), ('total_count', self.count), ])), ('objects', data), ])) class SearchFacetListSerializer(ListSerializer): @property def data(self): ret = super(ListSerializer, self).data return ReturnDict(ret, serializer=self) def to_representation(self, instance): ret = super(SearchFacetListSerializer, self).to_representation(instance) ret = OrderedDict([ ('results', ret), ('facets', self._context.get('facets', {'fields': {}})), ]) return ret
592c6550255793772add694cb941a0db0883713b
kamboo/core.py
kamboo/core.py
# Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ session = botocore.session.get_session() def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region)
# Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.session = botocore.session.get_session() self.service = service_name self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) def __repr__(self): return "KambooConnection: [%s, %s, %s]" % (self.account_id, self.region, self.service)
Fix the issue: "session" shared in different connections
Fix the issue: "session" shared in different connections
Python
apache-2.0
henrysher/kamboo,henrysher/kamboo
# Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ session = botocore.session.get_session() def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) Fix the issue: "session" shared in different connections
# Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.session = botocore.session.get_session() self.service = service_name self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) def __repr__(self): return "KambooConnection: [%s, %s, %s]" % (self.account_id, self.region, self.service)
<commit_before># Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ session = botocore.session.get_session() def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) <commit_msg>Fix the issue: "session" shared in different connections<commit_after>
# Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.session = botocore.session.get_session() self.service = service_name self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) def __repr__(self): return "KambooConnection: [%s, %s, %s]" % (self.account_id, self.region, self.service)
# Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ session = botocore.session.get_session() def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) Fix the issue: "session" shared in different connections# Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.session = botocore.session.get_session() self.service = service_name self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) def __repr__(self): return "KambooConnection: [%s, %s, %s]" % (self.account_id, self.region, self.service)
<commit_before># Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ session = botocore.session.get_session() def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) <commit_msg>Fix the issue: "session" shared in different connections<commit_after># Copyright (c) 2014, Henry Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import botocore from kotocore.session import Session log = logging.getLogger(__name__) class KambooConnection(object): """ Kamboo connection with botocore session initialized """ def __init__(self, service_name="ec2", region_name="us-east-1", account_id=None, credentials=None): self.session = botocore.session.get_session() self.service = service_name self.region = region_name self.account_id = account_id self.credentials = credentials if self.credentials: self.session.set_credentials(**self.credentials) Connection = Session(session=self.session).get_connection(service_name) self.conn = Connection(region_name=self.region) def __repr__(self): return "KambooConnection: [%s, %s, %s]" % (self.account_id, self.region, self.service)
b80607d0f5cff2d05bf607d4ff4847f14777130f
sieve/sieve.py
sieve/sieve.py
def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n+1, i)) return prime
def sieve(n): return list(primes(n)) def primes(n): if n < 2: raise StopIteration yield 2 not_prime = set() for i in range(3, n+1, 2): if i not in not_prime: not_prime.update(range(i*i, n+1, i)) yield i
Revert back to a generator - it's actually slight faster
Revert back to a generator - it's actually slight faster
Python
agpl-3.0
CubicComet/exercism-python-solutions
def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n+1, i)) return prime Revert back to a generator - it's actually slight faster
def sieve(n): return list(primes(n)) def primes(n): if n < 2: raise StopIteration yield 2 not_prime = set() for i in range(3, n+1, 2): if i not in not_prime: not_prime.update(range(i*i, n+1, i)) yield i
<commit_before>def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n+1, i)) return prime <commit_msg>Revert back to a generator - it's actually slight faster<commit_after>
def sieve(n): return list(primes(n)) def primes(n): if n < 2: raise StopIteration yield 2 not_prime = set() for i in range(3, n+1, 2): if i not in not_prime: not_prime.update(range(i*i, n+1, i)) yield i
def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n+1, i)) return prime Revert back to a generator - it's actually slight fasterdef sieve(n): return list(primes(n)) def primes(n): if n < 2: raise StopIteration yield 2 not_prime = set() for i in range(3, n+1, 2): if i not in not_prime: not_prime.update(range(i*i, n+1, i)) yield i
<commit_before>def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n+1, i)) return prime <commit_msg>Revert back to a generator - it's actually slight faster<commit_after>def sieve(n): return list(primes(n)) def primes(n): if n < 2: raise StopIteration yield 2 not_prime = set() for i in range(3, n+1, 2): if i not in not_prime: not_prime.update(range(i*i, n+1, i)) yield i
35a413ecdc83578a0ef63d0865a4fe7bae6f1e99
scipy/interpolate/generate_interpnd.py
scipy/interpolate/generate_interpnd.py
#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython dst_fn = os.path.join(tmp_dir, 'interpnd.c') ret = subprocess.call(['cython', '-I', '../..', '-o', dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open('interpnd.c', 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir)
#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template dotnet = False if len(sys.argv) > 1 and sys.argv[1] == '--dotnet': dotnet = True f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython if dotnet: dst_name = 'interpnd.cpp' args_extra = ['--dotnet'] else: dst_name = 'interpnd.c' args_extra = [] dst_fn = os.path.join(tmp_dir, dst_name) ret = subprocess.call(['cython', '-I', '../..', '-o'] + args_extra + [dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open(dst_name, 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir)
Modify the interpnd cython generator to allow .NET output
Modify the interpnd cython generator to allow .NET output
Python
bsd-3-clause
jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor
#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython dst_fn = os.path.join(tmp_dir, 'interpnd.c') ret = subprocess.call(['cython', '-I', '../..', '-o', dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open('interpnd.c', 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir) Modify the interpnd cython generator to allow .NET output
#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template dotnet = False if len(sys.argv) > 1 and sys.argv[1] == '--dotnet': dotnet = True f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython if dotnet: dst_name = 'interpnd.cpp' args_extra = ['--dotnet'] else: dst_name = 'interpnd.c' args_extra = [] dst_fn = os.path.join(tmp_dir, dst_name) ret = subprocess.call(['cython', '-I', '../..', '-o'] + args_extra + [dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open(dst_name, 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir)
<commit_before>#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython dst_fn = os.path.join(tmp_dir, 'interpnd.c') ret = subprocess.call(['cython', '-I', '../..', '-o', dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open('interpnd.c', 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir) <commit_msg>Modify the interpnd cython generator to allow .NET output<commit_after>
#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template dotnet = False if len(sys.argv) > 1 and sys.argv[1] == '--dotnet': dotnet = True f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython if dotnet: dst_name = 'interpnd.cpp' args_extra = ['--dotnet'] else: dst_name = 'interpnd.c' args_extra = [] dst_fn = os.path.join(tmp_dir, dst_name) ret = subprocess.call(['cython', '-I', '../..', '-o'] + args_extra + [dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open(dst_name, 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir)
#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython dst_fn = os.path.join(tmp_dir, 'interpnd.c') ret = subprocess.call(['cython', '-I', '../..', '-o', dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open('interpnd.c', 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir) Modify the interpnd cython generator to allow .NET output#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template dotnet = False if len(sys.argv) > 1 and sys.argv[1] == '--dotnet': dotnet = True f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython if dotnet: dst_name = 'interpnd.cpp' args_extra = ['--dotnet'] else: dst_name = 'interpnd.c' args_extra = [] dst_fn = os.path.join(tmp_dir, dst_name) ret = subprocess.call(['cython', '-I', '../..', '-o'] + args_extra + [dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open(dst_name, 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir)
<commit_before>#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython dst_fn = os.path.join(tmp_dir, 'interpnd.c') ret = subprocess.call(['cython', '-I', '../..', '-o', dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open('interpnd.c', 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir) <commit_msg>Modify the interpnd cython generator to allow .NET output<commit_after>#!/usr/bin/env python import tempfile import subprocess import os import sys import re import shutil from mako.template import Template dotnet = False if len(sys.argv) > 1 and sys.argv[1] == '--dotnet': dotnet = True f = open('interpnd.pyx', 'r') template = f.read() f.close() tmp_dir = tempfile.mkdtemp() try: # Run templating engine fn = os.path.join(tmp_dir, 'interpnd.pyx') f = open(fn, 'w') f.write(Template(template).render()) f.close() # Run Cython if dotnet: dst_name = 'interpnd.cpp' args_extra = ['--dotnet'] else: dst_name = 'interpnd.c' args_extra = [] dst_fn = os.path.join(tmp_dir, dst_name) ret = subprocess.call(['cython', '-I', '../..', '-o'] + args_extra + [dst_fn, fn]) if ret != 0: sys.exit(ret) # Strip comments f = open(dst_fn, 'r') text = f.read() f.close() r = re.compile(r'/\*(.*?)\*/', re.S) text = r.sub('', text) f = open(dst_name, 'w') f.write(text) f.close() finally: shutil.rmtree(tmp_dir)
88cd50a331c20fb65c495e92cc93867f03cd3826
lib/exp/featx/__init__.py
lib/exp/featx/__init__.py
__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load("s_{:03d}_kps".format(sid)) sd = self.load("s_{:03d}_des".format(sid)) fk = self.load("f_{:03d}_kps".format(fid)) fd = self.load("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd)
__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def load_feats(self, key): fd = self.load(key) if fd is None: return [] return fd def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load_feats("s_{:03d}_kps".format(sid)) sd = self.load_feats("s_{:03d}_des".format(sid)) fk = self.load_feats("f_{:03d}_kps".format(fid)) fd = self.load_feats("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd)
Load feats with zero length
Load feats with zero length
Python
agpl-3.0
speed-of-light/pyslider
__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load("s_{:03d}_kps".format(sid)) sd = self.load("s_{:03d}_des".format(sid)) fk = self.load("f_{:03d}_kps".format(fid)) fd = self.load("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd) Load feats with zero length
__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def load_feats(self, key): fd = self.load(key) if fd is None: return [] return fd def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load_feats("s_{:03d}_kps".format(sid)) sd = self.load_feats("s_{:03d}_des".format(sid)) fk = self.load_feats("f_{:03d}_kps".format(fid)) fd = self.load_feats("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd)
<commit_before>__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load("s_{:03d}_kps".format(sid)) sd = self.load("s_{:03d}_des".format(sid)) fk = self.load("f_{:03d}_kps".format(fid)) fd = self.load("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd) <commit_msg>Load feats with zero length<commit_after>
__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def load_feats(self, key): fd = self.load(key) if fd is None: return [] return fd def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load_feats("s_{:03d}_kps".format(sid)) sd = self.load_feats("s_{:03d}_des".format(sid)) fk = self.load_feats("f_{:03d}_kps".format(fid)) fd = self.load_feats("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd)
__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load("s_{:03d}_kps".format(sid)) sd = self.load("s_{:03d}_des".format(sid)) fk = self.load("f_{:03d}_kps".format(fid)) fd = self.load("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd) Load feats with zero length__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def load_feats(self, key): fd = self.load(key) if fd is None: return [] return fd def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load_feats("s_{:03d}_kps".format(sid)) sd = self.load_feats("s_{:03d}_des".format(sid)) fk = self.load_feats("f_{:03d}_kps".format(fid)) fd = self.load_feats("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd)
<commit_before>__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load("s_{:03d}_kps".format(sid)) sd = self.load("s_{:03d}_des".format(sid)) fk = self.load("f_{:03d}_kps".format(fid)) fd = self.load("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd) <commit_msg>Load feats with zero length<commit_after>__all__ = [] from lib.exp.featx.base import Feats from lib.exp.tools.slider import Slider from lib.exp.tools.video import Video from lib.exp.pre import Reducer class Featx(Feats): def __init__(self, root, name): Feats.__init__(self, root, name) def get_slide_feats(self): ss = Slider(self.root, self.name) imgl = ss.get_slides(None, gray=True, resize=True) self.feats(imgl, prefix="s") def get_frame_feats(self): rr = Reducer(self.root, self.name) vv = Video(self.root, self.name) imgl = vv.get_frames(rr.frame_ids(), gray=True) self.feats(imgl, prefix="f") def load_feats(self, key): fd = self.load(key) if fd is None: return [] return fd def get_feats_pair(self, sid, fid): """ Get features by given `slide`, `frame` pairs """ sk = self.load_feats("s_{:03d}_kps".format(sid)) sd = self.load_feats("s_{:03d}_des".format(sid)) fk = self.load_feats("f_{:03d}_kps".format(fid)) fd = self.load_feats("f_{:03d}_des".format(fid)) return dict(sk=sk, sd=sd, fk=fk, fd=fd)
4a24d8dc7123bd5ea0a34b35ea3c9880462075a1
entrypoint.py
entrypoint.py
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask app = Flask(__name__) # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app = Flask(__name__) app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
Debug Google Cloud Run support
Debug Google Cloud Run support
Python
mit
diodesign/diosix
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask app = Flask(__name__) # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output Debug Google Cloud Run support
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app = Flask(__name__) app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
<commit_before>#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask app = Flask(__name__) # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output <commit_msg>Debug Google Cloud Run support<commit_after>
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app = Flask(__name__) app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask app = Flask(__name__) # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output Debug Google Cloud Run support#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app = Flask(__name__) app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
<commit_before>#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask app = Flask(__name__) # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output <commit_msg>Debug Google Cloud Run support<commit_after>#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask # for Google Cloud Run @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app = Flask(__name__) app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
f24d3bbd9bd5bdfdfaf939bf795f5c4ad490e8dd
src/waypoints_reader/scripts/yaml_reader.py
src/waypoints_reader/scripts/yaml_reader.py
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def pub_data(): pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10) rospy.init_node('yaml_reader', anonymous=True) msg = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) msg.waypoints.append(waypoint) pub.publish(msg) if __name__ == '__main__': try: pub_data() except rospy.ROSInterruptException: pass
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.srv import ApplyGoals from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def get_waypoints(): sequence = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) sequence.waypoints.append(waypoint) return sequence if __name__ == '__main__': rospy.init_node('yaml_reader', anonymous=True) goal_sequence = get_waypoints() rospy.wait_for_service('apply_goals') try: apply_goals = rospy.ServiceProxy('apply_goals', ApplyGoals) resp = apply_goals(goal_sequence) print resp.message except rospy.ServiceException, e: print e
Change goals passage with service (from message)
Change goals passage with service (from message)
Python
bsd-3-clause
CIR-KIT/fifth_robot_pkg,CIR-KIT/fifth_robot_pkg,CIR-KIT/fifth_robot_pkg
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def pub_data(): pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10) rospy.init_node('yaml_reader', anonymous=True) msg = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) msg.waypoints.append(waypoint) pub.publish(msg) if __name__ == '__main__': try: pub_data() except rospy.ROSInterruptException: pass Change goals passage with service (from message)
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.srv import ApplyGoals from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def get_waypoints(): sequence = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) sequence.waypoints.append(waypoint) return sequence if __name__ == '__main__': rospy.init_node('yaml_reader', anonymous=True) goal_sequence = get_waypoints() rospy.wait_for_service('apply_goals') try: apply_goals = rospy.ServiceProxy('apply_goals', ApplyGoals) resp = apply_goals(goal_sequence) print resp.message except rospy.ServiceException, e: print e
<commit_before>#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def pub_data(): pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10) rospy.init_node('yaml_reader', anonymous=True) msg = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) msg.waypoints.append(waypoint) pub.publish(msg) if __name__ == '__main__': try: pub_data() except rospy.ROSInterruptException: pass <commit_msg>Change goals passage with service (from message)<commit_after>
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.srv import ApplyGoals from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def get_waypoints(): sequence = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) sequence.waypoints.append(waypoint) return sequence if __name__ == '__main__': rospy.init_node('yaml_reader', anonymous=True) goal_sequence = get_waypoints() rospy.wait_for_service('apply_goals') try: apply_goals = rospy.ServiceProxy('apply_goals', ApplyGoals) resp = apply_goals(goal_sequence) print resp.message except rospy.ServiceException, e: print e
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def pub_data(): pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10) rospy.init_node('yaml_reader', anonymous=True) msg = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) msg.waypoints.append(waypoint) pub.publish(msg) if __name__ == '__main__': try: pub_data() except rospy.ROSInterruptException: pass Change goals passage with service (from message)#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.srv import ApplyGoals from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def get_waypoints(): sequence = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) sequence.waypoints.append(waypoint) return sequence if __name__ == '__main__': rospy.init_node('yaml_reader', anonymous=True) goal_sequence = get_waypoints() rospy.wait_for_service('apply_goals') try: apply_goals = rospy.ServiceProxy('apply_goals', ApplyGoals) resp = apply_goals(goal_sequence) print resp.message except rospy.ServiceException, e: print e
<commit_before>#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def pub_data(): pub = rospy.Publisher('goal_sequence', GoalSequence, queue_size=10) rospy.init_node('yaml_reader', anonymous=True) msg = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) msg.waypoints.append(waypoint) pub.publish(msg) if __name__ == '__main__': try: pub_data() except rospy.ROSInterruptException: pass <commit_msg>Change goals passage with service (from message)<commit_after>#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.srv import ApplyGoals from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def get_waypoints(): sequence = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) sequence.waypoints.append(waypoint) return sequence if __name__ == '__main__': rospy.init_node('yaml_reader', anonymous=True) goal_sequence = get_waypoints() rospy.wait_for_service('apply_goals') try: apply_goals = rospy.ServiceProxy('apply_goals', ApplyGoals) resp = apply_goals(goal_sequence) print resp.message except rospy.ServiceException, e: print e
56bbd1eac61421b57d8576b233fcfe86644009d6
probe/sources/tcpdump.py
probe/sources/tcpdump.py
import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "'{}'".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait()
import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "{}".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait()
Fix trouble about the output filename
Fix trouble about the output filename
Python
mit
laulin/network-safety,laulin/network-safety
import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "'{}'".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait() Fix trouble about the output filename
import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "{}".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait()
<commit_before>import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "'{}'".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait() <commit_msg>Fix trouble about the output filename<commit_after>
import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "{}".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait()
import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "'{}'".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait() Fix trouble about the output filenameimport logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "{}".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait()
<commit_before>import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "'{}'".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait() <commit_msg>Fix trouble about the output filename<commit_after>import logging import subprocess class Tcpdump: def __init__(self, interface, buffer_size, pcap_size, pcap_timeout, output_filename, post_process=None): self._interface = interface self._buffer_size = buffer_size self._pcap_size = pcap_size self._pcap_timeout = pcap_timeout self._output_filename = output_filename self._post_process = post_process self._log = logging.getLogger(__name__) def make_command(self): cmd = ["tcpdump", "-pni", self._interface, "-B", str(self._buffer_size), "-C", str(self._pcap_size), "-G", str(self._pcap_timeout), "-w", "{}".format(self._output_filename)] if self._post_process: cmd += ["-z", self._post_process] return cmd def popen(self, **kwargs): cmd = self.make_command() self._log.debug(" ".join(cmd)) return subprocess.Popen(cmd) if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG) tcpdump = Tcpdump("enp0s3", 10240, 50, 60, "/tmp/%s.pcap") process = tcpdump.popen() process.wait()
a671952f498d9a355d15ec332d4e01e621bf1e6d
flask_admin/model/typefmt.py
flask_admin/model/typefmt.py
from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s"></span>' % glyph) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s icon-%s"></span>' % (glyph, glyph)) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
Change bool_formatter() to be backward compatible with bootstrap2
Change bool_formatter() to be backward compatible with bootstrap2
Python
bsd-3-clause
litnimax/flask-admin,flabe81/flask-admin,marrybird/flask-admin,marrybird/flask-admin,plaes/flask-admin,phantomxc/flask-admin,wangjun/flask-admin,jamesbeebop/flask-admin,jschneier/flask-admin,flask-admin/flask-admin,ibushong/test-repo,ondoheer/flask-admin,flask-admin/flask-admin,HermasT/flask-admin,quokkaproject/flask-admin,chase-seibert/flask-admin,iurisilvio/flask-admin,flabe81/flask-admin,petrus-jvrensburg/flask-admin,CoolCloud/flask-admin,HermasT/flask-admin,ondoheer/flask-admin,jmagnusson/flask-admin,jschneier/flask-admin,betterlife/flask-admin,ArtemSerga/flask-admin,NickWoodhams/flask-admin,toddetzel/flask-admin,late-warrior/flask-admin,mrjoes/flask-admin,dxmo/flask-admin,rochacbruno/flask-admin,ibushong/test-repo,wuxiangfeng/flask-admin,jmagnusson/flask-admin,AlmogCohen/flask-admin,iurisilvio/flask-admin,likaiguo/flask-admin,HermasT/flask-admin,ondoheer/flask-admin,likaiguo/flask-admin,wuxiangfeng/flask-admin,chase-seibert/flask-admin,betterlife/flask-admin,flabe81/flask-admin,janusnic/flask-admin,plaes/flask-admin,radioprotector/flask-admin,ArtemSerga/flask-admin,closeio/flask-admin,Kha/flask-admin,ibushong/test-repo,AlmogCohen/flask-admin,chase-seibert/flask-admin,marrybird/flask-admin,CoolCloud/flask-admin,torotil/flask-admin,closeio/flask-admin,betterlife/flask-admin,petrus-jvrensburg/flask-admin,AlmogCohen/flask-admin,CoolCloud/flask-admin,lifei/flask-admin,likaiguo/flask-admin,wangjun/flask-admin,torotil/flask-admin,toddetzel/flask-admin,closeio/flask-admin,flask-admin/flask-admin,ArtemSerga/flask-admin,likaiguo/flask-admin,jschneier/flask-admin,litnimax/flask-admin,mrjoes/flask-admin,rochacbruno/flask-admin,phantomxc/flask-admin,quokkaproject/flask-admin,radioprotector/flask-admin,mikelambert/flask-admin,janusnic/flask-admin,dxmo/flask-admin,phantomxc/flask-admin,petrus-jvrensburg/flask-admin,radioprotector/flask-admin,late-warrior/flask-admin,ArtemSerga/flask-admin,NickWoodhams/flask-admin,pawl/flask-admin,flabe81/flask-admin,wangjun/flask-admin,mikelambert/flask-admin,Junnplus/flask-admin,jschneier/flask-admin,plaes/flask-admin,Junnplus/flask-admin,torotil/flask-admin,wangjun/flask-admin,jamesbeebop/flask-admin,torotil/flask-admin,LennartP/flask-admin,litnimax/flask-admin,pawl/flask-admin,janusnic/flask-admin,petrus-jvrensburg/flask-admin,CoolCloud/flask-admin,Junnplus/flask-admin,mikelambert/flask-admin,mikelambert/flask-admin,iurisilvio/flask-admin,lifei/flask-admin,plaes/flask-admin,wuxiangfeng/flask-admin,Kha/flask-admin,quokkaproject/flask-admin,iurisilvio/flask-admin,rochacbruno/flask-admin,betterlife/flask-admin,lifei/flask-admin,chase-seibert/flask-admin,litnimax/flask-admin,Kha/flask-admin,Kha/flask-admin,LennartP/flask-admin,mrjoes/flask-admin,jamesbeebop/flask-admin,LennartP/flask-admin,phantomxc/flask-admin,late-warrior/flask-admin,AlmogCohen/flask-admin,wuxiangfeng/flask-admin,rochacbruno/flask-admin,lifei/flask-admin,HermasT/flask-admin,jmagnusson/flask-admin,dxmo/flask-admin,flask-admin/flask-admin,mrjoes/flask-admin,LennartP/flask-admin,toddetzel/flask-admin,jamesbeebop/flask-admin,closeio/flask-admin,jmagnusson/flask-admin,janusnic/flask-admin,NickWoodhams/flask-admin,radioprotector/flask-admin,Junnplus/flask-admin,ondoheer/flask-admin,NickWoodhams/flask-admin,dxmo/flask-admin,pawl/flask-admin,toddetzel/flask-admin,ibushong/test-repo,quokkaproject/flask-admin,marrybird/flask-admin,late-warrior/flask-admin
from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s"></span>' % glyph) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, } Change bool_formatter() to be backward compatible with bootstrap2
from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s icon-%s"></span>' % (glyph, glyph)) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
<commit_before>from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s"></span>' % glyph) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, } <commit_msg>Change bool_formatter() to be backward compatible with bootstrap2<commit_after>
from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s icon-%s"></span>' % (glyph, glyph)) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s"></span>' % glyph) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, } Change bool_formatter() to be backward compatible with bootstrap2from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s icon-%s"></span>' % (glyph, glyph)) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
<commit_before>from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s"></span>' % glyph) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, } <commit_msg>Change bool_formatter() to be backward compatible with bootstrap2<commit_after>from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s icon-%s"></span>' % (glyph, glyph)) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
aa4db7a84f117b577f74a355c160889cf334f227
lingcod/bookmarks/forms.py
lingcod/bookmarks/forms.py
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
Hide IP from input form
Hide IP from input form
Python
bsd-3-clause
Ecotrust/madrona_addons,Ecotrust/madrona_addons
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark Hide IP from input form
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
<commit_before>from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark <commit_msg>Hide IP from input form<commit_after>
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark Hide IP from input formfrom lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
<commit_before>from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark <commit_msg>Hide IP from input form<commit_after>from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
ceceada705d8e98329f67d9ca6c8cba6cebb01cc
lingcod/bookmarks/forms.py
lingcod/bookmarks/forms.py
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta(FeatureForm.Meta): model = Bookmark
Allow IP to be blank in form
Allow IP to be blank in form --HG-- branch : bookmarks
Python
bsd-3-clause
underbluewaters/marinemap,underbluewaters/marinemap,underbluewaters/marinemap
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark Allow IP to be blank in form --HG-- branch : bookmarks
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta(FeatureForm.Meta): model = Bookmark
<commit_before>from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark <commit_msg>Allow IP to be blank in form --HG-- branch : bookmarks<commit_after>
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta(FeatureForm.Meta): model = Bookmark
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark Allow IP to be blank in form --HG-- branch : bookmarksfrom lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta(FeatureForm.Meta): model = Bookmark
<commit_before>from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput()) class Meta(FeatureForm.Meta): model = Bookmark <commit_msg>Allow IP to be blank in form --HG-- branch : bookmarks<commit_after>from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput()) altitude = forms.FloatField(widget=forms.HiddenInput()) heading = forms.FloatField(widget=forms.HiddenInput()) tilt = forms.FloatField(widget=forms.HiddenInput()) roll = forms.FloatField(widget=forms.HiddenInput()) altitudeMode = forms.FloatField(widget=forms.HiddenInput()) publicstate = forms.CharField(widget=forms.HiddenInput()) ip = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta(FeatureForm.Meta): model = Bookmark
faebc6cc528255659e7798c3754395eb91a5d5f5
website/db_create.py
website/db_create.py
"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from app import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.')
"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from database import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.')
Update import in db creation script
Update import in db creation script
Python
lgpl-2.1
reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations
"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from app import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.') Update import in db creation script
"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from database import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.')
<commit_before>"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from app import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.') <commit_msg>Update import in db creation script<commit_after>
"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from database import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.')
"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from app import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.') Update import in db creation script"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from database import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.')
<commit_before>"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from app import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.') <commit_msg>Update import in db creation script<commit_after>"""" In case of exception: InvalidRequestError: Table '(some name)' is already defined for this MetaData instance just comment out part of app.py where import of views (and what comes along - models) occurs - it has to be the very end of the file. """ from database import db from import_data import import_data print('Removing relational database...') db.reflect() db.drop_all() print('Removing relational database completed.') print('Recreating relational database...') db.create_all() print('Recreating relational database completed.') print('Importing data') import_data() print('Importing completed') print('Done, databases reset completed.')
905a08bf59f6a7d51218aaa4559e7f4efa6244a9
thunderdome/tests/groovy/test_scanner.py
thunderdome/tests/groovy/test_scanner.py
import os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) import ipdb; ipdb.set_trace() assert len(result[6].body.split('\n')) == 8
import os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) assert len(result[6].body.split('\n')) == 8 result_map = {x.name: x for x in result} assert 'get_self' in result_map assert 'return_value' in result_map assert 'long_func' in result_map
Add Unit-Test For Scanner Problem
Add Unit-Test For Scanner Problem
Python
mit
StartTheShift/thunderdome,StartTheShift/thunderdome
import os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) import ipdb; ipdb.set_trace() assert len(result[6].body.split('\n')) == 8 Add Unit-Test For Scanner Problem
import os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) assert len(result[6].body.split('\n')) == 8 result_map = {x.name: x for x in result} assert 'get_self' in result_map assert 'return_value' in result_map assert 'long_func' in result_map
<commit_before>import os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) import ipdb; ipdb.set_trace() assert len(result[6].body.split('\n')) == 8 <commit_msg>Add Unit-Test For Scanner Problem<commit_after>
import os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) assert len(result[6].body.split('\n')) == 8 result_map = {x.name: x for x in result} assert 'get_self' in result_map assert 'return_value' in result_map assert 'long_func' in result_map
import os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) import ipdb; ipdb.set_trace() assert len(result[6].body.split('\n')) == 8 Add Unit-Test For Scanner Problemimport os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) assert len(result[6].body.split('\n')) == 8 result_map = {x.name: x for x in result} assert 'get_self' in result_map assert 'return_value' in result_map assert 'long_func' in result_map
<commit_before>import os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) import ipdb; ipdb.set_trace() assert len(result[6].body.split('\n')) == 8 <commit_msg>Add Unit-Test For Scanner Problem<commit_after>import os from unittest import TestCase from thunderdome.gremlin import parse class GroovyScannerTest(TestCase): """ Test Groovy language scanner """ def test_parsing_complicated_function(self): groovy_file = os.path.join(os.path.dirname(__file__), 'test.groovy') result = parse(groovy_file) assert len(result[6].body.split('\n')) == 8 result_map = {x.name: x for x in result} assert 'get_self' in result_map assert 'return_value' in result_map assert 'long_func' in result_map
f560e2352cc06ce7e0f8bd2db0fd991d8d0ca73c
scalymongo/__init__.py
scalymongo/__init__.py
# -*- coding: utf-8 -*- from pymongo.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS
# -*- coding: utf-8 -*- from bson.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS
Use ObjectId from bson instead of pymongo
import: Use ObjectId from bson instead of pymongo pymongo >= 2.2 stops importing ObjectId from bson so it need to be pulled in directly.
Python
bsd-3-clause
allancaffee/scaly-mongo
# -*- coding: utf-8 -*- from pymongo.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS import: Use ObjectId from bson instead of pymongo pymongo >= 2.2 stops importing ObjectId from bson so it need to be pulled in directly.
# -*- coding: utf-8 -*- from bson.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS
<commit_before># -*- coding: utf-8 -*- from pymongo.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS <commit_msg>import: Use ObjectId from bson instead of pymongo pymongo >= 2.2 stops importing ObjectId from bson so it need to be pulled in directly.<commit_after>
# -*- coding: utf-8 -*- from bson.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS
# -*- coding: utf-8 -*- from pymongo.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS import: Use ObjectId from bson instead of pymongo pymongo >= 2.2 stops importing ObjectId from bson so it need to be pulled in directly.# -*- coding: utf-8 -*- from bson.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS
<commit_before># -*- coding: utf-8 -*- from pymongo.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS <commit_msg>import: Use ObjectId from bson instead of pymongo pymongo >= 2.2 stops importing ObjectId from bson so it need to be pulled in directly.<commit_after># -*- coding: utf-8 -*- from bson.objectid import ObjectId from scalymongo.document import Document from scalymongo.connection import Connection from scalymongo.schema_operators import OR, IS
35d207c6760404cfd8802227d4926aed2ac9a7ae
cards/bjcard.py
cards/bjcard.py
""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, *args, **kwarg): super().__init__(*args, **kwarg) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value
""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, suit, rank): super().__init__(suit, rank) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value
Change params to suit and rank
Change params to suit and rank
Python
mit
johnpapa2/twenty-one,johnpapa2/twenty-one
""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, *args, **kwarg): super().__init__(*args, **kwarg) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value Change params to suit and rank
""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, suit, rank): super().__init__(suit, rank) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value
<commit_before>""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, *args, **kwarg): super().__init__(*args, **kwarg) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value <commit_msg>Change params to suit and rank<commit_after>
""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, suit, rank): super().__init__(suit, rank) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value
""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, *args, **kwarg): super().__init__(*args, **kwarg) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value Change params to suit and rank""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, suit, rank): super().__init__(suit, rank) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value
<commit_before>""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, *args, **kwarg): super().__init__(*args, **kwarg) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value <commit_msg>Change params to suit and rank<commit_after>""" Created on Dec 24, 2016 @author: john papa Copyright 2016 John Papa. All rights reserved. This work is licensed under the MIT License. """ from .card import Card class BjCard(Card): def __init__(self, suit, rank): super().__init__(suit, rank) @property def value(self): """ Returns the value of the card used for scoring the game """ if self._value: return self._value elif self.rank not in list('JQKA'): self._value = int(self.rank) elif self.rank in list('JQK'): self._value = 10 else: self._value = 11 return self._value
a9e24dc8444f24ee9be0987f9dc5fbe96b5c3408
money_conversion/money.py
money_conversion/money.py
class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper()
class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() def __repr__(self): return "%.2f %s" % (self.amount, self.currency)
Add reprensation method for Money class
Add reprensation method for Money class
Python
mit
mdsrosa/money-conversion-py
class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() Add reprensation method for Money class
class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() def __repr__(self): return "%.2f %s" % (self.amount, self.currency)
<commit_before> class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() <commit_msg>Add reprensation method for Money class<commit_after>
class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() def __repr__(self): return "%.2f %s" % (self.amount, self.currency)
class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() Add reprensation method for Money class class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() def __repr__(self): return "%.2f %s" % (self.amount, self.currency)
<commit_before> class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() <commit_msg>Add reprensation method for Money class<commit_after> class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() def __repr__(self): return "%.2f %s" % (self.amount, self.currency)
7fbcbaed02233eed41781adf665c0027d7b0e05f
src/geoserver/workspace.py
src/geoserver/workspace.py
from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): assert isinstance(name, basestring) self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href)
from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): super(Workspace, self).__init__() self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href)
Call superclass constructor for Workspace
Call superclass constructor for Workspace
Python
mit
cristianzamar/gsconfig,boundlessgeo/gsconfig,Geode/gsconfig,afabiani/gsconfig,garnertb/gsconfig.py,scottp-dpaw/gsconfig
from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): assert isinstance(name, basestring) self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href) Call superclass constructor for Workspace
from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): super(Workspace, self).__init__() self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href)
<commit_before>from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): assert isinstance(name, basestring) self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href) <commit_msg>Call superclass constructor for Workspace<commit_after>
from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): super(Workspace, self).__init__() self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href)
from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): assert isinstance(name, basestring) self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href) Call superclass constructor for Workspacefrom geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): super(Workspace, self).__init__() self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href)
<commit_before>from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): assert isinstance(name, basestring) self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href) <commit_msg>Call superclass constructor for Workspace<commit_after>from geoserver.support import atom_link, xml_property, write_bool, ResourceInfo import string def workspace_from_index(catalog, node): name = node.find("name") return Workspace(catalog, name.text) class Workspace(ResourceInfo): resource_type = "workspace" def __init__(self, catalog, name): super(Workspace, self).__init__() self.catalog = catalog self.name = name @property def href(self): return "%s/workspaces/%s.xml" % (self.catalog.service_url, self.name) @property def coveragestore_url(self): return "%s/workspaces/%s/coveragestores.xml" % (self.catalog.service_url, self.name) @property def datastore_url(self): return "%s/workspaces/%s/datastores.xml" % (self.catalog.service_url, self.name) enabled = xml_property("enabled", "enabled", lambda x: string.lower(x) == 'true') writers = dict( enabled = write_bool("enabled") ) def __repr__(self): return "%s @ %s" % (self.name, self.href)
43978f8c709d5f195229deb6ec7817a1815a4db6
sass_processor/storage.py
sass_processor/storage.py
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except ImportError: pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except (AttributeError, ImportError): pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result
Fix in case s3boto is not installed
Fix in case s3boto is not installed
Python
mit
jrief/django-sass-processor,jrief/django-sass-processor
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except ImportError: pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result Fix in case s3boto is not installed
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except (AttributeError, ImportError): pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result
<commit_before># -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except ImportError: pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result <commit_msg>Fix in case s3boto is not installed<commit_after>
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except (AttributeError, ImportError): pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except ImportError: pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result Fix in case s3boto is not installed# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except (AttributeError, ImportError): pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result
<commit_before># -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except ImportError: pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result <commit_msg>Fix in case s3boto is not installed<commit_after># -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles.finders import get_finders from django.core.files.storage import FileSystemStorage class SassFileStorage(FileSystemStorage): def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = getattr(settings, 'SASS_PROCESSOR_ROOT', settings.STATIC_ROOT) if base_url is None: base_url = settings.STATIC_URL super(SassFileStorage, self).__init__(location, base_url, *args, **kwargs) try: from storages.backends.s3boto3 import S3Boto3Storage class SassS3Boto3Storage(S3Boto3Storage): base_url = '{}.s3.amazonaws.com'.format(settings.AWS_STORAGE_BUCKET_NAME) except (AttributeError, ImportError): pass def find_file(path): for finder in get_finders(): result = finder.find(path) if result: return result
142e361d2bcfbdc15939ad33c600bf943025f7b1
api/v1/serializers/no_project_serializer.py
api/v1/serializers/no_project_serializer.py
from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .application_serializer import ApplicationSerializer from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): applications = serializers.SerializerMethodField('get_user_applications') instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_applications(self, atmo_user): return [ApplicationSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.application_set.filter(only_current(), projects=None)] def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('applications', 'instances', 'volumes')
from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('instances', 'volumes')
Remove final references to application
Remove final references to application
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .application_serializer import ApplicationSerializer from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): applications = serializers.SerializerMethodField('get_user_applications') instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_applications(self, atmo_user): return [ApplicationSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.application_set.filter(only_current(), projects=None)] def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('applications', 'instances', 'volumes') Remove final references to application
from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('instances', 'volumes')
<commit_before>from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .application_serializer import ApplicationSerializer from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): applications = serializers.SerializerMethodField('get_user_applications') instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_applications(self, atmo_user): return [ApplicationSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.application_set.filter(only_current(), projects=None)] def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('applications', 'instances', 'volumes') <commit_msg>Remove final references to application<commit_after>
from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('instances', 'volumes')
from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .application_serializer import ApplicationSerializer from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): applications = serializers.SerializerMethodField('get_user_applications') instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_applications(self, atmo_user): return [ApplicationSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.application_set.filter(only_current(), projects=None)] def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('applications', 'instances', 'volumes') Remove final references to applicationfrom core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('instances', 'volumes')
<commit_before>from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .application_serializer import ApplicationSerializer from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): applications = serializers.SerializerMethodField('get_user_applications') instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_applications(self, atmo_user): return [ApplicationSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.application_set.filter(only_current(), projects=None)] def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('applications', 'instances', 'volumes') <commit_msg>Remove final references to application<commit_after>from core.models.user import AtmosphereUser from core.query import only_current, only_current_source from rest_framework import serializers from .instance_serializer import InstanceSerializer from .volume_serializer import VolumeSerializer class NoProjectSerializer(serializers.ModelSerializer): instances = serializers.SerializerMethodField('get_user_instances') volumes = serializers.SerializerMethodField('get_user_volumes') def get_user_instances(self, atmo_user): return [InstanceSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.instance_set.filter(only_current(), source__provider__active=True, projects=None)] def get_user_volumes(self, atmo_user): return [VolumeSerializer( item, context={'request': self.context.get('request')}).data for item in atmo_user.volume_set().filter(*only_current_source(), instance_source__provider__active=True, projects=None)] class Meta: model = AtmosphereUser fields = ('instances', 'volumes')
ef8e99bb487cde437b5f669f662a0787b2047efa
src/penn_chime/settings.py
src/penn_chime/settings.py
#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=75, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), )
#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=60, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), )
Move n_days back to 60 so social distancing can be seen in the plots
Move n_days back to 60 so social distancing can be seen in the plots
Python
mit
CodeForPhilly/chime,CodeForPhilly/chime,CodeForPhilly/chime
#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=75, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), ) Move n_days back to 60 so social distancing can be seen in the plots
#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=60, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), )
<commit_before>#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=75, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), ) <commit_msg>Move n_days back to 60 so social distancing can be seen in the plots<commit_after>
#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=60, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), )
#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=75, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), ) Move n_days back to 60 so social distancing can be seen in the plots#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=60, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), )
<commit_before>#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=75, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), ) <commit_msg>Move n_days back to 60 so social distancing can be seen in the plots<commit_after>#!/usr/bin/env python from datetime import date from .parameters import Parameters, Regions, RateLos DEFAULTS = Parameters( region=Regions( delaware=564696, chester=519293, montgomery=826075, bucks=628341, philly=1581000, ), current_hospitalized=32, date_first_hospitalized=date(2020,3,7), doubling_time=4.0, hospitalized=RateLos(0.025, 7), icu=RateLos(0.0075, 9), infectious_days=14, known_infected=510, market_share=0.15, n_days=60, relative_contact_rate=0.3, ventilated=RateLos(0.005, 10), )
f100adc7991f894eac40ebe8ea6b9b67c89df00c
rackattack/common/globallock.py
rackattack/common/globallock.py
import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.1: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True
import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True
Increase global lock holding duration due to new network transactions
Increase global lock holding duration due to new network transactions
Python
apache-2.0
eliran-stratoscale/rackattack-virtual,eliran-stratoscale/rackattack-virtual,Stratoscale/rackattack-virtual,Stratoscale/rackattack-virtual
import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.1: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True Increase global lock holding duration due to new network transactions
import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True
<commit_before>import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.1: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True <commit_msg>Increase global lock holding duration due to new network transactions<commit_after>
import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True
import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.1: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True Increase global lock holding duration due to new network transactionsimport threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True
<commit_before>import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.1: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True <commit_msg>Increase global lock holding duration due to new network transactions<commit_after>import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True
50ad6dedb64c8e74b8d27375b9320f9fd9126c9c
registration/__init__.py
registration/__init__.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
Add utility function for retrieving the active registration backend.
Add utility function for retrieving the active registration backend.
Python
bsd-3-clause
alawnchen/django-registration,memnonila/django-registration,furious-luke/django-registration,furious-luke/django-registration,tanjunyen/django-registration,yorkedork/django-registration,imgmix/django-registration,arpitremarkable/django-registration,PSU-OIT-ARC/django-registration,erinspace/django-registration,rulz/django-registration,matejkloska/django-registration,alawnchen/django-registration,timgraham/django-registration,stillmatic/django-registration,Geffersonvivan/django-registration,maitho/django-registration,sergafts/django-registration,rulz/django-registration,wy123123/django-registration,stillmatic/django-registration,wda-hb/test,kazitanvirahsan/django-registration,wy123123/django-registration,allo-/django-registration,percipient/django-registration,percipient/django-registration,torchingloom/django-registration,torchingloom/django-registration,PetrDlouhy/django-registration,kinsights/django-registration,tanjunyen/django-registration,ei-grad/django-registration,mick-t/django-registration,PetrDlouhy/django-registration,timgraham/django-registration,mick-t/django-registration,kazitanvirahsan/django-registration,pando85/django-registration,nikolas/django-registration,kinsights/django-registration,wda-hb/test,imgmix/django-registration,matejkloska/django-registration,nikolas/django-registration,arpitremarkable/django-registration,Geffersonvivan/django-registration,memnonila/django-registration,pando85/django-registration,sergafts/django-registration,PSU-OIT-ARC/django-registration,yorkedork/django-registration,ei-grad/django-registration,maitho/django-registration,allo-/django-registration,erinspace/django-registration
Add utility function for retrieving the active registration backend.
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
<commit_before><commit_msg>Add utility function for retrieving the active registration backend.<commit_after>
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
Add utility function for retrieving the active registration backend.from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
<commit_before><commit_msg>Add utility function for retrieving the active registration backend.<commit_after>from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.core.exceptions.ImproperlyConfigured`` if the specified backend cannot be located. """ i = settings.REGISTRATION_BACKEND.rfind('.') module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:] try: mod = import_module(module) except ImportError, e: raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) try: backend_class = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) return backend_class()
37da65953471b5dd0930e102b861878012938701
registration/__init__.py
registration/__init__.py
from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
Python
bsd-3-clause
lubosz/django-registration,lubosz/django-registration
from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
<commit_before>from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover <commit_msg>Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.<commit_after>
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
<commit_before>from django.utils.version import get_version as django_get_version VERSION = (0, 9, 0, 'beta', 1) def get_version(): return django_get_version(VERSION) # pragma: no cover <commit_msg>Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.<commit_after>VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
c02c3f4603c967c4e8df8314bfe0f4759cb0bca4
openprescribing/manage.py
openprescribing/manage.py
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1 and sys.argv[1] in ['test', 'pipeline_e2e_tests']: os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1: if sys.argv[1] == 'test': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" elif sys.argv[1] == 'pipeline_e2e_tests': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.e2etest" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Set settings for e2e tests correctly
Set settings for e2e tests correctly
Python
mit
annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1 and sys.argv[1] in ['test', 'pipeline_e2e_tests']: os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Set settings for e2e tests correctly
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1: if sys.argv[1] == 'test': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" elif sys.argv[1] == 'pipeline_e2e_tests': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.e2etest" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
<commit_before>#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1 and sys.argv[1] in ['test', 'pipeline_e2e_tests']: os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) <commit_msg>Set settings for e2e tests correctly<commit_after>
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1: if sys.argv[1] == 'test': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" elif sys.argv[1] == 'pipeline_e2e_tests': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.e2etest" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1 and sys.argv[1] in ['test', 'pipeline_e2e_tests']: os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Set settings for e2e tests correctly#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1: if sys.argv[1] == 'test': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" elif sys.argv[1] == 'pipeline_e2e_tests': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.e2etest" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
<commit_before>#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1 and sys.argv[1] in ['test', 'pipeline_e2e_tests']: os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) <commit_msg>Set settings for e2e tests correctly<commit_after>#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # We can't do read_dotenv('../environment') because that assumes that when # manage.py we are in its current directory, which isn't the case for cron # jobs. env_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '..', 'environment' ) dotenv.read_dotenv(env_path, override=True) if len(sys.argv) > 1: if sys.argv[1] == 'test': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.test" elif sys.argv[1] == 'pipeline_e2e_tests': os.environ["DJANGO_SETTINGS_MODULE"] = "openprescribing.settings.e2etest" from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
13a25d26dc53f7a3c2f1a8706de26339035bea39
lib/bx/misc/bgzf_tests.py
lib/bx/misc/bgzf_tests.py
import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" ) print f.read( 10 ) print f.seek( 0 ) print f.read( 10 ) test_bgzf()
import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" ) assert f.read( 10 ) == "begin 644 " print f.seek( 0 ) assert f.read( 10 ) == "begin 644 "
Make BGZF test a real unittest
Make BGZF test a real unittest
Python
mit
uhjish/bx-python,uhjish/bx-python,uhjish/bx-python
import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" ) print f.read( 10 ) print f.seek( 0 ) print f.read( 10 ) test_bgzf()Make BGZF test a real unittest
import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" ) assert f.read( 10 ) == "begin 644 " print f.seek( 0 ) assert f.read( 10 ) == "begin 644 "
<commit_before>import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" ) print f.read( 10 ) print f.seek( 0 ) print f.read( 10 ) test_bgzf()<commit_msg>Make BGZF test a real unittest<commit_after>
import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" ) assert f.read( 10 ) == "begin 644 " print f.seek( 0 ) assert f.read( 10 ) == "begin 644 "
import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" ) print f.read( 10 ) print f.seek( 0 ) print f.read( 10 ) test_bgzf()Make BGZF test a real unittestimport bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" ) assert f.read( 10 ) == "begin 644 " print f.seek( 0 ) assert f.read( 10 ) == "begin 644 "
<commit_before>import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" ) print f.read( 10 ) print f.seek( 0 ) print f.read( 10 ) test_bgzf()<commit_msg>Make BGZF test a real unittest<commit_after>import bx.misc.bgzf def test_bgzf(): f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" ) assert f.read( 10 ) == "begin 644 " print f.seek( 0 ) assert f.read( 10 ) == "begin 644 "
de1988304714b44e641a4c4ac50fa650887621d6
geoportail/geonames/views.py
geoportail/geonames/views.py
import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = u'\n'.join([u'{name} <em>{county_name}</em>|{lon} {lat}'.format( name=unicodedata.normalize('NFKD', t.name), county_name=t.county_name, lon=t.point.coords[0], lat=t.point.coords[1], ) for t in towns]) if not content: content = _('No results. Search is limited to city names.') return HttpResponse(content)
import json import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = [{ "name": unicodedata.normalize('NFKD', t.name), "county_name": t.county_name, "lon": t.point.coords[0], "lat": t.point.coords[1], } for t in towns] if not content: content = [{'name': _('No results. Search is limited to city names.')}] return HttpResponse(json.dumps(content), content_type='application/json')
Return JSON in the autocomplete view
Return JSON in the autocomplete view
Python
bsd-3-clause
brutasse/geoportail,brutasse/geoportail,brutasse/geoportail
import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = u'\n'.join([u'{name} <em>{county_name}</em>|{lon} {lat}'.format( name=unicodedata.normalize('NFKD', t.name), county_name=t.county_name, lon=t.point.coords[0], lat=t.point.coords[1], ) for t in towns]) if not content: content = _('No results. Search is limited to city names.') return HttpResponse(content) Return JSON in the autocomplete view
import json import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = [{ "name": unicodedata.normalize('NFKD', t.name), "county_name": t.county_name, "lon": t.point.coords[0], "lat": t.point.coords[1], } for t in towns] if not content: content = [{'name': _('No results. Search is limited to city names.')}] return HttpResponse(json.dumps(content), content_type='application/json')
<commit_before>import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = u'\n'.join([u'{name} <em>{county_name}</em>|{lon} {lat}'.format( name=unicodedata.normalize('NFKD', t.name), county_name=t.county_name, lon=t.point.coords[0], lat=t.point.coords[1], ) for t in towns]) if not content: content = _('No results. Search is limited to city names.') return HttpResponse(content) <commit_msg>Return JSON in the autocomplete view<commit_after>
import json import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = [{ "name": unicodedata.normalize('NFKD', t.name), "county_name": t.county_name, "lon": t.point.coords[0], "lat": t.point.coords[1], } for t in towns] if not content: content = [{'name': _('No results. Search is limited to city names.')}] return HttpResponse(json.dumps(content), content_type='application/json')
import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = u'\n'.join([u'{name} <em>{county_name}</em>|{lon} {lat}'.format( name=unicodedata.normalize('NFKD', t.name), county_name=t.county_name, lon=t.point.coords[0], lat=t.point.coords[1], ) for t in towns]) if not content: content = _('No results. Search is limited to city names.') return HttpResponse(content) Return JSON in the autocomplete viewimport json import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = [{ "name": unicodedata.normalize('NFKD', t.name), "county_name": t.county_name, "lon": t.point.coords[0], "lat": t.point.coords[1], } for t in towns] if not content: content = [{'name': _('No results. Search is limited to city names.')}] return HttpResponse(json.dumps(content), content_type='application/json')
<commit_before>import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = u'\n'.join([u'{name} <em>{county_name}</em>|{lon} {lat}'.format( name=unicodedata.normalize('NFKD', t.name), county_name=t.county_name, lon=t.point.coords[0], lat=t.point.coords[1], ) for t in towns]) if not content: content = _('No results. Search is limited to city names.') return HttpResponse(content) <commit_msg>Return JSON in the autocomplete view<commit_after>import json import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = [{ "name": unicodedata.normalize('NFKD', t.name), "county_name": t.county_name, "lon": t.point.coords[0], "lat": t.point.coords[1], } for t in towns] if not content: content = [{'name': _('No results. Search is limited to city names.')}] return HttpResponse(json.dumps(content), content_type='application/json')
44d1623e8b7c0922cb9138d5e589a7a9e51f7610
enactiveagents/model/perceptionhandler.py
enactiveagents/model/perceptionhandler.py
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta elif isinstance(entity, structure.Food): return "f%s" % delta return ""
Add food to the perception handler
Add food to the perception handler
Python
mit
Beskhue/enactive-agents,Beskhue/enactive-agents,Beskhue/enactive-agents
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""Add food to the perception handler
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta elif isinstance(entity, structure.Food): return "f%s" % delta return ""
<commit_before>""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""<commit_msg>Add food to the perception handler<commit_after>
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta elif isinstance(entity, structure.Food): return "f%s" % delta return ""
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""Add food to the perception handler""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta elif isinstance(entity, structure.Food): return "f%s" % delta return ""
<commit_before>""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""<commit_msg>Add food to the perception handler<commit_after>""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta elif isinstance(entity, structure.Food): return "f%s" % delta return ""
877d13f1ef433c99bf61e0a3eaa0228240997eca
nanomon/probe/__init__.py
nanomon/probe/__init__.py
import time import logging from nanomon.queue import QueueWorker logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete() def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) return True
import time import logging from nanomon.queue import QueueWorker from nanomon.resources import MonitoringGroup, Node, Monitor, Command logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) group_objects = [] node_name = task.task['name'] monitoring_groups = task.task['monitoring_groups'] for group in monitoring_groups: try: group_objects.append(MonitoringGroup.registry[group]) except KeyError: logger.warning("Monitoring group '%s' not found in registry " "for node '%s'. Skipping." % (group, node_name)) continue node = Node.registry.get(node_name, Node(node_name, monitoring_groups=group_objects)) logger.debug("Executing monitors for node %s:" % (node_name)) logger.debug(node.execute_monitors()) return True def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete()
Make the probe actually do something with monitors
Make the probe actually do something with monitors Uses the execute_monitors method of the nodes now, which doesn't really do much, but will in the future.
Python
bsd-2-clause
cloudtools/nymms
import time import logging from nanomon.queue import QueueWorker logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete() def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) return True Make the probe actually do something with monitors Uses the execute_monitors method of the nodes now, which doesn't really do much, but will in the future.
import time import logging from nanomon.queue import QueueWorker from nanomon.resources import MonitoringGroup, Node, Monitor, Command logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) group_objects = [] node_name = task.task['name'] monitoring_groups = task.task['monitoring_groups'] for group in monitoring_groups: try: group_objects.append(MonitoringGroup.registry[group]) except KeyError: logger.warning("Monitoring group '%s' not found in registry " "for node '%s'. Skipping." % (group, node_name)) continue node = Node.registry.get(node_name, Node(node_name, monitoring_groups=group_objects)) logger.debug("Executing monitors for node %s:" % (node_name)) logger.debug(node.execute_monitors()) return True def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete()
<commit_before>import time import logging from nanomon.queue import QueueWorker logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete() def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) return True <commit_msg>Make the probe actually do something with monitors Uses the execute_monitors method of the nodes now, which doesn't really do much, but will in the future.<commit_after>
import time import logging from nanomon.queue import QueueWorker from nanomon.resources import MonitoringGroup, Node, Monitor, Command logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) group_objects = [] node_name = task.task['name'] monitoring_groups = task.task['monitoring_groups'] for group in monitoring_groups: try: group_objects.append(MonitoringGroup.registry[group]) except KeyError: logger.warning("Monitoring group '%s' not found in registry " "for node '%s'. Skipping." % (group, node_name)) continue node = Node.registry.get(node_name, Node(node_name, monitoring_groups=group_objects)) logger.debug("Executing monitors for node %s:" % (node_name)) logger.debug(node.execute_monitors()) return True def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete()
import time import logging from nanomon.queue import QueueWorker logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete() def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) return True Make the probe actually do something with monitors Uses the execute_monitors method of the nodes now, which doesn't really do much, but will in the future.import time import logging from nanomon.queue import QueueWorker from nanomon.resources import MonitoringGroup, Node, Monitor, Command logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) group_objects = [] node_name = task.task['name'] monitoring_groups = task.task['monitoring_groups'] for group in monitoring_groups: try: group_objects.append(MonitoringGroup.registry[group]) except KeyError: logger.warning("Monitoring group '%s' not found in registry " "for node '%s'. Skipping." % (group, node_name)) continue node = Node.registry.get(node_name, Node(node_name, monitoring_groups=group_objects)) logger.debug("Executing monitors for node %s:" % (node_name)) logger.debug(node.execute_monitors()) return True def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete()
<commit_before>import time import logging from nanomon.queue import QueueWorker logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete() def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) return True <commit_msg>Make the probe actually do something with monitors Uses the execute_monitors method of the nodes now, which doesn't really do much, but will in the future.<commit_after>import time import logging from nanomon.queue import QueueWorker from nanomon.resources import MonitoringGroup, Node, Monitor, Command logger = logging.getLogger(__name__) class Probe(QueueWorker): def run(self, max_sleep=2, min_sleep=1): did_task = False max_sleep = sleep = float(max_sleep) while True: last_did_task = did_task did_task = self.perform_task() if not did_task: if not last_did_task: sleep = sleep - 1 if sleep <= 0: sleep = min_sleep logger.debug("Sleeping for %.02f." % (sleep)) time.sleep(sleep) else: sleep = max_sleep def task_handler(self, task): logger.debug("Handling task: %s" % (task.task)) group_objects = [] node_name = task.task['name'] monitoring_groups = task.task['monitoring_groups'] for group in monitoring_groups: try: group_objects.append(MonitoringGroup.registry[group]) except KeyError: logger.warning("Monitoring group '%s' not found in registry " "for node '%s'. Skipping." % (group, node_name)) continue node = Node.registry.get(node_name, Node(node_name, monitoring_groups=group_objects)) logger.debug("Executing monitors for node %s:" % (node_name)) logger.debug(node.execute_monitors()) return True def handle_task_result(self, task, result): if result: logger.debug("Deleting task: %s" % (task.task)) task.delete()
01e8e212768bb80476b9ce7da938fc04aa306f3e
tensorflow_datasets/dataset_collections/xtreme/xtreme_test.py
tensorflow_datasets/dataset_collections/xtreme/xtreme_test.py
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestLongt5(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestXtreme(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme
Solve typo in xtreme testing
Solve typo in xtreme testing PiperOrigin-RevId: 477195014
Python
apache-2.0
tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestLongt5(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme Solve typo in xtreme testing PiperOrigin-RevId: 477195014
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestXtreme(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme
<commit_before># coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestLongt5(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme <commit_msg>Solve typo in xtreme testing PiperOrigin-RevId: 477195014<commit_after>
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestXtreme(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestLongt5(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme Solve typo in xtreme testing PiperOrigin-RevId: 477195014# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestXtreme(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme
<commit_before># coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestLongt5(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme <commit_msg>Solve typo in xtreme testing PiperOrigin-RevId: 477195014<commit_after># coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for xtreme.""" from tensorflow_datasets.dataset_collections.xtreme import xtreme from tensorflow_datasets.testing.dataset_collection_builder_testing import DatasetCollectionTestBase class TestXtreme(DatasetCollectionTestBase): DATASET_COLLECTION_CLASS = xtreme.Xtreme
c598306bd1f323f62167c6be33205019b53296b9
tests/test_vector2_negation.py
tests/test_vector2_negation.py
from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector)
from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector) @given(vector=vectors()) def test_negation_addition(vector: Vector2): assert vector + (- vector) == (0, 0)
Test that negation is the additive inverse
tests/negation: Test that negation is the additive inverse
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector) tests/negation: Test that negation is the additive inverse
from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector) @given(vector=vectors()) def test_negation_addition(vector: Vector2): assert vector + (- vector) == (0, 0)
<commit_before>from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector) <commit_msg>tests/negation: Test that negation is the additive inverse<commit_after>
from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector) @given(vector=vectors()) def test_negation_addition(vector: Vector2): assert vector + (- vector) == (0, 0)
from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector) tests/negation: Test that negation is the additive inversefrom hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector) @given(vector=vectors()) def test_negation_addition(vector: Vector2): assert vector + (- vector) == (0, 0)
<commit_before>from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector) <commit_msg>tests/negation: Test that negation is the additive inverse<commit_after>from hypothesis import given from ppb_vector import Vector2 from utils import vectors @given(vector=vectors()) def test_negation_scalar(vector: Vector2): assert - vector == (-1) * vector @given(vector=vectors()) def test_negation_involutive(vector: Vector2): assert vector == - (- vector) @given(vector=vectors()) def test_negation_addition(vector: Vector2): assert vector + (- vector) == (0, 0)
dfb11ba136359e9624b05af2e065eac8d8cd5111
plankton/lcg/lcg.py
plankton/lcg/lcg.py
from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self._DEFAULT_SEED # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:])
from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self.seed(self._DEFAULT_SEED) # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:])
Use seed function in constructor since some LCGs might overwrite it.
Use seed function in constructor since some LCGs might overwrite it.
Python
mit
SpacePlant/Plankton
from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self._DEFAULT_SEED # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:]) Use seed function in constructor since some LCGs might overwrite it.
from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self.seed(self._DEFAULT_SEED) # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:])
<commit_before>from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self._DEFAULT_SEED # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:]) <commit_msg>Use seed function in constructor since some LCGs might overwrite it.<commit_after>
from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self.seed(self._DEFAULT_SEED) # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:])
from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self._DEFAULT_SEED # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:]) Use seed function in constructor since some LCGs might overwrite it.from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self.seed(self._DEFAULT_SEED) # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:])
<commit_before>from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self._DEFAULT_SEED # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:]) <commit_msg>Use seed function in constructor since some LCGs might overwrite it.<commit_after>from collections import namedtuple from ..prng import PRNG class LCG(PRNG): LCGConstants = namedtuple('LCGConstants', ['a', # Multiplier 'c', # Increment 'm']) # Modulus def __init__(self): self._state = self.seed(self._DEFAULT_SEED) # Returns a tuple with the LCG constants def _get_constants(self): pass def seed(self, val): self._state = val % self._get_constants().m def next(self): constants = self._get_constants() self._state = (constants.a * self._state + constants.c) % constants.m return self._state def recover(self, vals): self._verify_input(vals) self._state = vals[0] self._verify_output(vals[1:])
0bd82f80279348f101d09b8aa0955c8ab934533c
tests/window/WINDOW_CAPTION.py
tests/window/WINDOW_CAPTION.py
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(200, 200) w2 = window.Window(200, 200) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(400, 200, resizable=True) w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
Make windows bigger in this test so the captions can be read.
Make windows bigger in this test so the captions can be read. Index: tests/window/WINDOW_CAPTION.py =================================================================== --- tests/window/WINDOW_CAPTION.py (revision 777) +++ tests/window/WINDOW_CAPTION.py (working copy) @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): - w1 = window.Window(200, 200) - w2 = window.Window(200, 200) + w1 = window.Window(400, 200, resizable=True) + w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
Python
bsd-3-clause
mpasternak/pyglet-fix-issue-552,kmonsoor/pyglet,odyaka341/pyglet,cledio66/pyglet,arifgursel/pyglet,cledio66/pyglet,shaileshgoogler/pyglet,gdkar/pyglet,arifgursel/pyglet,kmonsoor/pyglet,cledio66/pyglet,Austin503/pyglet,Austin503/pyglet,Alwnikrotikz/pyglet,mpasternak/michaldtz-fixes-518-522,arifgursel/pyglet,odyaka341/pyglet,mpasternak/michaldtz-fix-552,kmonsoor/pyglet,shaileshgoogler/pyglet,qbektrix/pyglet,mpasternak/michaldtz-fixes-518-522,qbektrix/pyglet,qbektrix/pyglet,xshotD/pyglet,Alwnikrotikz/pyglet,gdkar/pyglet,mpasternak/pyglet-fix-issue-518-522,xshotD/pyglet,mpasternak/pyglet-fix-issue-518-522,Austin503/pyglet,Alwnikrotikz/pyglet,mpasternak/pyglet-fix-issue-518-522,shaileshgoogler/pyglet,google-code-export/pyglet,mpasternak/michaldtz-fixes-518-522,gdkar/pyglet,odyaka341/pyglet,mpasternak/pyglet-fix-issue-552,Alwnikrotikz/pyglet,odyaka341/pyglet,google-code-export/pyglet,mpasternak/michaldtz-fix-552,mpasternak/pyglet-fix-issue-552,google-code-export/pyglet,shaileshgoogler/pyglet,arifgursel/pyglet,Austin503/pyglet,mpasternak/michaldtz-fix-552,qbektrix/pyglet,gdkar/pyglet,google-code-export/pyglet,mpasternak/pyglet-fix-issue-518-522,cledio66/pyglet,kmonsoor/pyglet,xshotD/pyglet,arifgursel/pyglet,kmonsoor/pyglet,xshotD/pyglet,Austin503/pyglet,google-code-export/pyglet,shaileshgoogler/pyglet,mpasternak/pyglet-fix-issue-552,qbektrix/pyglet,cledio66/pyglet,odyaka341/pyglet,mpasternak/michaldtz-fixes-518-522,mpasternak/michaldtz-fix-552,gdkar/pyglet,xshotD/pyglet,Alwnikrotikz/pyglet
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(200, 200) w2 = window.Window(200, 200) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main() Make windows bigger in this test so the captions can be read. Index: tests/window/WINDOW_CAPTION.py =================================================================== --- tests/window/WINDOW_CAPTION.py (revision 777) +++ tests/window/WINDOW_CAPTION.py (working copy) @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): - w1 = window.Window(200, 200) - w2 = window.Window(200, 200) + w1 = window.Window(400, 200, resizable=True) + w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(400, 200, resizable=True) w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
<commit_before>#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(200, 200) w2 = window.Window(200, 200) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main() <commit_msg>Make windows bigger in this test so the captions can be read. Index: tests/window/WINDOW_CAPTION.py =================================================================== --- tests/window/WINDOW_CAPTION.py (revision 777) +++ tests/window/WINDOW_CAPTION.py (working copy) @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): - w1 = window.Window(200, 200) - w2 = window.Window(200, 200) + w1 = window.Window(400, 200, resizable=True) + w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?')<commit_after>
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(400, 200, resizable=True) w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(200, 200) w2 = window.Window(200, 200) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main() Make windows bigger in this test so the captions can be read. Index: tests/window/WINDOW_CAPTION.py =================================================================== --- tests/window/WINDOW_CAPTION.py (revision 777) +++ tests/window/WINDOW_CAPTION.py (working copy) @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): - w1 = window.Window(200, 200) - w2 = window.Window(200, 200) + w1 = window.Window(400, 200, resizable=True) + w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?')#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(400, 200, resizable=True) w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
<commit_before>#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(200, 200) w2 = window.Window(200, 200) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main() <commit_msg>Make windows bigger in this test so the captions can be read. Index: tests/window/WINDOW_CAPTION.py =================================================================== --- tests/window/WINDOW_CAPTION.py (revision 777) +++ tests/window/WINDOW_CAPTION.py (working copy) @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): - w1 = window.Window(200, 200) - w2 = window.Window(200, 200) + w1 = window.Window(400, 200, resizable=True) + w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?')<commit_after>#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the test. ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import time import unittest from pyglet import window class WINDOW_CAPTION(unittest.TestCase): def test_caption(self): w1 = window.Window(400, 200, resizable=True) w2 = window.Window(400, 200, resizable=True) count = 1 w1.set_caption('Window caption %d' % count) w2.set_caption(u'\u00bfHabla espa\u00f1ol?') last_time = time.time() while not (w1.has_exit or w2.has_exit): if time.time() - last_time > 1: count += 1 w1.set_caption('Window caption %d' % count) last_time = time.time() w1.dispatch_events() w2.dispatch_events() w1.close() w2.close() if __name__ == '__main__': unittest.main()
d03250e1af17a40be3b9aa70fef67e50ab556a87
numba2/compiler/layout.py
numba2/compiler/layout.py
# -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ from numba2.lib import vectorobject from numba2.lib import arrayobject from numba2.runtime.obj import pointerobject if ty.impl == pointerobject.Pointer: (base,) = ty.parameters return ptypes.Pointer(representation_type(base)) if ty.impl == vectorobject.Vector: base, count = ty.parameters return ptypes.Vector(representation_type(base), count) if ty.impl == arrayobject.Array: base, count = ty.parameters return ptypes.Array(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type
# -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ # NOTE: special cases should be kept to an absolute minimum here. They # should probably be introduced only if ctypes cannot represent the # type from numba2.lib import vectorobject if ty.impl == vectorobject.Vector: # Ctypes does not support vectors base, count = ty.parameters return ptypes.Vector(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type
Remove some object representation clobbering code
Remove some object representation clobbering code
Python
bsd-2-clause
flypy/flypy,flypy/flypy
# -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ from numba2.lib import vectorobject from numba2.lib import arrayobject from numba2.runtime.obj import pointerobject if ty.impl == pointerobject.Pointer: (base,) = ty.parameters return ptypes.Pointer(representation_type(base)) if ty.impl == vectorobject.Vector: base, count = ty.parameters return ptypes.Vector(representation_type(base), count) if ty.impl == arrayobject.Array: base, count = ty.parameters return ptypes.Array(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type Remove some object representation clobbering code
# -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ # NOTE: special cases should be kept to an absolute minimum here. They # should probably be introduced only if ctypes cannot represent the # type from numba2.lib import vectorobject if ty.impl == vectorobject.Vector: # Ctypes does not support vectors base, count = ty.parameters return ptypes.Vector(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type
<commit_before># -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ from numba2.lib import vectorobject from numba2.lib import arrayobject from numba2.runtime.obj import pointerobject if ty.impl == pointerobject.Pointer: (base,) = ty.parameters return ptypes.Pointer(representation_type(base)) if ty.impl == vectorobject.Vector: base, count = ty.parameters return ptypes.Vector(representation_type(base), count) if ty.impl == arrayobject.Array: base, count = ty.parameters return ptypes.Array(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type <commit_msg>Remove some object representation clobbering code<commit_after>
# -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ # NOTE: special cases should be kept to an absolute minimum here. They # should probably be introduced only if ctypes cannot represent the # type from numba2.lib import vectorobject if ty.impl == vectorobject.Vector: # Ctypes does not support vectors base, count = ty.parameters return ptypes.Vector(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type
# -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ from numba2.lib import vectorobject from numba2.lib import arrayobject from numba2.runtime.obj import pointerobject if ty.impl == pointerobject.Pointer: (base,) = ty.parameters return ptypes.Pointer(representation_type(base)) if ty.impl == vectorobject.Vector: base, count = ty.parameters return ptypes.Vector(representation_type(base), count) if ty.impl == arrayobject.Array: base, count = ty.parameters return ptypes.Array(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type Remove some object representation clobbering code# -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ # NOTE: special cases should be kept to an absolute minimum here. They # should probably be introduced only if ctypes cannot represent the # type from numba2.lib import vectorobject if ty.impl == vectorobject.Vector: # Ctypes does not support vectors base, count = ty.parameters return ptypes.Vector(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type
<commit_before># -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ from numba2.lib import vectorobject from numba2.lib import arrayobject from numba2.runtime.obj import pointerobject if ty.impl == pointerobject.Pointer: (base,) = ty.parameters return ptypes.Pointer(representation_type(base)) if ty.impl == vectorobject.Vector: base, count = ty.parameters return ptypes.Vector(representation_type(base), count) if ty.impl == arrayobject.Array: base, count = ty.parameters return ptypes.Array(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type <commit_msg>Remove some object representation clobbering code<commit_after># -*- coding: utf-8 -*- """ Object layout. """ from __future__ import print_function, division, absolute_import from numba2 import conversion from pykit import types as ptypes from pykit.utils import ctypes_support #===------------------------------------------------------------------=== # Types #===------------------------------------------------------------------=== def representation_type(ty): """ Get the low-level representation type for a high-level (user-defined) type. Returns ======= The pykit type for the object layout. """ # NOTE: special cases should be kept to an absolute minimum here. They # should probably be introduced only if ctypes cannot represent the # type from numba2.lib import vectorobject if ty.impl == vectorobject.Vector: # Ctypes does not support vectors base, count = ty.parameters return ptypes.Vector(representation_type(base), count) cty = conversion.ctype(ty) result_type = ctypes_support.from_ctypes_type(cty) if result_type.is_struct: result_type = ptypes.Pointer(result_type) return result_type
df25af8c12f824ee46a7bbf676f9adfcef5b1624
grazer/run.py
grazer/run.py
import click from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") def main(env, config): load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
import click import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") @click.option("--log_level", default="INFO") def main(env, config, log_level): logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
Allow to config log level
Allow to config log level
Python
mit
CodersOfTheNight/verata
import click from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") def main(env, config): load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main() Allow to config log level
import click import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") @click.option("--log_level", default="INFO") def main(env, config, log_level): logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
<commit_before>import click from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") def main(env, config): load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main() <commit_msg>Allow to config log level<commit_after>
import click import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") @click.option("--log_level", default="INFO") def main(env, config, log_level): logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
import click from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") def main(env, config): load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main() Allow to config log levelimport click import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") @click.option("--log_level", default="INFO") def main(env, config, log_level): logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
<commit_before>import click from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") def main(env, config): load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main() <commit_msg>Allow to config log level<commit_after>import click import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") @click.option("--log_level", default="INFO") def main(env, config, log_level): logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
86cbea3478837ca2c1804f2068b497ee957e6f95
pyvista/_version.py
pyvista/_version.py
""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 1 # Nice string for the version __version__ = '.'.join(map(str, version_info))
""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 2 # Nice string for the version __version__ = '.'.join(map(str, version_info))
Bump version: 0.21.1 → 0.21.2
Bump version: 0.21.1 → 0.21.2
Python
mit
akaszynski/vtkInterface
""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 1 # Nice string for the version __version__ = '.'.join(map(str, version_info)) Bump version: 0.21.1 → 0.21.2
""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 2 # Nice string for the version __version__ = '.'.join(map(str, version_info))
<commit_before>""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 1 # Nice string for the version __version__ = '.'.join(map(str, version_info)) <commit_msg>Bump version: 0.21.1 → 0.21.2<commit_after>
""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 2 # Nice string for the version __version__ = '.'.join(map(str, version_info))
""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 1 # Nice string for the version __version__ = '.'.join(map(str, version_info)) Bump version: 0.21.1 → 0.21.2""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 2 # Nice string for the version __version__ = '.'.join(map(str, version_info))
<commit_before>""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 1 # Nice string for the version __version__ = '.'.join(map(str, version_info)) <commit_msg>Bump version: 0.21.1 → 0.21.2<commit_after>""" version info for pyvista """ # major, minor, patch version_info = 0, 21, 2 # Nice string for the version __version__ = '.'.join(map(str, version_info))
b5fa5ed84b8427d052c0e1f494384e9fd06bfe6a
onadata/libs/mixins/mfa.py
onadata/libs/mixins/mfa.py
# coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for ' 'this account. {verbose_name} cannot be used.' ).format(verbose_name=self.verbose_name))
# coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for this ' 'account. ##authentication class## cannot be used.' ).replace('##authentication class##', self.verbose_name))
Use new translated string placeholder style
Use new translated string placeholder style
Python
bsd-2-clause
kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat
# coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for ' 'this account. {verbose_name} cannot be used.' ).format(verbose_name=self.verbose_name)) Use new translated string placeholder style
# coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for this ' 'account. ##authentication class## cannot be used.' ).replace('##authentication class##', self.verbose_name))
<commit_before># coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for ' 'this account. {verbose_name} cannot be used.' ).format(verbose_name=self.verbose_name)) <commit_msg>Use new translated string placeholder style<commit_after>
# coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for this ' 'account. ##authentication class## cannot be used.' ).replace('##authentication class##', self.verbose_name))
# coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for ' 'this account. {verbose_name} cannot be used.' ).format(verbose_name=self.verbose_name)) Use new translated string placeholder style# coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for this ' 'account. ##authentication class## cannot be used.' ).replace('##authentication class##', self.verbose_name))
<commit_before># coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for ' 'this account. {verbose_name} cannot be used.' ).format(verbose_name=self.verbose_name)) <commit_msg>Use new translated string placeholder style<commit_after># coding: utf-8 from django.conf import settings from django.utils.translation import gettext as _ from rest_framework import exceptions from onadata.apps.main.models.user_profile import UserProfile class MFABlockerMixin: def validate_mfa_not_active(self, user: 'auth.User'): """ Raise an exception if MFA is enabled for user's account. """ # This condition is kind of temporary. We can activate/deactivate # class based on settings. Useful until we decide whether # TokenAuthentication should be deactivated with MFA # ToDo Remove the condition when kobotoolbox/kpi#3383 is released/merged class_path = f'{self.__module__}.{self.__class__.__name__}' if class_path not in settings.MFA_SUPPORTED_AUTH_CLASSES: try: is_mfa_active = user.profile.is_mfa_active except UserProfile.DoesNotExist: pass else: if is_mfa_active: raise exceptions.AuthenticationFailed(_( 'Multi-factor authentication is enabled for this ' 'account. ##authentication class## cannot be used.' ).replace('##authentication class##', self.verbose_name))
c6071093c35c2a83a683fe55788946ae99b38256
contacts/api.py
contacts/api.py
""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _card = None def __init__(self): self._card = vobject.vCard()
""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject from .exceptions import ContactCreationException from .rules import ALLOWED_FIELDS class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _allowed_fields = ALLOWED_FIELDS + ['_card', '_card_field'] _card = None def __init__(self, **kwargs): self._card = vobject.vCard() # all those keys will be initialized as class attributes allowed_keys = set(ALLOWED_FIELDS) # initialize all allowed keys to false self.__dict__.update((key, False) for key in allowed_keys) # and update the given keys by their given values self.__dict__.update((key, value) for key, value in kwargs.items() if key in allowed_keys) if not self.name: raise ContactCreationException( "A Contact Card must have a name associated with it." ) def __setattr__(self, attribute, value): if not attribute in set(self._allowed_fields): print("{0} is not a valid attribute of a Contact Card.\nValid attributes are: {1}".format( attribute, ALLOWED_FIELDS )) else: self.__dict__[attribute] = value
Update CC Object to limit fields, use custom exception and rules
Update CC Object to limit fields, use custom exception and rules
Python
mit
heimann/contacts
""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _card = None def __init__(self): self._card = vobject.vCard() Update CC Object to limit fields, use custom exception and rules
""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject from .exceptions import ContactCreationException from .rules import ALLOWED_FIELDS class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _allowed_fields = ALLOWED_FIELDS + ['_card', '_card_field'] _card = None def __init__(self, **kwargs): self._card = vobject.vCard() # all those keys will be initialized as class attributes allowed_keys = set(ALLOWED_FIELDS) # initialize all allowed keys to false self.__dict__.update((key, False) for key in allowed_keys) # and update the given keys by their given values self.__dict__.update((key, value) for key, value in kwargs.items() if key in allowed_keys) if not self.name: raise ContactCreationException( "A Contact Card must have a name associated with it." ) def __setattr__(self, attribute, value): if not attribute in set(self._allowed_fields): print("{0} is not a valid attribute of a Contact Card.\nValid attributes are: {1}".format( attribute, ALLOWED_FIELDS )) else: self.__dict__[attribute] = value
<commit_before>""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _card = None def __init__(self): self._card = vobject.vCard() <commit_msg>Update CC Object to limit fields, use custom exception and rules<commit_after>
""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject from .exceptions import ContactCreationException from .rules import ALLOWED_FIELDS class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _allowed_fields = ALLOWED_FIELDS + ['_card', '_card_field'] _card = None def __init__(self, **kwargs): self._card = vobject.vCard() # all those keys will be initialized as class attributes allowed_keys = set(ALLOWED_FIELDS) # initialize all allowed keys to false self.__dict__.update((key, False) for key in allowed_keys) # and update the given keys by their given values self.__dict__.update((key, value) for key, value in kwargs.items() if key in allowed_keys) if not self.name: raise ContactCreationException( "A Contact Card must have a name associated with it." ) def __setattr__(self, attribute, value): if not attribute in set(self._allowed_fields): print("{0} is not a valid attribute of a Contact Card.\nValid attributes are: {1}".format( attribute, ALLOWED_FIELDS )) else: self.__dict__[attribute] = value
""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _card = None def __init__(self): self._card = vobject.vCard() Update CC Object to limit fields, use custom exception and rules""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject from .exceptions import ContactCreationException from .rules import ALLOWED_FIELDS class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _allowed_fields = ALLOWED_FIELDS + ['_card', '_card_field'] _card = None def __init__(self, **kwargs): self._card = vobject.vCard() # all those keys will be initialized as class attributes allowed_keys = set(ALLOWED_FIELDS) # initialize all allowed keys to false self.__dict__.update((key, False) for key in allowed_keys) # and update the given keys by their given values self.__dict__.update((key, value) for key, value in kwargs.items() if key in allowed_keys) if not self.name: raise ContactCreationException( "A Contact Card must have a name associated with it." ) def __setattr__(self, attribute, value): if not attribute in set(self._allowed_fields): print("{0} is not a valid attribute of a Contact Card.\nValid attributes are: {1}".format( attribute, ALLOWED_FIELDS )) else: self.__dict__[attribute] = value
<commit_before>""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _card = None def __init__(self): self._card = vobject.vCard() <commit_msg>Update CC Object to limit fields, use custom exception and rules<commit_after>""" contacts.api ~~~~~~~~~~~~ This module implements the Contacts 📕 API. :copyright: (c) 2017 by David Heimann. :license: MIT, see LICENSE for more details. """ import vobject from .exceptions import ContactCreationException from .rules import ALLOWED_FIELDS class ContactCard(object): """ A :class:`Contact Card <ContactCard>` object. :param name: Full Name (required). :param first_name: First Name. :param last_name: Last Name. :param photo: fileobject of photo. :param email: E-Mail address. :param website: URL. :param twitter: Twitter Username (ex: @david_heimann) """ _allowed_fields = ALLOWED_FIELDS + ['_card', '_card_field'] _card = None def __init__(self, **kwargs): self._card = vobject.vCard() # all those keys will be initialized as class attributes allowed_keys = set(ALLOWED_FIELDS) # initialize all allowed keys to false self.__dict__.update((key, False) for key in allowed_keys) # and update the given keys by their given values self.__dict__.update((key, value) for key, value in kwargs.items() if key in allowed_keys) if not self.name: raise ContactCreationException( "A Contact Card must have a name associated with it." ) def __setattr__(self, attribute, value): if not attribute in set(self._allowed_fields): print("{0} is not a valid attribute of a Contact Card.\nValid attributes are: {1}".format( attribute, ALLOWED_FIELDS )) else: self.__dict__[attribute] = value
e00140c1488fd17f44932dee3eb320e2ae697b90
tests/list_match.py
tests/list_match.py
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil()))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0
Fix actual type error in test code
Fix actual type error in test code
Python
mit
pshc/archipelago,pshc/archipelago,pshc/archipelago
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0 Fix actual type error in test code
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil()))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0
<commit_before>from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0 <commit_msg>Fix actual type error in test code<commit_after>
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil()))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0 Fix actual type error in test codefrom bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil()))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0
<commit_before>from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0 <commit_msg>Fix actual type error in test code<commit_after>from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil()))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0
f76015fdf37db44a54ce0e0038b4b85978c39839
tests/test_utils.py
tests/test_utils.py
# -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
# -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting along with the code formatter. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
Add import statements breaking linter
Add import statements breaking linter
Python
apache-2.0
BastiTee/bastis-python-toolbox
# -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5 Add import statements breaking linter
# -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting along with the code formatter. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
<commit_before># -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5 <commit_msg>Add import statements breaking linter<commit_after>
# -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting along with the code formatter. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
# -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5 Add import statements breaking linter# -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting along with the code formatter. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
<commit_before># -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5 <commit_msg>Add import statements breaking linter<commit_after># -*- coding: utf-8 -*- """Basic test suite. There are some 'noqa: F401' in this file to just test the isort import sorting along with the code formatter. """ import __future__ # noqa: F401 import json # noqa: F401 from os import path # noqa: F401 from re import IGNORECASE, sub # noqa: F401 import click # noqa: F401 import my_module # noqa: F401 from my_module.utils import add_two_numbers import pytest import requests # noqa: F401 class TestUtils: # noqa: D101 @pytest.mark.parametrize('number_left, number_right', [ (None, 1), (1, None), (None, None) ]) def test_add_two_numbers_no_input(self, number_left, number_right): """Basic input validation.""" with pytest.raises(ValueError): add_two_numbers(number_left, number_right) def test_add_two_numbers_regular_input(self): """Basic asserting test.""" assert add_two_numbers(2, 3) == 5
6c9640cf0e9e8e187a61fc81f6c0eed0988601e1
apps/accounts/views.py
apps/accounts/views.py
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): model = UserProfile class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): queryset = UserProfile.objects.all().select_related('user') class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass
Make sure the 'user' object is available in the UserProfile queryset in the view.
Make sure the 'user' object is available in the UserProfile queryset in the view.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): model = UserProfile class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass Make sure the 'user' object is available in the UserProfile queryset in the view.
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): queryset = UserProfile.objects.all().select_related('user') class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass
<commit_before>from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): model = UserProfile class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass <commit_msg>Make sure the 'user' object is available in the UserProfile queryset in the view.<commit_after>
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): queryset = UserProfile.objects.all().select_related('user') class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): model = UserProfile class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass Make sure the 'user' object is available in the UserProfile queryset in the view.from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): queryset = UserProfile.objects.all().select_related('user') class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass
<commit_before>from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): model = UserProfile class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass <commit_msg>Make sure the 'user' object is available in the UserProfile queryset in the view.<commit_after>from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import UserProfile class UserProfileBase(object): queryset = UserProfile.objects.all().select_related('user') class UserProfileList(UserProfileBase, ListView): pass class UserProfileDetail(UserProfileBase, DetailView): pass
62705d28c826a213a42de504c041d56d72bd64df
examples/sparkfun_redbot/sparkfun_experiments/Exp2_DriveForward.py
examples/sparkfun_redbot/sparkfun_experiments/Exp2_DriveForward.py
#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop()
#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): print("Left and right motors at full speed forward") motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds print("Stop both motors") motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop()
Add a log to Exp2
Add a log to Exp2
Python
agpl-3.0
MrYsLab/pymata-aio
#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop() Add a log to Exp2
#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): print("Left and right motors at full speed forward") motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds print("Stop both motors") motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop()
<commit_before>#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop() <commit_msg>Add a log to Exp2<commit_after>
#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): print("Left and right motors at full speed forward") motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds print("Stop both motors") motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop()
#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop() Add a log to Exp2#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): print("Left and right motors at full speed forward") motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds print("Stop both motors") motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop()
<commit_before>#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop() <commit_msg>Add a log to Exp2<commit_after>#!/usr/bin/python3.4 """ Exp2_DriveForward -- RedBot Experiment 2 Drive forward and stop. Hardware setup: The Power switch must be on, the motors must be connected, and the board must be receiving power from the battery. The motor switch must also be switched to RUN. """ from pymata_aio.pymata3 import PyMata3 from RedBot import RedBotMotors # This line "includes" the RedBot library into your sketch. # Provides special objects, methods, and functions for the RedBot. board = PyMata3() motors = RedBotMotors(board) # Instantiate the motor control object. This only needs to be done once. def setup(): print("Left and right motors at full speed forward") motors.drive(255) # Turn on Left and right motors at full speed forward. board.sleep(2.0) # Waits for 2 seconds print("Stop both motors") motors.stop() # Stops both motors def loop(): # Nothing here. We'll get to this in the next experiment. pass if __name__ == "__main__": setup() while True: loop()
b9c3404550273e4b0af68ebe9da27c4bf405de9b
rohrpost/message.py
rohrpost/message.py
import json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data content.update(**additional_data) if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data)
import json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data)
Remove superflous line, remove duplicate data
Remove superflous line, remove duplicate data
Python
mit
axsemantics/rohrpost,axsemantics/rohrpost
import json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data content.update(**additional_data) if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data) Remove superflous line, remove duplicate data
import json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data)
<commit_before>import json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data content.update(**additional_data) if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data) <commit_msg>Remove superflous line, remove duplicate data<commit_after>
import json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data)
import json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data content.update(**additional_data) if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data) Remove superflous line, remove duplicate dataimport json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data)
<commit_before>import json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data content.update(**additional_data) if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data) <commit_msg>Remove superflous line, remove duplicate data<commit_after>import json def _send_message(message, content: dict, close: bool): message.reply_channel.send({ 'text': json.dumps(content), 'close': close, }) def send_message(message, message_id, handler, close=False, error=None, **additional_data): content = dict() if message_id: content['id'] = message_id if handler: content['type'] = handler if error: content['error'] = error if additional_data: content['data'] = additional_data if not content: raise Exception('Cannot send an empty message.') _send_message(message, content, close=close) def send_success(message, message_id, handler, close=False, **additional_data): """ This method directly wraps send_message but checks the existence of id and type. """ if not message_id or not handler: raise Exception('You have to provide a message ID and handler on success messages.') send_message(message, message_id, handler, close=close, **additional_data) def send_error(message, message_id, handler, error, close=False, **additional_data): """ This method wraps send_message and makes sure that error is a keyword argument. """ send_message(message, message_id, handler, close=close, error=error, **additional_data)
6cb0a6f35f4722f5e0b5e9b7c2028bbb6f278402
operation.py
operation.py
""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job is the set of operations needed to fully build a radiator - order determines the relative order among a set of operations that belog to the same job """ class Operation: def __init__(self, machine, duration, job_model, job_id): self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Job#" + str(self.job_model) + " Machine#" + str(self.machine) + " Duration=" + str(self.duration)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation))
""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - name improves readability when printing - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job_model is the radiator model that this operation belongs to - job_id is the job to which this operation belongs - dependencies is a list containing the operations that this operation depends on """ class Operation: def __init__(self, name, machine, duration, job_model, job_id): self.name = name self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Name: " + str(name) + " Machine: " + str(self.machine) + " Duration: " + str(self.duration) + "Job model: " + str(self.job_model) + "Job ID: " + str(self.job_id)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation))
Update str() and add comments
Update str() and add comments
Python
mit
Irvel/JSSP-Genetic-Algorithm
""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job is the set of operations needed to fully build a radiator - order determines the relative order among a set of operations that belog to the same job """ class Operation: def __init__(self, machine, duration, job_model, job_id): self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Job#" + str(self.job_model) + " Machine#" + str(self.machine) + " Duration=" + str(self.duration)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation)) Update str() and add comments
""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - name improves readability when printing - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job_model is the radiator model that this operation belongs to - job_id is the job to which this operation belongs - dependencies is a list containing the operations that this operation depends on """ class Operation: def __init__(self, name, machine, duration, job_model, job_id): self.name = name self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Name: " + str(name) + " Machine: " + str(self.machine) + " Duration: " + str(self.duration) + "Job model: " + str(self.job_model) + "Job ID: " + str(self.job_id)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation))
<commit_before>""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job is the set of operations needed to fully build a radiator - order determines the relative order among a set of operations that belog to the same job """ class Operation: def __init__(self, machine, duration, job_model, job_id): self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Job#" + str(self.job_model) + " Machine#" + str(self.machine) + " Duration=" + str(self.duration)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation)) <commit_msg>Update str() and add comments<commit_after>
""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - name improves readability when printing - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job_model is the radiator model that this operation belongs to - job_id is the job to which this operation belongs - dependencies is a list containing the operations that this operation depends on """ class Operation: def __init__(self, name, machine, duration, job_model, job_id): self.name = name self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Name: " + str(name) + " Machine: " + str(self.machine) + " Duration: " + str(self.duration) + "Job model: " + str(self.job_model) + "Job ID: " + str(self.job_id)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation))
""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job is the set of operations needed to fully build a radiator - order determines the relative order among a set of operations that belog to the same job """ class Operation: def __init__(self, machine, duration, job_model, job_id): self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Job#" + str(self.job_model) + " Machine#" + str(self.machine) + " Duration=" + str(self.duration)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation)) Update str() and add comments""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - name improves readability when printing - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job_model is the radiator model that this operation belongs to - job_id is the job to which this operation belongs - dependencies is a list containing the operations that this operation depends on """ class Operation: def __init__(self, name, machine, duration, job_model, job_id): self.name = name self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Name: " + str(name) + " Machine: " + str(self.machine) + " Duration: " + str(self.duration) + "Job model: " + str(self.job_model) + "Job ID: " + str(self.job_id)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation))
<commit_before>""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job is the set of operations needed to fully build a radiator - order determines the relative order among a set of operations that belog to the same job """ class Operation: def __init__(self, machine, duration, job_model, job_id): self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Job#" + str(self.job_model) + " Machine#" + str(self.machine) + " Duration=" + str(self.duration)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation)) <commit_msg>Update str() and add comments<commit_after>""" operation.py ~~~~~~~~~~~~~ This stores the information of each individual operation in the production line. - name improves readability when printing - machine is the machine in which that operation will be executed - duration is the amount of time in which the operation will be completed - job_model is the radiator model that this operation belongs to - job_id is the job to which this operation belongs - dependencies is a list containing the operations that this operation depends on """ class Operation: def __init__(self, name, machine, duration, job_model, job_id): self.name = name self.machine = machine self.duration = duration self.job_model = job_model self.job_id = job_id self.dependencies = [] def __str__(self): return ("Name: " + str(name) + " Machine: " + str(self.machine) + " Duration: " + str(self.duration) + "Job model: " + str(self.job_model) + "Job ID: " + str(self.job_id)) def print_dependencies(self): if len(self.dependencies) > 0: print(str(self) + " depends on ") for operation in self.dependencies: print(str(operation))
6df115b41d18f7e74a0220550a04459d83d391d0
pox/lib/packet/__init__.py
pox/lib/packet/__init__.py
""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', ]
""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. import arp as ARP import dhcp as DHCP import dns as DNS import eap as EAP import eapol as EAPOL import ethernet as ETHERNET import icmp as ICMP import ipv4 as IPV4 import lldp as LLDP import tcp as TCP import udp as UDP import vlan as VLAN from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', 'ARP', 'DHCP', 'DNS', 'EAP', 'EAPOL', 'ETHERNET', 'ICMP', 'IPV4', 'LLDP', 'TCP', 'UDP', 'VLAN', ]
Add all submodules to import *
packet: Add all submodules to import * You can now access pox.lib.packet.icmp as pox.lib.packet.ICMP if you import the whole package (e.g., import pox.lib.packet as pkg). --HG-- extra : rebase_source : b48d05949977468a669bdd55caab7ac898689441
Python
apache-2.0
adusia/pox,diogommartins/pox,waltznetworks/pox,VamsikrishnaNallabothu/pox,PrincetonUniversity/pox,kulawczukmarcin/mypox,MurphyMc/pox,noxrepo/pox,carlye566/IoT-POX,kpengboy/pox-exercise,noxrepo/pox,chenyuntc/pox,denovogroup/pox,andiwundsam/_of_normalize,jacobq/csci5221-viro-project,carlye566/IoT-POX,kulawczukmarcin/mypox,waltznetworks/pox,kavitshah8/SDNDeveloper,kpengboy/pox-exercise,MurphyMc/pox,VamsikrishnaNallabothu/pox,xAKLx/pox,adusia/pox,PrincetonUniversity/pox,pthien92/sdn,carlye566/IoT-POX,diogommartins/pox,chenyuntc/pox,waltznetworks/pox,adusia/pox,xAKLx/pox,PrincetonUniversity/pox,kulawczukmarcin/mypox,waltznetworks/pox,pthien92/sdn,noxrepo/pox,MurphyMc/pox,diogommartins/pox,kavitshah8/SDNDeveloper,denovogroup/pox,MurphyMc/pox,chenyuntc/pox,adusia/pox,chenyuntc/pox,VamsikrishnaNallabothu/pox,andiwundsam/_of_normalize,PrincetonUniversity/pox,xAKLx/pox,pthien92/sdn,andiwundsam/_of_normalize,diogommartins/pox,denovogroup/pox,carlye566/IoT-POX,denovogroup/pox,kulawczukmarcin/mypox,PrincetonUniversity/pox,waltznetworks/pox,jacobq/csci5221-viro-project,pthien92/sdn,kpengboy/pox-exercise,chenyuntc/pox,adusia/pox,noxrepo/pox,kavitshah8/SDNDeveloper,denovogroup/pox,xAKLx/pox,pthien92/sdn,MurphyMc/pox,carlye566/IoT-POX,kulawczukmarcin/mypox,andiwundsam/_of_normalize,jacobq/csci5221-viro-project,kpengboy/pox-exercise,diogommartins/pox,kpengboy/pox-exercise,VamsikrishnaNallabothu/pox,VamsikrishnaNallabothu/pox,kavitshah8/SDNDeveloper,xAKLx/pox,jacobq/csci5221-viro-project,jacobq/csci5221-viro-project
""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', ] packet: Add all submodules to import * You can now access pox.lib.packet.icmp as pox.lib.packet.ICMP if you import the whole package (e.g., import pox.lib.packet as pkg). --HG-- extra : rebase_source : b48d05949977468a669bdd55caab7ac898689441
""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. import arp as ARP import dhcp as DHCP import dns as DNS import eap as EAP import eapol as EAPOL import ethernet as ETHERNET import icmp as ICMP import ipv4 as IPV4 import lldp as LLDP import tcp as TCP import udp as UDP import vlan as VLAN from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', 'ARP', 'DHCP', 'DNS', 'EAP', 'EAPOL', 'ETHERNET', 'ICMP', 'IPV4', 'LLDP', 'TCP', 'UDP', 'VLAN', ]
<commit_before>""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', ] <commit_msg>packet: Add all submodules to import * You can now access pox.lib.packet.icmp as pox.lib.packet.ICMP if you import the whole package (e.g., import pox.lib.packet as pkg). --HG-- extra : rebase_source : b48d05949977468a669bdd55caab7ac898689441<commit_after>
""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. import arp as ARP import dhcp as DHCP import dns as DNS import eap as EAP import eapol as EAPOL import ethernet as ETHERNET import icmp as ICMP import ipv4 as IPV4 import lldp as LLDP import tcp as TCP import udp as UDP import vlan as VLAN from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', 'ARP', 'DHCP', 'DNS', 'EAP', 'EAPOL', 'ETHERNET', 'ICMP', 'IPV4', 'LLDP', 'TCP', 'UDP', 'VLAN', ]
""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', ] packet: Add all submodules to import * You can now access pox.lib.packet.icmp as pox.lib.packet.ICMP if you import the whole package (e.g., import pox.lib.packet as pkg). --HG-- extra : rebase_source : b48d05949977468a669bdd55caab7ac898689441""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. import arp as ARP import dhcp as DHCP import dns as DNS import eap as EAP import eapol as EAPOL import ethernet as ETHERNET import icmp as ICMP import ipv4 as IPV4 import lldp as LLDP import tcp as TCP import udp as UDP import vlan as VLAN from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', 'ARP', 'DHCP', 'DNS', 'EAP', 'EAPOL', 'ETHERNET', 'ICMP', 'IPV4', 'LLDP', 'TCP', 'UDP', 'VLAN', ]
<commit_before>""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', ] <commit_msg>packet: Add all submodules to import * You can now access pox.lib.packet.icmp as pox.lib.packet.ICMP if you import the whole package (e.g., import pox.lib.packet as pkg). --HG-- extra : rebase_source : b48d05949977468a669bdd55caab7ac898689441<commit_after>""" The POX packet library for packet parsing and creation. This is based heavily on NOX's packet library, though it has undergone some signficant change, particularly with regard to making packet assembly easier. Could still use more work. """ # None of this is probably that big, and almost all of it gets loaded # under most circumstances anyway. Let's just load all of it. import arp as ARP import dhcp as DHCP import dns as DNS import eap as EAP import eapol as EAPOL import ethernet as ETHERNET import icmp as ICMP import ipv4 as IPV4 import lldp as LLDP import tcp as TCP import udp as UDP import vlan as VLAN from arp import * from dhcp import * from dns import * from eap import * from eapol import * from ethernet import * from icmp import * from ipv4 import * from lldp import * from tcp import * from udp import * from vlan import * __all__ = [ 'arp', 'dhcp', 'dns', 'eap', 'eapol', 'ethernet', 'icmp', 'ipv4', 'lldp', 'tcp', 'tcp_opt', 'udp', 'vlan', 'ARP', 'DHCP', 'DNS', 'EAP', 'EAPOL', 'ETHERNET', 'ICMP', 'IPV4', 'LLDP', 'TCP', 'UDP', 'VLAN', ]
1f40edb5c567d85c621339a28d2b20c8f5406460
jacquard/service/commands.py
jacquard/service/commands.py
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(object): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
Make this derive from the correct type
Make this derive from the correct type
Python
mit
prophile/jacquard,prophile/jacquard
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(object): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, ) Make this derive from the correct type
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
<commit_before>import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(object): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, ) <commit_msg>Make this derive from the correct type<commit_after>
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(object): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, ) Make this derive from the correct typeimport werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
<commit_before>import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(object): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, ) <commit_msg>Make this derive from the correct type<commit_after>import werkzeug.debug import werkzeug.serving from jacquard.commands import BaseCommand from jacquard.service import get_wsgi_app class RunServer(BaseCommand): help = "run a (local, debug) server" def add_arguments(self, parser): parser.add_argument( '-p', '--port', type=int, default=8888, help="port to bind to", ) parser.add_argument( '-b', '--bind', type=str, default='::1', help="address to bind to", ) def handle(self, config, options): app = get_wsgi_app(config) werkzeug.serving.run_simple( options.bind, options.port, app, use_reloader=True, use_debugger=True, use_evalex=True, threaded=False, processes=1, )
29a1c8f4eab13b5b17fffbd18a720b0ae5ab04b3
handoverservice/mail_draft/tests_ddsutil.py
handoverservice/mail_draft/tests_ddsutil.py
from django.test import TestCase from handover_api.models import User import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called)
from django.test import TestCase from handover_api.models import User from django.core.exceptions import ObjectDoesNotExist import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called) def testFailsWithoutAPIKeyUser(self): with self.settings(DDSCLIENT_PROPERTIES={}): self.assertEqual(len(User.objects.all()), 0) with self.assertRaises(ObjectDoesNotExist): ddsutil = DDSUtil('abcd-efgh-1234-5678') ddsutil.remote_store
Add test for user does not exist
Add test for user does not exist
Python
mit
Duke-GCB/DukeDSHandoverService,Duke-GCB/DukeDSHandoverService,Duke-GCB/DukeDSHandoverService
from django.test import TestCase from handover_api.models import User import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called) Add test for user does not exist
from django.test import TestCase from handover_api.models import User from django.core.exceptions import ObjectDoesNotExist import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called) def testFailsWithoutAPIKeyUser(self): with self.settings(DDSCLIENT_PROPERTIES={}): self.assertEqual(len(User.objects.all()), 0) with self.assertRaises(ObjectDoesNotExist): ddsutil = DDSUtil('abcd-efgh-1234-5678') ddsutil.remote_store
<commit_before>from django.test import TestCase from handover_api.models import User import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called) <commit_msg>Add test for user does not exist<commit_after>
from django.test import TestCase from handover_api.models import User from django.core.exceptions import ObjectDoesNotExist import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called) def testFailsWithoutAPIKeyUser(self): with self.settings(DDSCLIENT_PROPERTIES={}): self.assertEqual(len(User.objects.all()), 0) with self.assertRaises(ObjectDoesNotExist): ddsutil = DDSUtil('abcd-efgh-1234-5678') ddsutil.remote_store
from django.test import TestCase from handover_api.models import User import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called) Add test for user does not existfrom django.test import TestCase from handover_api.models import User from django.core.exceptions import ObjectDoesNotExist import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called) def testFailsWithoutAPIKeyUser(self): with self.settings(DDSCLIENT_PROPERTIES={}): self.assertEqual(len(User.objects.all()), 0) with self.assertRaises(ObjectDoesNotExist): ddsutil = DDSUtil('abcd-efgh-1234-5678') ddsutil.remote_store
<commit_before>from django.test import TestCase from handover_api.models import User import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called) <commit_msg>Add test for user does not exist<commit_after>from django.test import TestCase from handover_api.models import User from django.core.exceptions import ObjectDoesNotExist import mock import mail_draft from mail_draft.dds_util import DDSUtil class DDSUtilTestCase(TestCase): @mock.patch('ddsc.core.remotestore.RemoteStore') def testGetEmail(self, mockRemoteStore): user_id = 'abcd-1234-efgh-8876' email = 'example@domain.com' # Mock a remote user object, and bind it to fetch_user remote_user = mock.Mock() remote_user.email = email instance = mockRemoteStore.return_value instance.fetch_user.return_value = remote_user # Only import DDSUtil once we've patched RemoteStore try: reload(mail_draft.dds_util) except NameError: # Python 3 import importlib importlib.reload(mail_draft.dds_util) User.objects.create(dds_id=user_id, api_key='uhn3wk7h24ighg8i2') # DDSUtil reads settings from django settings, so inject some here with self.settings(DDSCLIENT_PROPERTIES={}): ddsutil = DDSUtil(user_id) self.assertEqual(email, ddsutil.get_email_address(user_id)) self.assertTrue(instance.fetch_user.called) def testFailsWithoutAPIKeyUser(self): with self.settings(DDSCLIENT_PROPERTIES={}): self.assertEqual(len(User.objects.all()), 0) with self.assertRaises(ObjectDoesNotExist): ddsutil = DDSUtil('abcd-efgh-1234-5678') ddsutil.remote_store
60bf4d1457059b3cd53e5b37eab6d428ff4df511
src/artgraph/plugins/infobox.py
src/artgraph/plugins/infobox.py
from artgraph.plugins.plugin import Plugin from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
from artgraph.plugins.plugin import Plugin class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
Fix imports to be able to import properly from the worker nodes
Fix imports to be able to import properly from the worker nodes
Python
mit
dMaggot/ArtistGraph
from artgraph.plugins.plugin import Plugin from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships Fix imports to be able to import properly from the worker nodes
from artgraph.plugins.plugin import Plugin class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
<commit_before>from artgraph.plugins.plugin import Plugin from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships <commit_msg>Fix imports to be able to import properly from the worker nodes<commit_after>
from artgraph.plugins.plugin import Plugin class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
from artgraph.plugins.plugin import Plugin from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships Fix imports to be able to import properly from the worker nodesfrom artgraph.plugins.plugin import Plugin class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
<commit_before>from artgraph.plugins.plugin import Plugin from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships <commit_msg>Fix imports to be able to import properly from the worker nodes<commit_after>from artgraph.plugins.plugin import Plugin class InfoboxPlugin(Plugin): def __init__(self, node): self._node = node def get_nodes(self): from artgraph.node import Node, NodeTypes from artgraph.relationship import AssociatedActRelationship wikicode = self.get_wikicode(self._node.get_title()) templates = wikicode.filter_templates() relationships = [] for t in templates: if t.name.matches('Infobox musical artist'): associated_acts = t.get('associated_acts') for w in associated_acts.value.filter_wikilinks(): relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST))) return relationships
b2f51817d2182e3074cb679ead963e4a07514a54
importer/management/commands/import_list.py
importer/management/commands/import_list.py
import logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects()
import logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data.data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects()
Fix invalid access to CachedObject
Fix invalid access to CachedObject
Python
mit
meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent,meine-stadt-transparent/meine-stadt-transparent
import logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects() Fix invalid access to CachedObject
import logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data.data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects()
<commit_before>import logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects() <commit_msg>Fix invalid access to CachedObject<commit_after>
import logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data.data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects()
import logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects() Fix invalid access to CachedObjectimport logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data.data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects()
<commit_before>import logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects() <commit_msg>Fix invalid access to CachedObject<commit_after>import logging from importer.management.commands._import_base_command import ImportBaseCommand from importer.models import ExternalList, CachedObject logger = logging.getLogger(__name__) class Command(ImportBaseCommand): help = "Import the objects from an external list of an oparl body" def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "list", choices=["paper", "person", "organization", "meeting"] ) def handle(self, *args, **options): importer, body = self.get_importer(options) body_data = CachedObject.objects.get(url=body.oparl_id) oparl_id = body_data.data[options["list"]] if ExternalList.objects.filter(url=oparl_id).exists(): importer.fetch_list_update(oparl_id) else: importer.fetch_list_initial(oparl_id) importer.import_objects()
c544c0d2b8356125d1a5465b44617aaaaeab0ea1
scrapy/utils/ftp.py
scrapy/utils/ftp.py
import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ ftp = FTP() ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file) ftp.quit()
import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ with FTP() as ftp: ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file)
Use context management with `FTP`
Use context management with `FTP`
Python
bsd-3-clause
eLRuLL/scrapy,scrapy/scrapy,dangra/scrapy,elacuesta/scrapy,pablohoffman/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,eLRuLL/scrapy,starrify/scrapy,pawelmhm/scrapy,elacuesta/scrapy,scrapy/scrapy,elacuesta/scrapy,starrify/scrapy,scrapy/scrapy,dangra/scrapy,starrify/scrapy,pablohoffman/scrapy,pawelmhm/scrapy,eLRuLL/scrapy,dangra/scrapy
import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ ftp = FTP() ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file) ftp.quit() Use context management with `FTP`
import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ with FTP() as ftp: ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file)
<commit_before>import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ ftp = FTP() ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file) ftp.quit() <commit_msg>Use context management with `FTP`<commit_after>
import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ with FTP() as ftp: ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file)
import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ ftp = FTP() ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file) ftp.quit() Use context management with `FTP`import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ with FTP() as ftp: ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file)
<commit_before>import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ ftp = FTP() ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file) ftp.quit() <commit_msg>Use context management with `FTP`<commit_after>import posixpath from ftplib import error_perm, FTP from posixpath import dirname def ftp_makedirs_cwd(ftp, path, first_call=True): """Set the current directory of the FTP connection given in the ``ftp`` argument (as a ftplib.FTP object), creating all parent directories if they don't exist. The ftplib.FTP object must be already connected and logged in. """ try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if first_call: ftp.cwd(path) def ftp_store_file( *, path, file, host, port, username, password, use_active_mode=False): """Opens a FTP connection with passed credentials,sets current directory to the directory extracted from given path, then uploads the file to server """ with FTP() as ftp: ftp.connect(host, port) ftp.login(username, password) if use_active_mode: ftp.set_pasv(False) file.seek(0) dirname, filename = posixpath.split(path) ftp_makedirs_cwd(ftp, dirname) ftp.storbinary('STOR %s' % filename, file)
3483933b7e5709ef79a3f632bae09d24b22f4a44
pygp/likelihoods/__base.py
pygp/likelihoods/__base.py
""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False)
""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import numpy as np import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False)
Fix bug in RealLikelihood due to not importing numpy.
Fix bug in RealLikelihood due to not importing numpy.
Python
bsd-2-clause
mwhoffman/pygp
""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False) Fix bug in RealLikelihood due to not importing numpy.
""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import numpy as np import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False)
<commit_before>""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False) <commit_msg>Fix bug in RealLikelihood due to not importing numpy.<commit_after>
""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import numpy as np import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False)
""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False) Fix bug in RealLikelihood due to not importing numpy.""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import numpy as np import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False)
<commit_before>""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False) <commit_msg>Fix bug in RealLikelihood due to not importing numpy.<commit_after>""" Implementation of the squared-exponential kernels. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import numpy as np import abc # local imports from ..utils.models import Parameterized # exported symbols __all__ = ['Likelihood', 'RealLikelihood'] class Likelihood(Parameterized): """ Likelihood interface. """ @abc.abstractmethod def transform(self, y): pass class RealLikelihood(Likelihood): def transform(self, y): return np.array(y, ndmin=1, dtype=float, copy=False)
e164a50432f4f133e07d864a1923852754924f34
byceps/services/authentication/service.py
byceps/services/authentication/service.py
""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() return user
""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() return user
Check for account activity before password verification
Check for account activity before password verification
Python
bsd-3-clause
m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() return user Check for account activity before password verification
""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() return user
<commit_before>""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() return user <commit_msg>Check for account activity before password verification<commit_after>
""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() return user
""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() return user Check for account activity before password verification""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() return user
<commit_before>""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() return user <commit_msg>Check for account activity before password verification<commit_after>""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() return user
cc0fe75312fe5eb7cdfbb56942632a66730c71d6
src/opencmiss/neon/settings/mainsettings.py
src/opencmiss/neon/settings/mainsettings.py
''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 3 VERSION_MINOR = 9 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 0 VERSION_MINOR = 1 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
Reset Neon version to 0.1.0
Reset Neon version to 0.1.0
Python
apache-2.0
alan-wu/neon
''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 3 VERSION_MINOR = 9 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat) Reset Neon version to 0.1.0
''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 0 VERSION_MINOR = 1 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
<commit_before>''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 3 VERSION_MINOR = 9 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat) <commit_msg>Reset Neon version to 0.1.0<commit_after>
''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 0 VERSION_MINOR = 1 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 3 VERSION_MINOR = 9 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat) Reset Neon version to 0.1.0''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 0 VERSION_MINOR = 1 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
<commit_before>''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 3 VERSION_MINOR = 9 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat) <commit_msg>Reset Neon version to 0.1.0<commit_after>''' Copyright 2015 University of Auckland Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from PySide import QtCore VERSION_MAJOR = 0 VERSION_MINOR = 1 VERSION_PATCH = 0 VERSION_STRING = str(VERSION_MAJOR) + "." + str(VERSION_MINOR) + "." + str(VERSION_PATCH) APPLICATION_NAME = 'Neon' ORGANISATION_NAME = 'OpenCMISS' ORGANISATION_DOMAIN = 'opencmiss.org' def setApplicationSettings(app): app.setOrganizationDomain(ORGANISATION_DOMAIN) app.setOrganizationName(ORGANISATION_NAME) app.setApplicationName(APPLICATION_NAME) app.setApplicationVersion(VERSION_STRING) QtCore.QSettings.setDefaultFormat(QtCore.QSettings.IniFormat)
c5fb6fc400e19cdeac3b2cf21ec94893b1c2e92d
srw/plotting.py
srw/plotting.py
import matplotlib.pyplot as plt def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour)
import matplotlib.pyplot as plt from astropy import units as u from .logs import get_logger logger = get_logger(__name__) try: import ds9 except ImportError: logger.warning('No ds9 package available. ' 'Related functions are not available') no_ds9 = True else: no_ds9 = False def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) def show_on_image(lc, filename, frame_index=0, radius=3 * u.pix): if no_ds9: raise NotImplementedError("Cannot find module ds9") d = ds9.ds9() d.set('file {0}'.format(filename)) x, y = lc.ccdx[frame_index], lc.ccdy[frame_index] d.set('region command {{circle {x} {y} {radius}}}'.format( x=x, y=y, radius=radius.to(u.pix).value)) d.set('zoom to 8')
Add show on image function
Add show on image function
Python
mit
mindriot101/srw
import matplotlib.pyplot as plt def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) Add show on image function
import matplotlib.pyplot as plt from astropy import units as u from .logs import get_logger logger = get_logger(__name__) try: import ds9 except ImportError: logger.warning('No ds9 package available. ' 'Related functions are not available') no_ds9 = True else: no_ds9 = False def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) def show_on_image(lc, filename, frame_index=0, radius=3 * u.pix): if no_ds9: raise NotImplementedError("Cannot find module ds9") d = ds9.ds9() d.set('file {0}'.format(filename)) x, y = lc.ccdx[frame_index], lc.ccdy[frame_index] d.set('region command {{circle {x} {y} {radius}}}'.format( x=x, y=y, radius=radius.to(u.pix).value)) d.set('zoom to 8')
<commit_before>import matplotlib.pyplot as plt def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) <commit_msg>Add show on image function<commit_after>
import matplotlib.pyplot as plt from astropy import units as u from .logs import get_logger logger = get_logger(__name__) try: import ds9 except ImportError: logger.warning('No ds9 package available. ' 'Related functions are not available') no_ds9 = True else: no_ds9 = False def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) def show_on_image(lc, filename, frame_index=0, radius=3 * u.pix): if no_ds9: raise NotImplementedError("Cannot find module ds9") d = ds9.ds9() d.set('file {0}'.format(filename)) x, y = lc.ccdx[frame_index], lc.ccdy[frame_index] d.set('region command {{circle {x} {y} {radius}}}'.format( x=x, y=y, radius=radius.to(u.pix).value)) d.set('zoom to 8')
import matplotlib.pyplot as plt def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) Add show on image functionimport matplotlib.pyplot as plt from astropy import units as u from .logs import get_logger logger = get_logger(__name__) try: import ds9 except ImportError: logger.warning('No ds9 package available. ' 'Related functions are not available') no_ds9 = True else: no_ds9 = False def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) def show_on_image(lc, filename, frame_index=0, radius=3 * u.pix): if no_ds9: raise NotImplementedError("Cannot find module ds9") d = ds9.ds9() d.set('file {0}'.format(filename)) x, y = lc.ccdx[frame_index], lc.ccdy[frame_index] d.set('region command {{circle {x} {y} {radius}}}'.format( x=x, y=y, radius=radius.to(u.pix).value)) d.set('zoom to 8')
<commit_before>import matplotlib.pyplot as plt def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) <commit_msg>Add show on image function<commit_after>import matplotlib.pyplot as plt from astropy import units as u from .logs import get_logger logger = get_logger(__name__) try: import ds9 except ImportError: logger.warning('No ds9 package available. ' 'Related functions are not available') no_ds9 = True else: no_ds9 = False def plot_transiting(lc, period, epoch, ax=None, unit='mjd', colour=None): if unit.lower() == 'jd': epoch -= 2400000.5 lc.compute_phase(period, epoch) if ax is None: ax = plt.gca() phase = lc.phase.copy() phase[phase > 0.8] -= 1.0 ax.errorbar(phase, lc.flux, lc.fluxerr, ls='None', marker='None', capsize=0., alpha=0.3, color=colour) ax.plot(phase, lc.flux, '.', ms=2., color=colour) def show_on_image(lc, filename, frame_index=0, radius=3 * u.pix): if no_ds9: raise NotImplementedError("Cannot find module ds9") d = ds9.ds9() d.set('file {0}'.format(filename)) x, y = lc.ccdx[frame_index], lc.ccdy[frame_index] d.set('region command {{circle {x} {y} {radius}}}'.format( x=x, y=y, radius=radius.to(u.pix).value)) d.set('zoom to 8')