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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
65b71b6352f07a0ca9a2fdbbbb4f7156b59f59b7 | djangae/contrib/gauth_sql/backends.py | djangae/contrib/gauth_sql/backends.py | from djangae.contrib.gauth.common.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
| from djangae.contrib.gauth.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
| Fix bad import on gauth_sql | Fix bad import on gauth_sql
| Python | bsd-3-clause | grzes/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae,potatolondon/djangae | from djangae.contrib.gauth.common.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
Fix bad import on gauth_sql | from djangae.contrib.gauth.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
| <commit_before>from djangae.contrib.gauth.common.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
<commit_msg>Fix bad import on gauth_sql<commit_after> | from djangae.contrib.gauth.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
| from djangae.contrib.gauth.common.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
Fix bad import on gauth_sqlfrom djangae.contrib.gauth.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
| <commit_before>from djangae.contrib.gauth.common.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
<commit_msg>Fix bad import on gauth_sql<commit_after>from djangae.contrib.gauth.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
|
0701e34c76a4ea55b1334c9b48c88fd346f49fa2 | nazs/apps.py | nazs/apps.py | # -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import os
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from django.core import management
from django.conf import settings
from .sudo import set_euid
set_euid()
# Sync volatile db and set permissions
volatile_db = settings.DATABASES['volatile']['NAME']
management.call_command('syncdb',
database='volatile',
interactive=False,
verbosity=0)
os.chmod(volatile_db, 0600)
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
| # -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from .sudo import set_euid
set_euid()
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
| Stop auto creation of shm database | Stop auto creation of shm database
| Python | agpl-3.0 | exekias/droplet,exekias/droplet,exekias/droplet | # -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import os
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from django.core import management
from django.conf import settings
from .sudo import set_euid
set_euid()
# Sync volatile db and set permissions
volatile_db = settings.DATABASES['volatile']['NAME']
management.call_command('syncdb',
database='volatile',
interactive=False,
verbosity=0)
os.chmod(volatile_db, 0600)
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
Stop auto creation of shm database | # -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from .sudo import set_euid
set_euid()
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
| <commit_before># -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import os
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from django.core import management
from django.conf import settings
from .sudo import set_euid
set_euid()
# Sync volatile db and set permissions
volatile_db = settings.DATABASES['volatile']['NAME']
management.call_command('syncdb',
database='volatile',
interactive=False,
verbosity=0)
os.chmod(volatile_db, 0600)
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
<commit_msg>Stop auto creation of shm database<commit_after> | # -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from .sudo import set_euid
set_euid()
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
| # -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import os
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from django.core import management
from django.conf import settings
from .sudo import set_euid
set_euid()
# Sync volatile db and set permissions
volatile_db = settings.DATABASES['volatile']['NAME']
management.call_command('syncdb',
database='volatile',
interactive=False,
verbosity=0)
os.chmod(volatile_db, 0600)
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
Stop auto creation of shm database# -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from .sudo import set_euid
set_euid()
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
| <commit_before># -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import os
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from django.core import management
from django.conf import settings
from .sudo import set_euid
set_euid()
# Sync volatile db and set permissions
volatile_db = settings.DATABASES['volatile']['NAME']
management.call_command('syncdb',
database='volatile',
interactive=False,
verbosity=0)
os.chmod(volatile_db, 0600)
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
<commit_msg>Stop auto creation of shm database<commit_after># -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.apps import AppConfig
import pkg_resources
class NAZSConfig(AppConfig):
name = 'nazs'
def ready(self):
from .sudo import set_euid
set_euid()
# Load all modules
for app in pkg_resources.iter_entry_points('nazs.app'):
__import__(app.module_name + '.module')
|
5e7daffadbd523e1d2a457d10977b1c8a2880d9d | docs/example-plugins/directAPIcall.py | docs/example-plugins/directAPIcall.py | from __future__ import unicode_literals
from client import slack_client as sc
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
| from __future__ import unicode_literals
from client import slack_client as sc
def process_message(data):
'''If a user passes 'print users' in a message, print the users in the slack
team to the console. (Don't run this in production probably)'''
if 'print users' in data['text']:
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
| Add a bit more info into the example plugin. | Add a bit more info into the example plugin.
| Python | mit | erynofwales/ubot2,aerickson/python-rtmbot,jammons/python-rtmbot,slackhq/python-rtmbot,ChihChengLiang/python-rtmbot,erynofwales/ubot2 | from __future__ import unicode_literals
from client import slack_client as sc
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
Add a bit more info into the example plugin. | from __future__ import unicode_literals
from client import slack_client as sc
def process_message(data):
'''If a user passes 'print users' in a message, print the users in the slack
team to the console. (Don't run this in production probably)'''
if 'print users' in data['text']:
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
| <commit_before>from __future__ import unicode_literals
from client import slack_client as sc
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
<commit_msg>Add a bit more info into the example plugin.<commit_after> | from __future__ import unicode_literals
from client import slack_client as sc
def process_message(data):
'''If a user passes 'print users' in a message, print the users in the slack
team to the console. (Don't run this in production probably)'''
if 'print users' in data['text']:
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
| from __future__ import unicode_literals
from client import slack_client as sc
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
Add a bit more info into the example plugin.from __future__ import unicode_literals
from client import slack_client as sc
def process_message(data):
'''If a user passes 'print users' in a message, print the users in the slack
team to the console. (Don't run this in production probably)'''
if 'print users' in data['text']:
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
| <commit_before>from __future__ import unicode_literals
from client import slack_client as sc
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
<commit_msg>Add a bit more info into the example plugin.<commit_after>from __future__ import unicode_literals
from client import slack_client as sc
def process_message(data):
'''If a user passes 'print users' in a message, print the users in the slack
team to the console. (Don't run this in production probably)'''
if 'print users' in data['text']:
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
|
9883a1ac995816160a35fd66107a576289062123 | apis/betterself/v1/events/views.py | apis/betterself/v1/events/views.py | from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
| from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
def get_queryset(self):
name = self.request.query_params.get('name')
if name:
queryset = self.model.objects.filter(name__iexact=name)
else:
queryset = self.model.objects.all()
return queryset
| Add queryset, but debate if better options | Add queryset, but debate if better options
| Python | mit | jeffshek/betterself,jeffshek/betterself,jeffshek/betterself,jeffshek/betterself | from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
Add queryset, but debate if better options | from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
def get_queryset(self):
name = self.request.query_params.get('name')
if name:
queryset = self.model.objects.filter(name__iexact=name)
else:
queryset = self.model.objects.all()
return queryset
| <commit_before>from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
<commit_msg>Add queryset, but debate if better options<commit_after> | from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
def get_queryset(self):
name = self.request.query_params.get('name')
if name:
queryset = self.model.objects.filter(name__iexact=name)
else:
queryset = self.model.objects.all()
return queryset
| from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
Add queryset, but debate if better optionsfrom apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
def get_queryset(self):
name = self.request.query_params.get('name')
if name:
queryset = self.model.objects.filter(name__iexact=name)
else:
queryset = self.model.objects.all()
return queryset
| <commit_before>from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
<commit_msg>Add queryset, but debate if better options<commit_after>from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
def get_queryset(self):
name = self.request.query_params.get('name')
if name:
queryset = self.model.objects.filter(name__iexact=name)
else:
queryset = self.model.objects.all()
return queryset
|
a397f781751536f07e41644f8331990f5e0e8803 | aiofiles/__init__.py | aiofiles/__init__.py | """Utilities for asyncio-friendly file handling."""
from .threadpool import open
__version__ = "0.7.0dev0"
__all__ = ["open"]
| """Utilities for asyncio-friendly file handling."""
from .threadpool import open
from . import tempfile
__version__ = "0.7.0dev0"
__all__ = ['open', 'tempfile']
| Add files via upload Rebase | Add files via upload
Rebase
| Python | apache-2.0 | Tinche/aiofiles | """Utilities for asyncio-friendly file handling."""
from .threadpool import open
__version__ = "0.7.0dev0"
__all__ = ["open"]
Add files via upload
Rebase | """Utilities for asyncio-friendly file handling."""
from .threadpool import open
from . import tempfile
__version__ = "0.7.0dev0"
__all__ = ['open', 'tempfile']
| <commit_before>"""Utilities for asyncio-friendly file handling."""
from .threadpool import open
__version__ = "0.7.0dev0"
__all__ = ["open"]
<commit_msg>Add files via upload
Rebase<commit_after> | """Utilities for asyncio-friendly file handling."""
from .threadpool import open
from . import tempfile
__version__ = "0.7.0dev0"
__all__ = ['open', 'tempfile']
| """Utilities for asyncio-friendly file handling."""
from .threadpool import open
__version__ = "0.7.0dev0"
__all__ = ["open"]
Add files via upload
Rebase"""Utilities for asyncio-friendly file handling."""
from .threadpool import open
from . import tempfile
__version__ = "0.7.0dev0"
__all__ = ['open', 'tempfile']
| <commit_before>"""Utilities for asyncio-friendly file handling."""
from .threadpool import open
__version__ = "0.7.0dev0"
__all__ = ["open"]
<commit_msg>Add files via upload
Rebase<commit_after>"""Utilities for asyncio-friendly file handling."""
from .threadpool import open
from . import tempfile
__version__ = "0.7.0dev0"
__all__ = ['open', 'tempfile']
|
f83a2dd996ad8f1f0807e4ef877df52d62a4ce45 | tests/test_particle_restart/test_particle_restart.py | tests/test_particle_restart/test_particle_restart.py | #!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
| #!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=PIPE, stdout=PIPE)
stdout, stderr = proc.communicate()
assert stderr != ''
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=PIPE, stdout=PIPE, shell=True)
stdout, stderr = proc.communicate()
assert stderr != ''
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
| Change particle restart test to check for output on stderr rather than checking the return status. | Change particle restart test to check for output on stderr rather than checking the return status.
| Python | mit | wbinventor/openmc,shenqicang/openmc,sxds/opemmc,shikhar413/openmc,liangjg/openmc,smharper/openmc,walshjon/openmc,kellyrowland/openmc,amandalund/openmc,samuelshaner/openmc,johnnyliu27/openmc,bhermanmit/cdash,bhermanmit/openmc,mit-crpg/openmc,keadyk/openmc_mg_prepush,smharper/openmc,johnnyliu27/openmc,shenqicang/openmc,amandalund/openmc,nhorelik/openmc,lilulu/openmc,keadyk/openmc_mg_prepush,liangjg/openmc,amandalund/openmc,sxds/opemmc,samuelshaner/openmc,kellyrowland/openmc,shikhar413/openmc,smharper/openmc,paulromano/openmc,lilulu/openmc,mjlong/openmc,samuelshaner/openmc,mit-crpg/openmc,nhorelik/openmc,paulromano/openmc,walshjon/openmc,bhermanmit/openmc,smharper/openmc,johnnyliu27/openmc,keadyk/openmc_mg_prepush,shikhar413/openmc,liangjg/openmc,wbinventor/openmc,liangjg/openmc,wbinventor/openmc,wbinventor/openmc,johnnyliu27/openmc,mit-crpg/openmc,walshjon/openmc,mjlong/openmc,walshjon/openmc,mit-crpg/openmc,paulromano/openmc,shikhar413/openmc,paulromano/openmc,lilulu/openmc,samuelshaner/openmc,amandalund/openmc | #!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
Change particle restart test to check for output on stderr rather than checking the return status. | #!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=PIPE, stdout=PIPE)
stdout, stderr = proc.communicate()
assert stderr != ''
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=PIPE, stdout=PIPE, shell=True)
stdout, stderr = proc.communicate()
assert stderr != ''
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
| <commit_before>#!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
<commit_msg>Change particle restart test to check for output on stderr rather than checking the return status.<commit_after> | #!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=PIPE, stdout=PIPE)
stdout, stderr = proc.communicate()
assert stderr != ''
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=PIPE, stdout=PIPE, shell=True)
stdout, stderr = proc.communicate()
assert stderr != ''
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
| #!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
Change particle restart test to check for output on stderr rather than checking the return status.#!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=PIPE, stdout=PIPE)
stdout, stderr = proc.communicate()
assert stderr != ''
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=PIPE, stdout=PIPE, shell=True)
stdout, stderr = proc.communicate()
assert stderr != ''
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
| <commit_before>#!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])
assert returncode != 0
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
<commit_msg>Change particle restart test to check for output on stderr rather than checking the return status.<commit_after>#!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=PIPE, stdout=PIPE)
stdout, stderr = proc.communicate()
assert stderr != ''
def test_created_restart():
assert os.path.exists(pwd + '/particle_0.binary')
def test_run_restart():
proc = Popen([pwd + '/../../src/openmc -s particle_0.binary'],
stderr=PIPE, stdout=PIPE, shell=True)
stdout, stderr = proc.communicate()
assert stderr != ''
def teardown():
output = [pwd + '/particle_0.binary']
for f in output:
if os.path.exists(f):
os.remove(f)
|
9d14c70b68eb1b00b8b6826ee6fc2e58fb4a0ab6 | settings_test.py | settings_test.py | # These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
| # These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
| Use only md5 to hash passwords when running tests | Use only md5 to hash passwords when running tests
| Python | bsd-3-clause | peterbe/airmozilla,ehsan/airmozilla,lcamacho/airmozilla,anu7495/airmozilla,anu7495/airmozilla,anu7495/airmozilla,blossomica/airmozilla,lcamacho/airmozilla,EricSekyere/airmozilla,Nolski/airmozilla,tannishk/airmozilla,ehsan/airmozilla,blossomica/airmozilla,anjalymehla/airmozilla,ehsan/airmozilla,zofuthan/airmozilla,chirilo/airmozilla,bugzPDX/airmozilla,EricSekyere/airmozilla,mozilla/airmozilla,tannishk/airmozilla,chirilo/airmozilla,chirilo/airmozilla,mythmon/airmozilla,kenrick95/airmozilla,tannishk/airmozilla,a-buck/airmozilla,mythmon/airmozilla,Nolski/airmozilla,ehsan/airmozilla,mozilla/airmozilla,kenrick95/airmozilla,anu7495/airmozilla,kenrick95/airmozilla,bugzPDX/airmozilla,anjalymehla/airmozilla,zofuthan/airmozilla,ehsan/airmozilla,chirilo/airmozilla,mythmon/airmozilla,a-buck/airmozilla,tannishk/airmozilla,lcamacho/airmozilla,mozilla/airmozilla,peterbe/airmozilla,mozilla/airmozilla,mythmon/airmozilla,anjalymehla/airmozilla,anu7495/airmozilla,a-buck/airmozilla,anjalymehla/airmozilla,mythmon/airmozilla,lcamacho/airmozilla,lcamacho/airmozilla,bugzPDX/airmozilla,blossomica/airmozilla,Nolski/airmozilla,EricSekyere/airmozilla,bugzPDX/airmozilla,EricSekyere/airmozilla,zofuthan/airmozilla,chirilo/airmozilla,Nolski/airmozilla,kenrick95/airmozilla,a-buck/airmozilla,blossomica/airmozilla,anjalymehla/airmozilla,zofuthan/airmozilla,peterbe/airmozilla,kenrick95/airmozilla,Nolski/airmozilla,zofuthan/airmozilla,tannishk/airmozilla,EricSekyere/airmozilla | # These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
Use only md5 to hash passwords when running tests | # These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
| <commit_before># These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
<commit_msg>Use only md5 to hash passwords when running tests<commit_after> | # These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
| # These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
Use only md5 to hash passwords when running tests# These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
| <commit_before># These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
<commit_msg>Use only md5 to hash passwords when running tests<commit_after># These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
|
52c78b7498f52d26cd5dc2ea27c6c0f2dc6db117 | pytips/models.py | pytips/models.py | # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
| # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
def newest_tip(self):
"""Retrieve the ``Tip`` with the newest ``publication_date``."""
return self.filter(Tip.url.like('%twitter.com%')).order_by(
Tip.publication_date).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
| Add a helper for retrieving the newest Tip. | Add a helper for retrieving the newest Tip.
| Python | isc | gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips | # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
Add a helper for retrieving the newest Tip. | # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
def newest_tip(self):
"""Retrieve the ``Tip`` with the newest ``publication_date``."""
return self.filter(Tip.url.like('%twitter.com%')).order_by(
Tip.publication_date).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
| <commit_before># -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
<commit_msg>Add a helper for retrieving the newest Tip.<commit_after> | # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
def newest_tip(self):
"""Retrieve the ``Tip`` with the newest ``publication_date``."""
return self.filter(Tip.url.like('%twitter.com%')).order_by(
Tip.publication_date).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
| # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
Add a helper for retrieving the newest Tip.# -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
def newest_tip(self):
"""Retrieve the ``Tip`` with the newest ``publication_date``."""
return self.filter(Tip.url.like('%twitter.com%')).order_by(
Tip.publication_date).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
| <commit_before># -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
<commit_msg>Add a helper for retrieving the newest Tip.<commit_after># -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
def random_tip(self):
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
def newest_tip(self):
"""Retrieve the ``Tip`` with the newest ``publication_date``."""
return self.filter(Tip.url.like('%twitter.com%')).order_by(
Tip.publication_date).first()
class Tip(db.Model):
"""Represents a 'tip' for display."""
query_class = TipQuery
id = db.Column(db.Integer, primary_key=True)
author_name = db.Column(db.String, nullable=False)
author_url = db.Column(db.String(1024), nullable=False)
url = db.Column(db.String(1024), unique=True, nullable=False)
rendered_html = db.Column(db.String(1024), unique=True, nullable=False)
publication_date = db.Column(db.DateTime(timezone=True), nullable=False)
def __repr__(self):
return '<Tip %r>' % self.url
def as_dict(self):
"""Return a simple ``dict`` representation of this model."""
return dict((c.name, getattr(self, c.name)) for c in self.__table__.columns)
|
17fd955a3b4abe5ca751ea05e0cdb30429a9ce04 | ghettoq/backends/pyredis.py | ghettoq/backends/pyredis.py | from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
dest, item = self.client.brpop([queue], timeout=1)
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
dest, item = self.client.brpop(queues, timeout=timeout)
return item, dest
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
| from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message, priority = 0):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
try:
dest, item = self.client.brpop([queue], timeout=1)
except TypeError:
raise Empty
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
try:
item, dest = self.client.brpop(queues, timeout=1)
except TypeError:
raise Empty
return item
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
| Throw Empty exception if BRPOP returns None. Add priority argument so it works with the latest version. | Throw Empty exception if BRPOP returns None.
Add priority argument so it works with the latest version.
| Python | bsd-3-clause | ask/ghettoq | from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
dest, item = self.client.brpop([queue], timeout=1)
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
dest, item = self.client.brpop(queues, timeout=timeout)
return item, dest
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
Throw Empty exception if BRPOP returns None.
Add priority argument so it works with the latest version. | from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message, priority = 0):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
try:
dest, item = self.client.brpop([queue], timeout=1)
except TypeError:
raise Empty
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
try:
item, dest = self.client.brpop(queues, timeout=1)
except TypeError:
raise Empty
return item
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
| <commit_before>from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
dest, item = self.client.brpop([queue], timeout=1)
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
dest, item = self.client.brpop(queues, timeout=timeout)
return item, dest
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
<commit_msg>Throw Empty exception if BRPOP returns None.
Add priority argument so it works with the latest version.<commit_after> | from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message, priority = 0):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
try:
dest, item = self.client.brpop([queue], timeout=1)
except TypeError:
raise Empty
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
try:
item, dest = self.client.brpop(queues, timeout=1)
except TypeError:
raise Empty
return item
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
| from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
dest, item = self.client.brpop([queue], timeout=1)
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
dest, item = self.client.brpop(queues, timeout=timeout)
return item, dest
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
Throw Empty exception if BRPOP returns None.
Add priority argument so it works with the latest version.from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message, priority = 0):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
try:
dest, item = self.client.brpop([queue], timeout=1)
except TypeError:
raise Empty
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
try:
item, dest = self.client.brpop(queues, timeout=1)
except TypeError:
raise Empty
return item
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
| <commit_before>from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
dest, item = self.client.brpop([queue], timeout=1)
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
dest, item = self.client.brpop(queues, timeout=timeout)
return item, dest
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
<commit_msg>Throw Empty exception if BRPOP returns None.
Add priority argument so it works with the latest version.<commit_after>from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int):
if not database or database == "/":
database = DEFAULT_DB
elif database.startswith('/'):
database = database[1:]
try:
database = int(database)
except ValueError:
raise AttributeError(
"Database name must be integer between 0 "
"and database_count - 1")
super(RedisBackend, self).__init__(host, port, user, password,
database, timeout)
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message, priority = 0):
self.client.lpush(queue, message)
def get(self, queue):
if not queue:
raise Empty
try:
dest, item = self.client.brpop([queue], timeout=1)
except TypeError:
raise Empty
return item
def get_many(self, queues, timeout=None):
if not queues:
raise Empty
try:
item, dest = self.client.brpop(queues, timeout=1)
except TypeError:
raise Empty
return item
def purge(self, queue):
size = self.client.llen(queue)
self.client.delete(queue)
return size
|
91c3eb57ea3b2cd12654cbd6925a681d3450e77e | go/apps/jsbox/definition.py | go/apps/jsbox/definition.py | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
| from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
def configured_endpoints(self, config):
return []
| Add start of hook for extra jsbox endpoints. | Add start of hook for extra jsbox endpoints.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
Add start of hook for extra jsbox endpoints. | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
def configured_endpoints(self, config):
return []
| <commit_before>from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
<commit_msg>Add start of hook for extra jsbox endpoints.<commit_after> | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
def configured_endpoints(self, config):
return []
| from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
Add start of hook for extra jsbox endpoints.from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
def configured_endpoints(self, config):
return []
| <commit_before>from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
<commit_msg>Add start of hook for extra jsbox endpoints.<commit_after>from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
conversation_type = 'jsbox'
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
def configured_endpoints(self, config):
return []
|
0b8aa961cb8aa6646aa1b660f6f669cf82492225 | helper/windows.py | helper/windows.py | """
Windows platform support for running the application as a detached process.
"""
import subprocess
import sys
DETACHED_PROCESS = 8
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
| """
Windows platform support for running the application as a detached process.
"""
import platform
import subprocess
import sys
DETACHED_PROCESS = 8
def operating_system():
"""Return a string identifying the operating system the application
is running on.
:rtype: str
"""
return '%s %s (%s)' % (platform.system(),
platform.release(),
platform.version())
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
| Implement the operating_system() method for Windows | Implement the operating_system() method for Windows
| Python | bsd-3-clause | dave-shawley/helper,gmr/helper,gmr/helper | """
Windows platform support for running the application as a detached process.
"""
import subprocess
import sys
DETACHED_PROCESS = 8
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
Implement the operating_system() method for Windows | """
Windows platform support for running the application as a detached process.
"""
import platform
import subprocess
import sys
DETACHED_PROCESS = 8
def operating_system():
"""Return a string identifying the operating system the application
is running on.
:rtype: str
"""
return '%s %s (%s)' % (platform.system(),
platform.release(),
platform.version())
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
| <commit_before>"""
Windows platform support for running the application as a detached process.
"""
import subprocess
import sys
DETACHED_PROCESS = 8
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
<commit_msg>Implement the operating_system() method for Windows<commit_after> | """
Windows platform support for running the application as a detached process.
"""
import platform
import subprocess
import sys
DETACHED_PROCESS = 8
def operating_system():
"""Return a string identifying the operating system the application
is running on.
:rtype: str
"""
return '%s %s (%s)' % (platform.system(),
platform.release(),
platform.version())
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
| """
Windows platform support for running the application as a detached process.
"""
import subprocess
import sys
DETACHED_PROCESS = 8
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
Implement the operating_system() method for Windows"""
Windows platform support for running the application as a detached process.
"""
import platform
import subprocess
import sys
DETACHED_PROCESS = 8
def operating_system():
"""Return a string identifying the operating system the application
is running on.
:rtype: str
"""
return '%s %s (%s)' % (platform.system(),
platform.release(),
platform.version())
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
| <commit_before>"""
Windows platform support for running the application as a detached process.
"""
import subprocess
import sys
DETACHED_PROCESS = 8
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
<commit_msg>Implement the operating_system() method for Windows<commit_after>"""
Windows platform support for running the application as a detached process.
"""
import platform
import subprocess
import sys
DETACHED_PROCESS = 8
def operating_system():
"""Return a string identifying the operating system the application
is running on.
:rtype: str
"""
return '%s %s (%s)' % (platform.system(),
platform.release(),
platform.version())
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplementedError
#args = [sys.executable]
#args.extend(sys.argv)
#self.pid = subprocess.Popen(args,
# creationflags=DETACHED_PROCESS,
# shell=True).pid
|
5eb1fe63bdbf0e6ce4832d70d9971e62c231c7b8 | core/management/commands/run_urlscript.py | core/management/commands/run_urlscript.py | try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("http://{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
| try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
| Use the site that has scheme also input. | Use the site that has scheme also input.
| Python | mit | theju/urlscript | try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("http://{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
Use the site that has scheme also input. | try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
| <commit_before>try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("http://{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
<commit_msg>Use the site that has scheme also input.<commit_after> | try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
| try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("http://{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
Use the site that has scheme also input.try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
| <commit_before>try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("http://{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
<commit_msg>Use the site that has scheme also input.<commit_after>try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urlopen("{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
))
class Command(BaseCommand):
help = "Run the url scripts"
can_import_settings = True
def handle(self, *args, **options):
pool = multiprocessing.Pool(multiprocessing.cpu_count())
today = int(datetime.date.today().strftime("%s"))
now = datetime.datetime.now()
curr_time = int(now.strftime("%s")) - now.second
mins_passed = int((curr_time - today) / 60.0)
intervals = Cron.objects.filter(interval__lte=mins_passed)\
.values_list('interval', flat=True).\
order_by('interval').distinct()
for interval in intervals:
if mins_passed % interval == 0 or settings.DEBUG:
for cron in Cron.objects.filter(interval=interval):
url = cron.url
pool.apply_async(request_url, (url, ))
pool.close()
pool.join()
|
74e9c87f4a6ad9ad6458a1e297460220c587b197 | rbuild/client.py | rbuild/client.py | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None):
cfg = rbuild.rBuildConfiguration(ignoreErrors=True)
plugins = pluginloader.getPlugins(cfg, disabledPlugins)
return rbuildClient(cfg, plugins)
| #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
from rbuild import rbuildcfg
from rbuild.internal import pluginloader
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None, root=None):
cfg = rbuildcfg.rBuildConfiguration(readConfigFiles=True,
ignoreErrors=True, root=root)
plugins = pluginloader.getPlugins([], cfg.pluginDirs, disabledPlugins)
return rBuildClient(plugins, cfg)
| Fix getClient bugs found by smoketest | Fix getClient bugs found by smoketest
| Python | apache-2.0 | fedora-conary/rbuild,sassoftware/rbuild,fedora-conary/rbuild,sassoftware/rbuild | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None):
cfg = rbuild.rBuildConfiguration(ignoreErrors=True)
plugins = pluginloader.getPlugins(cfg, disabledPlugins)
return rbuildClient(cfg, plugins)
Fix getClient bugs found by smoketest | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
from rbuild import rbuildcfg
from rbuild.internal import pluginloader
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None, root=None):
cfg = rbuildcfg.rBuildConfiguration(readConfigFiles=True,
ignoreErrors=True, root=root)
plugins = pluginloader.getPlugins([], cfg.pluginDirs, disabledPlugins)
return rBuildClient(plugins, cfg)
| <commit_before>#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None):
cfg = rbuild.rBuildConfiguration(ignoreErrors=True)
plugins = pluginloader.getPlugins(cfg, disabledPlugins)
return rbuildClient(cfg, plugins)
<commit_msg>Fix getClient bugs found by smoketest<commit_after> | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
from rbuild import rbuildcfg
from rbuild.internal import pluginloader
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None, root=None):
cfg = rbuildcfg.rBuildConfiguration(readConfigFiles=True,
ignoreErrors=True, root=root)
plugins = pluginloader.getPlugins([], cfg.pluginDirs, disabledPlugins)
return rBuildClient(plugins, cfg)
| #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None):
cfg = rbuild.rBuildConfiguration(ignoreErrors=True)
plugins = pluginloader.getPlugins(cfg, disabledPlugins)
return rbuildClient(cfg, plugins)
Fix getClient bugs found by smoketest#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
from rbuild import rbuildcfg
from rbuild.internal import pluginloader
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None, root=None):
cfg = rbuildcfg.rBuildConfiguration(readConfigFiles=True,
ignoreErrors=True, root=root)
plugins = pluginloader.getPlugins([], cfg.pluginDirs, disabledPlugins)
return rBuildClient(plugins, cfg)
| <commit_before>#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None):
cfg = rbuild.rBuildConfiguration(ignoreErrors=True)
plugins = pluginloader.getPlugins(cfg, disabledPlugins)
return rbuildClient(cfg, plugins)
<commit_msg>Fix getClient bugs found by smoketest<commit_after>#
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/licenses/CPL-1.0.
#
# This program is distributed in the hope that it will be useful, but
# without any warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the Common Public License for
# full details.
#
"""
The rBuild Appliance Developer Process Toolkit client object
The C{client} module provides the core objects used for consuming rBuild
as a Python API. Instances of C{rBuildClient} are the handles used as
the core API item by which consumers of the python API call the plugins
that implement rBuild functionality, and by which plugins communicate
with each other.
"""
from rbuild import rbuildcfg
from rbuild.internal import pluginloader
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
self.pluginMgr = pluginMgr
for plugin in pluginMgr.plugins:
setattr(self, plugin.__class__.__name__, plugin)
def getClient(disabledPlugins=None, root=None):
cfg = rbuildcfg.rBuildConfiguration(readConfigFiles=True,
ignoreErrors=True, root=root)
plugins = pluginloader.getPlugins([], cfg.pluginDirs, disabledPlugins)
return rBuildClient(plugins, cfg)
|
6c4178f4b5518568d83523db418d34c36a791852 | skylines/__init__.py | skylines/__init__.py | from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
| from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
load_path = app.config.get('ASSETS_LOAD_DIR', None)
if load_path is not None:
load_url = app.config.get('ASSETS_LOAD_URL', None)
assets.append_path(load_path, load_url)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
| Configure webassets environment from app.config | flask: Configure webassets environment from app.config
| Python | agpl-3.0 | RBE-Avionik/skylines,Turbo87/skylines,snip/skylines,Turbo87/skylines,skylines-project/skylines,skylines-project/skylines,RBE-Avionik/skylines,snip/skylines,Harry-R/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,snip/skylines,TobiasLohner/SkyLines,kerel-fs/skylines,kerel-fs/skylines,Harry-R/skylines,shadowoneau/skylines,TobiasLohner/SkyLines,Turbo87/skylines,shadowoneau/skylines,shadowoneau/skylines,Harry-R/skylines,skylines-project/skylines,RBE-Avionik/skylines,kerel-fs/skylines,shadowoneau/skylines,Turbo87/skylines,Harry-R/skylines,skylines-project/skylines | from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
flask: Configure webassets environment from app.config | from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
load_path = app.config.get('ASSETS_LOAD_DIR', None)
if load_path is not None:
load_url = app.config.get('ASSETS_LOAD_URL', None)
assets.append_path(load_path, load_url)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
| <commit_before>from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
<commit_msg>flask: Configure webassets environment from app.config<commit_after> | from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
load_path = app.config.get('ASSETS_LOAD_DIR', None)
if load_path is not None:
load_url = app.config.get('ASSETS_LOAD_URL', None)
assets.append_path(load_path, load_url)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
| from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
flask: Configure webassets environment from app.configfrom flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
load_path = app.config.get('ASSETS_LOAD_DIR', None)
if load_path is not None:
load_url = app.config.get('ASSETS_LOAD_URL', None)
assets.append_path(load_path, load_url)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
| <commit_before>from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
<commit_msg>flask: Configure webassets environment from app.config<commit_after>from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel(app)
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
load_path = app.config.get('ASSETS_LOAD_DIR', None)
if load_path is not None:
load_url = app.config.get('ASSETS_LOAD_URL', None)
assets.append_path(load_path, load_url)
assets.register(bundles)
return app
app = create_app()
import skylines.views
@app.context_processor
def inject_helpers_lib():
return dict(h=helpers)
@app.context_processor
def inject_template_context():
return dict(c=g)
|
4727991d29bc888611b6eaa403456524785b6338 | highlightjs/testsettings.py | highlightjs/testsettings.py | import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
| import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
},
]
| Add django backend for test settings | Add django backend for test settings | Python | mit | MounirMesselmeni/django-highlightjs | import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
Add django backend for test settings | import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
},
]
| <commit_before>import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
<commit_msg>Add django backend for test settings<commit_after> | import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
},
]
| import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
Add django backend for test settingsimport django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
},
]
| <commit_before>import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
<commit_msg>Add django backend for test settings<commit_after>import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
},
]
|
97e3309a66c5d84489df4a384552e5b5d75643ea | spotpy/unittests/test_objectivefunctions.py | spotpy/unittests/test_objectivefunctions.py | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
print(self.simulation)
print(self.evaluation)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
| import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_pbias(self):
res = of.pbias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -156.66937901878677, self.tolerance)
def test_nashsutcliffe(self):
res = of.nashsutcliffe(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
| Add tests for pbias and nashsutcliffe | Add tests for pbias and nashsutcliffe
| Python | mit | bees4ever/spotpy,thouska/spotpy,thouska/spotpy,bees4ever/spotpy,thouska/spotpy,bees4ever/spotpy | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
print(self.simulation)
print(self.evaluation)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
Add tests for pbias and nashsutcliffe | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_pbias(self):
res = of.pbias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -156.66937901878677, self.tolerance)
def test_nashsutcliffe(self):
res = of.nashsutcliffe(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
| <commit_before>import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
print(self.simulation)
print(self.evaluation)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
<commit_msg>Add tests for pbias and nashsutcliffe<commit_after> | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_pbias(self):
res = of.pbias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -156.66937901878677, self.tolerance)
def test_nashsutcliffe(self):
res = of.nashsutcliffe(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
| import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
print(self.simulation)
print(self.evaluation)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
Add tests for pbias and nashsutcliffeimport unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_pbias(self):
res = of.pbias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -156.66937901878677, self.tolerance)
def test_nashsutcliffe(self):
res = of.nashsutcliffe(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
| <commit_before>import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
print(self.simulation)
print(self.evaluation)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
<commit_msg>Add tests for pbias and nashsutcliffe<commit_after>import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance)
def test_pbias(self):
res = of.pbias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -156.66937901878677, self.tolerance)
def test_nashsutcliffe(self):
res = of.nashsutcliffe(self.evaluation, self.simulation)
self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance)
def test_length_mismatch_return_nan(self):
all_funcs = of._all_functions
for func in all_funcs:
res = func([0], [0, 1])
self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res))
if __name__ == '__main__':
unittest.main()
|
63814839642e593e35f8afaf68fc6724b69075b5 | trade_server.py | trade_server.py | import json
import threading
import socket
import SocketServer
from orderbook import match_bid, offers, asks
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
data = json.loads(data)
messages.append(data)
print "MESSAGES: {}".format(messages)
if data['type'] == 'bid':
response = handle_bid(data)
elif data['type'] == 'ask':
response = handle_asks(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
| import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
response = handle_data(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_data(data):
data = json.loads(data)
if data['type'] == 'ask':
handle_ask(data)
elif data['type'] == 'bid':
handle_bid(data)
elif data['type'] == 'greeting':
handle_greeting(data)
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
def handle_greeting(greeting):
pass
| Add stubs for handling requests to server. | Add stubs for handling requests to server.
| Python | mit | Tribler/decentral-market | import json
import threading
import socket
import SocketServer
from orderbook import match_bid, offers, asks
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
data = json.loads(data)
messages.append(data)
print "MESSAGES: {}".format(messages)
if data['type'] == 'bid':
response = handle_bid(data)
elif data['type'] == 'ask':
response = handle_asks(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
Add stubs for handling requests to server. | import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
response = handle_data(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_data(data):
data = json.loads(data)
if data['type'] == 'ask':
handle_ask(data)
elif data['type'] == 'bid':
handle_bid(data)
elif data['type'] == 'greeting':
handle_greeting(data)
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
def handle_greeting(greeting):
pass
| <commit_before>import json
import threading
import socket
import SocketServer
from orderbook import match_bid, offers, asks
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
data = json.loads(data)
messages.append(data)
print "MESSAGES: {}".format(messages)
if data['type'] == 'bid':
response = handle_bid(data)
elif data['type'] == 'ask':
response = handle_asks(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
<commit_msg>Add stubs for handling requests to server.<commit_after> | import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
response = handle_data(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_data(data):
data = json.loads(data)
if data['type'] == 'ask':
handle_ask(data)
elif data['type'] == 'bid':
handle_bid(data)
elif data['type'] == 'greeting':
handle_greeting(data)
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
def handle_greeting(greeting):
pass
| import json
import threading
import socket
import SocketServer
from orderbook import match_bid, offers, asks
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
data = json.loads(data)
messages.append(data)
print "MESSAGES: {}".format(messages)
if data['type'] == 'bid':
response = handle_bid(data)
elif data['type'] == 'ask':
response = handle_asks(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
Add stubs for handling requests to server.import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
response = handle_data(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_data(data):
data = json.loads(data)
if data['type'] == 'ask':
handle_ask(data)
elif data['type'] == 'bid':
handle_bid(data)
elif data['type'] == 'greeting':
handle_greeting(data)
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
def handle_greeting(greeting):
pass
| <commit_before>import json
import threading
import socket
import SocketServer
from orderbook import match_bid, offers, asks
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
data = json.loads(data)
messages.append(data)
print "MESSAGES: {}".format(messages)
if data['type'] == 'bid':
response = handle_bid(data)
elif data['type'] == 'ask':
response = handle_asks(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
<commit_msg>Add stubs for handling requests to server.<commit_after>import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
response = handle_data(data)
cur_thread = threading.current_thread()
response = "\n{}: {}".format(cur_thread.name, data)
self.request.sendall(response)
except socket.error:
# Surpress errno 13 Broken Pipe
pass
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
def create_server(host="localhost", port=0):
server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
def handle_data(data):
data = json.loads(data)
if data['type'] == 'ask':
handle_ask(data)
elif data['type'] == 'bid':
handle_bid(data)
elif data['type'] == 'greeting':
handle_greeting(data)
def handle_ask(ask):
asks.append(ask)
def handle_bid(bid):
bids.append(bid)
def handle_greeting(greeting):
pass
|
8b2cb51c8913737c524e1b922aeb02c07bfb2afc | src/keybar/models/entry.py | src/keybar/models/entry.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
| from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, decrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
def decrypt(self, password):
return decrypt(self.value, password, bytes(self.salt))
| Add decrypt helper to Entry | Add decrypt helper to Entry
| Python | bsd-3-clause | keybar/keybar | from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
Add decrypt helper to Entry | from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, decrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
def decrypt(self, password):
return decrypt(self.value, password, bytes(self.salt))
| <commit_before>from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
<commit_msg>Add decrypt helper to Entry<commit_after> | from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, decrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
def decrypt(self, password):
return decrypt(self.value, password, bytes(self.salt))
| from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
Add decrypt helper to Entryfrom django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, decrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
def decrypt(self, password):
return decrypt(self.value, password, bytes(self.salt))
| <commit_before>from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
<commit_msg>Add decrypt helper to Entry<commit_after>from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, decrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextField(_('Title'), blank=True, default='')
url = models.URLField(blank=True, default='')
identifier = models.TextField(_('Identifier for login'),
help_text=_('Usually a username or email address'))
value = models.TextField(_('The encrypted value for the entry.'),
help_text=_('Usually a password.'))
description = models.TextField(_('Description'), blank=True, default='')
salt = models.BinaryField(null=True, blank=True)
def set_value(self, password, value, salt=None):
if salt is None:
salt = get_salt()
self.value = encrypt(value, password, salt)
self.salt = salt
def decrypt(self, password):
return decrypt(self.value, password, bytes(self.salt))
|
87eac064f56c8a617c6aa2412345bb12352432ca | il2fb/ds/airbridge/api/http/responses/rest.py | il2fb/ds/airbridge/api/http/responses/rest.py | # coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else 0
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
| # coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else None
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
| Fix indents for minimized JSON | Fix indents for minimized JSON
| Python | mit | IL2HorusTeam/il2fb-ds-airbridge | # coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else 0
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
Fix indents for minimized JSON | # coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else None
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
| <commit_before># coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else 0
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
<commit_msg>Fix indents for minimized JSON<commit_after> | # coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else None
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
| # coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else 0
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
Fix indents for minimized JSON# coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else None
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
| <commit_before># coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else 0
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
<commit_msg>Fix indents for minimized JSON<commit_after># coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
"""
def __init__(
self,
payload: dict=None,
detail: Any=None,
pretty: bool=False,
content_type: str='application/json',
charset: str='utf-8',
**kwargs
):
payload = payload if payload is not None else {}
detail = detail if detail is not None else self.detail
if detail:
payload['detail'] = str(detail)
indent = 2 if pretty else None
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status)
super().__init__(
text=text,
charset=charset,
content_type=content_type,
**kwargs
)
class RESTSuccess(RESTResponse):
status = 200
class RESTBadRequest(RESTResponse):
status = 400
detail = "Bad request"
class RESTNotFound(RESTBadRequest):
status = 404
detail = "Resource not found"
class RESTInternalServerError(RESTResponse):
status = 500
detail = (
"The server encountered an unexpected condition that prevented it "
"from fulfilling the request"
)
|
91e80dbaba20a914737fa64b0b35cf315bc79f0a | runtests.py | runtests.py | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=30'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
| Add timeout to all tests | Add timeout to all tests
| Python | mit | spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
Add timeout to all tests | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=30'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
| <commit_before># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
<commit_msg>Add timeout to all tests<commit_after> | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=30'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
Add timeout to all tests# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=30'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
| <commit_before># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=20'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
<commit_msg>Add timeout to all tests<commit_after># -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
'--timeout=30'])
# sys.exit doesn't work here because some things could be running
# in the background (e.g. closing the main window) when this point
# is reached. And if that's the case, sys.exit does't stop the
# script (as you would expected).
if errno != 0:
raise SystemExit(errno)
if __name__ == '__main__':
main()
|
cfc95643733244275e605a8ff0c00d4861067a13 | character_shift/character_shift.py | character_shift/character_shift.py | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
| #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
| Use bitwise operators on ordinals to reduce code size | Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.
| Python | mit | TotempaaltJ/tiniest-code,TotempaaltJ/tiniest-code | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators. | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
| <commit_before>#!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
<commit_msg>Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.<commit_after> | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
| #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.#!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
| <commit_before>#!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
<commit_msg>Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.<commit_after>#!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BCDA+', shift('ABCZ+', 1)
assert shift('bcda+', 1, True) == 'abcz+', shift('bcda+', 1, True)
|
1632b64372f2f38a6c43b000ace631d183278375 | observations/forms.py | observations/forms.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
with transaction.atomic():
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
| Use transaction.atomic in batch uploader. | Use transaction.atomic in batch uploader.
| Python | mit | zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
Use transaction.atomic in batch uploader. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
with transaction.atomic():
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
<commit_msg>Use transaction.atomic in batch uploader.<commit_after> | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
with transaction.atomic():
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
Use transaction.atomic in batch uploader.# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
with transaction.atomic():
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
<commit_msg>Use transaction.atomic in batch uploader.<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploadForm(forms.Form):
aavso_file = forms.FileField(label=_("Observations file"))
def process_file(self):
fp = self.cleaned_data['aavso_file']
reader = VisualFormatReader(fp)
observer = Observer.objects.get(aavso_code=reader.observer_code)
with transaction.atomic():
for row in reader:
try:
star = Star.objects.get(name=row['name'])
fainter_than = '<' in row['magnitude']
magnitude = float(row['magnitude'].replace('<', ''))
jd = float(row['date'])
try:
observation = Observation.objects.get(
observer=observer,
star=star,
jd=jd,
)
except Observation.DoesNotExist:
observation = Observation(
observer=observer,
star=star,
jd=jd,
)
observation.magnitude = magnitude
observation.fainter_than = fainter_than
observation.comp1 = row['comp1']
observation.comp2 = row['comp2']
observation.chart = row['chart']
observation.comment_code = row['comment_code']
observation.notes = row['notes']
observation.save()
except Exception as e:
print row
print e
continue
|
a9cf757a0a8dc0bf558492676b1bfb5d630a78c1 | ModRepository/Util.py | ModRepository/Util.py | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=[actions.keys()],
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args) | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=actions.keys(),
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args) | Fix a derp on argparse | Fix a derp on argparse
| Python | bsd-2-clause | admiral0/AntaniRepos | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=[actions.keys()],
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args)Fix a derp on argparse | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=actions.keys(),
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args) | <commit_before>__author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=[actions.keys()],
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args)<commit_msg>Fix a derp on argparse<commit_after> | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=actions.keys(),
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args) | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=[actions.keys()],
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args)Fix a derp on argparse__author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=actions.keys(),
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args) | <commit_before>__author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=[actions.keys()],
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args)<commit_msg>Fix a derp on argparse<commit_after>__author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
for m in repo.list_mods().values():
try:
Mod(m)
except JsonNotValid as e:
print(str(e))
except JsonNotValid as e:
print(str(e))
def list_mods(args):
repo = ModManager(args.mod_repo)
for mod in repo.mods.values():
print(mod.slug + ' ')
print(','.join(mod.data['versions'].keys()))
actions = {
'validate': validate,
'list': list_mods
}
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
parser.add_argument('-a', dest='action', type=str, default='validate', choices=actions.keys(),
help='Action to perform')
def init():
args = parser.parse_args()
actions[args.action](args) |
8394011dc2cd0a6fe682c435b8e09f8accb1311f | web/impact/impact/v1/views/criterion_option_spec_list_view.py | web/impact/impact/v1/views/criterion_option_spec_list_view.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.base_list_view import BaseListView
from impact.v1.views.post_mixin import PostMixin
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView, PostMixin):
view_name = "criterion_option_spec"
helper_class = CriterionOptionSpecHelper
actions = ['GET', 'POST'] # Should get this from PostMixin
| # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.post_mixin import PostMixin
from impact.v1.views.base_list_view import BaseListView
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView,
PostMixin):
helper_class = CriterionOptionSpecHelper
view_name = "criterion_option_spec"
actions = ['GET', 'POST'] # Should get this from PostMixin
| Move some code around because code climate said so | [AC-5622] Move some code around because code climate said so
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.base_list_view import BaseListView
from impact.v1.views.post_mixin import PostMixin
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView, PostMixin):
view_name = "criterion_option_spec"
helper_class = CriterionOptionSpecHelper
actions = ['GET', 'POST'] # Should get this from PostMixin
[AC-5622] Move some code around because code climate said so | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.post_mixin import PostMixin
from impact.v1.views.base_list_view import BaseListView
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView,
PostMixin):
helper_class = CriterionOptionSpecHelper
view_name = "criterion_option_spec"
actions = ['GET', 'POST'] # Should get this from PostMixin
| <commit_before># MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.base_list_view import BaseListView
from impact.v1.views.post_mixin import PostMixin
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView, PostMixin):
view_name = "criterion_option_spec"
helper_class = CriterionOptionSpecHelper
actions = ['GET', 'POST'] # Should get this from PostMixin
<commit_msg>[AC-5622] Move some code around because code climate said so<commit_after> | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.post_mixin import PostMixin
from impact.v1.views.base_list_view import BaseListView
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView,
PostMixin):
helper_class = CriterionOptionSpecHelper
view_name = "criterion_option_spec"
actions = ['GET', 'POST'] # Should get this from PostMixin
| # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.base_list_view import BaseListView
from impact.v1.views.post_mixin import PostMixin
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView, PostMixin):
view_name = "criterion_option_spec"
helper_class = CriterionOptionSpecHelper
actions = ['GET', 'POST'] # Should get this from PostMixin
[AC-5622] Move some code around because code climate said so# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.post_mixin import PostMixin
from impact.v1.views.base_list_view import BaseListView
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView,
PostMixin):
helper_class = CriterionOptionSpecHelper
view_name = "criterion_option_spec"
actions = ['GET', 'POST'] # Should get this from PostMixin
| <commit_before># MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.base_list_view import BaseListView
from impact.v1.views.post_mixin import PostMixin
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView, PostMixin):
view_name = "criterion_option_spec"
helper_class = CriterionOptionSpecHelper
actions = ['GET', 'POST'] # Should get this from PostMixin
<commit_msg>[AC-5622] Move some code around because code climate said so<commit_after># MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.post_mixin import PostMixin
from impact.v1.views.base_list_view import BaseListView
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView,
PostMixin):
helper_class = CriterionOptionSpecHelper
view_name = "criterion_option_spec"
actions = ['GET', 'POST'] # Should get this from PostMixin
|
16dd533f32b3efdbbe9c2f7c6e5e3f42fe6c6b1d | qtpy/tests/test_qtprintsupport.py | qtpy/tests/test_qtprintsupport.py | import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
| """Test QtPrintSupport."""
import os
import sys
import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
def test_qpagesetupdialog_exec_():
"""Test qtpy.QtPrintSupport.QPageSetupDialog exec_"""
assert QtPrintSupport.QPageSetupDialog.exec_ is not None
def test_qprintdialog_exec_():
"""Test qtpy.QtPrintSupport.QPrintDialog exec_"""
assert QtPrintSupport.QPrintDialog.exec_ is not None
@pytest.mark.skipif(sys.platform.startswith('linux') and os.environ.get('USE_CONDA', 'No') == 'No',
reason="Fatal Python error: Aborted on Linux CI when not using conda")
def test_qprintpreviewwidget_print_(qtbot):
"""Test qtpy.QtPrintSupport.QPrintPreviewWidget print_"""
assert QtPrintSupport.QPrintPreviewWidget.print_ is not None
preview_widget = QtPrintSupport.QPrintPreviewWidget()
preview_widget.print_()
| Add tests for aliased methods | QtPrintSupport: Add tests for aliased methods
| Python | mit | spyder-ide/qtpy | import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
QtPrintSupport: Add tests for aliased methods | """Test QtPrintSupport."""
import os
import sys
import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
def test_qpagesetupdialog_exec_():
"""Test qtpy.QtPrintSupport.QPageSetupDialog exec_"""
assert QtPrintSupport.QPageSetupDialog.exec_ is not None
def test_qprintdialog_exec_():
"""Test qtpy.QtPrintSupport.QPrintDialog exec_"""
assert QtPrintSupport.QPrintDialog.exec_ is not None
@pytest.mark.skipif(sys.platform.startswith('linux') and os.environ.get('USE_CONDA', 'No') == 'No',
reason="Fatal Python error: Aborted on Linux CI when not using conda")
def test_qprintpreviewwidget_print_(qtbot):
"""Test qtpy.QtPrintSupport.QPrintPreviewWidget print_"""
assert QtPrintSupport.QPrintPreviewWidget.print_ is not None
preview_widget = QtPrintSupport.QPrintPreviewWidget()
preview_widget.print_()
| <commit_before>import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
<commit_msg>QtPrintSupport: Add tests for aliased methods<commit_after> | """Test QtPrintSupport."""
import os
import sys
import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
def test_qpagesetupdialog_exec_():
"""Test qtpy.QtPrintSupport.QPageSetupDialog exec_"""
assert QtPrintSupport.QPageSetupDialog.exec_ is not None
def test_qprintdialog_exec_():
"""Test qtpy.QtPrintSupport.QPrintDialog exec_"""
assert QtPrintSupport.QPrintDialog.exec_ is not None
@pytest.mark.skipif(sys.platform.startswith('linux') and os.environ.get('USE_CONDA', 'No') == 'No',
reason="Fatal Python error: Aborted on Linux CI when not using conda")
def test_qprintpreviewwidget_print_(qtbot):
"""Test qtpy.QtPrintSupport.QPrintPreviewWidget print_"""
assert QtPrintSupport.QPrintPreviewWidget.print_ is not None
preview_widget = QtPrintSupport.QPrintPreviewWidget()
preview_widget.print_()
| import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
QtPrintSupport: Add tests for aliased methods"""Test QtPrintSupport."""
import os
import sys
import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
def test_qpagesetupdialog_exec_():
"""Test qtpy.QtPrintSupport.QPageSetupDialog exec_"""
assert QtPrintSupport.QPageSetupDialog.exec_ is not None
def test_qprintdialog_exec_():
"""Test qtpy.QtPrintSupport.QPrintDialog exec_"""
assert QtPrintSupport.QPrintDialog.exec_ is not None
@pytest.mark.skipif(sys.platform.startswith('linux') and os.environ.get('USE_CONDA', 'No') == 'No',
reason="Fatal Python error: Aborted on Linux CI when not using conda")
def test_qprintpreviewwidget_print_(qtbot):
"""Test qtpy.QtPrintSupport.QPrintPreviewWidget print_"""
assert QtPrintSupport.QPrintPreviewWidget.print_ is not None
preview_widget = QtPrintSupport.QPrintPreviewWidget()
preview_widget.print_()
| <commit_before>import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
<commit_msg>QtPrintSupport: Add tests for aliased methods<commit_after>"""Test QtPrintSupport."""
import os
import sys
import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrintPreviewDialog is not None
assert QtPrintSupport.QPrintEngine is not None
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
def test_qpagesetupdialog_exec_():
"""Test qtpy.QtPrintSupport.QPageSetupDialog exec_"""
assert QtPrintSupport.QPageSetupDialog.exec_ is not None
def test_qprintdialog_exec_():
"""Test qtpy.QtPrintSupport.QPrintDialog exec_"""
assert QtPrintSupport.QPrintDialog.exec_ is not None
@pytest.mark.skipif(sys.platform.startswith('linux') and os.environ.get('USE_CONDA', 'No') == 'No',
reason="Fatal Python error: Aborted on Linux CI when not using conda")
def test_qprintpreviewwidget_print_(qtbot):
"""Test qtpy.QtPrintSupport.QPrintPreviewWidget print_"""
assert QtPrintSupport.QPrintPreviewWidget.print_ is not None
preview_widget = QtPrintSupport.QPrintPreviewWidget()
preview_widget.print_()
|
3129d72151d81d8745a8e81ab4940dcd56a67b66 | scripts/get-translator-credits.py | scripts/get-translator-credits.py | import subprocess
import re
from collections import defaultdict
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
locales = sorted(authors_by_locale.keys())
for locale in locales:
print(locale)
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
| import subprocess
import re
from collections import defaultdict
from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
language_names = [
(Locale.parse(locale_string).english_name, locale_string)
for locale_string in authors_by_locale.keys()
]
language_names.sort()
for (language_name, locale) in language_names:
print("%s - %s" % (language_name, locale))
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
| Sort languages by English name | Sort languages by English name
| Python | bsd-3-clause | zerolab/wagtail,thenewguy/wagtail,timorieber/wagtail,kaedroho/wagtail,kurtrwall/wagtail,nilnvoid/wagtail,nutztherookie/wagtail,kurtw/wagtail,nimasmi/wagtail,torchbox/wagtail,zerolab/wagtail,timorieber/wagtail,FlipperPA/wagtail,rsalmaso/wagtail,zerolab/wagtail,kaedroho/wagtail,mixxorz/wagtail,mikedingjan/wagtail,rsalmaso/wagtail,kaedroho/wagtail,takeflight/wagtail,mikedingjan/wagtail,chrxr/wagtail,thenewguy/wagtail,mikedingjan/wagtail,timorieber/wagtail,hamsterbacke23/wagtail,wagtail/wagtail,kurtw/wagtail,iansprice/wagtail,takeflight/wagtail,chrxr/wagtail,nilnvoid/wagtail,mixxorz/wagtail,torchbox/wagtail,thenewguy/wagtail,zerolab/wagtail,nutztherookie/wagtail,quru/wagtail,gasman/wagtail,kaedroho/wagtail,hamsterbacke23/wagtail,zerolab/wagtail,wagtail/wagtail,iansprice/wagtail,nealtodd/wagtail,takeflight/wagtail,nutztherookie/wagtail,mixxorz/wagtail,Toshakins/wagtail,nimasmi/wagtail,jnns/wagtail,kurtw/wagtail,hamsterbacke23/wagtail,nilnvoid/wagtail,kurtrwall/wagtail,nimasmi/wagtail,Toshakins/wagtail,kurtrwall/wagtail,quru/wagtail,kurtrwall/wagtail,wagtail/wagtail,gasman/wagtail,quru/wagtail,jnns/wagtail,torchbox/wagtail,nilnvoid/wagtail,rsalmaso/wagtail,jnns/wagtail,Toshakins/wagtail,thenewguy/wagtail,FlipperPA/wagtail,nimasmi/wagtail,FlipperPA/wagtail,nealtodd/wagtail,iansprice/wagtail,kurtw/wagtail,mixxorz/wagtail,chrxr/wagtail,chrxr/wagtail,takeflight/wagtail,wagtail/wagtail,nealtodd/wagtail,wagtail/wagtail,thenewguy/wagtail,iansprice/wagtail,rsalmaso/wagtail,nutztherookie/wagtail,FlipperPA/wagtail,rsalmaso/wagtail,gasman/wagtail,jnns/wagtail,nealtodd/wagtail,hamsterbacke23/wagtail,timorieber/wagtail,mixxorz/wagtail,Toshakins/wagtail,gasman/wagtail,torchbox/wagtail,gasman/wagtail,kaedroho/wagtail,mikedingjan/wagtail,quru/wagtail | import subprocess
import re
from collections import defaultdict
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
locales = sorted(authors_by_locale.keys())
for locale in locales:
print(locale)
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
Sort languages by English name | import subprocess
import re
from collections import defaultdict
from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
language_names = [
(Locale.parse(locale_string).english_name, locale_string)
for locale_string in authors_by_locale.keys()
]
language_names.sort()
for (language_name, locale) in language_names:
print("%s - %s" % (language_name, locale))
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
| <commit_before>import subprocess
import re
from collections import defaultdict
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
locales = sorted(authors_by_locale.keys())
for locale in locales:
print(locale)
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
<commit_msg>Sort languages by English name<commit_after> | import subprocess
import re
from collections import defaultdict
from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
language_names = [
(Locale.parse(locale_string).english_name, locale_string)
for locale_string in authors_by_locale.keys()
]
language_names.sort()
for (language_name, locale) in language_names:
print("%s - %s" % (language_name, locale))
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
| import subprocess
import re
from collections import defaultdict
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
locales = sorted(authors_by_locale.keys())
for locale in locales:
print(locale)
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
Sort languages by English nameimport subprocess
import re
from collections import defaultdict
from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
language_names = [
(Locale.parse(locale_string).english_name, locale_string)
for locale_string in authors_by_locale.keys()
]
language_names.sort()
for (language_name, locale) in language_names:
print("%s - %s" % (language_name, locale))
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
| <commit_before>import subprocess
import re
from collections import defaultdict
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
locales = sorted(authors_by_locale.keys())
for locale in locales:
print(locale)
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
<commit_msg>Sort languages by English name<commit_after>import subprocess
import re
from collections import defaultdict
from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string from filename
locale = re.search(r'locale/(\w+)/LC_MESSAGES', filename).group(1)
if locale == 'en':
continue
# read author list from each file
with file(filename) as f:
has_found_translators_heading = False
for line in f:
line = line.strip()
if line.startswith('#'):
if has_found_translators_heading:
author = re.match(r'\# (.*), [\d\-]+', line).group(1)
authors_by_locale[locale].add(author)
elif line.startswith('# Translators:'):
has_found_translators_heading = True
else:
if has_found_translators_heading:
break
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
language_names = [
(Locale.parse(locale_string).english_name, locale_string)
for locale_string in authors_by_locale.keys()
]
language_names.sort()
for (language_name, locale) in language_names:
print("%s - %s" % (language_name, locale))
print("-----")
for author in sorted(authors_by_locale[locale]):
print(author)
print('')
|
c974f7ed5f63278c24165d626e9e5dd63f18f7ae | tensorflow/python/debug/lib/op_callbacks_common.py | tensorflow/python/debug/lib/op_callbacks_common.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
)
| # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"LoopCond",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
# TPU-specific ops begin.
b"TPUReplicatedInput",
b"TPUReplicateMetadata",
b"TPUCompilationResult",
b"TPUReplicatedOutput",
b"ConfigureDistributedTPU",
)
| Support enable_check_numerics() and enable_dump_debug_info() callback on TPUs | [tfdbg] Support enable_check_numerics() and enable_dump_debug_info() callback on TPUs
- Skip a set of TPU compilation-specific ops from tfdbg's op callbacks.
PiperOrigin-RevId: 281836861
Change-Id: Ic7ff59a32eba26d5bb3ee2ac4f5f9166c78928c8
| Python | apache-2.0 | renyi533/tensorflow,karllessard/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,aldian/tensorflow,jhseu/tensorflow,renyi533/tensorflow,sarvex/tensorflow,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ppwwyyxx/tensorflow,tensorflow/tensorflow,aldian/tensorflow,xzturn/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,renyi533/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,cxxgtxy/tensorflow,xzturn/tensorflow,xzturn/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,frreiss/tensorflow-fred,xzturn/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,adit-chandra/tensorflow,frreiss/tensorflow-fred,ppwwyyxx/tensorflow,petewarden/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,arborh/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,renyi533/tensorflow,ppwwyyxx/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,ppwwyyxx/tensorflow,renyi533/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,aldian/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,jhseu/tensorflow,gunan/tensorflow,arborh/tensorflow,gunan/tensorflow,xzturn/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,annarev/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,yongtang/tensorflow,jhseu/tensorflow,annarev/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,cxxgtxy/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ppwwyyxx/tensorflow,yongtang/tensorflow,aldian/tensorflow,renyi533/tensorflow,davidzchen/tensorflow,annarev/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,xzturn/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,renyi533/tensorflow,cxxgtxy/tensorflow,aam-at/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,arborh/tensorflow,yongtang/tensorflow,aldian/tensorflow,cxxgtxy/tensorflow,gunan/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,adit-chandra/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,aam-at/tensorflow,jhseu/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,adit-chandra/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,jhseu/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,jhseu/tensorflow,freedomtan/tensorflow,karllessard/tensorflow,arborh/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,frreiss/tensorflow-fred,arborh/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,Intel-tensorflow/tensorflow,freedomtan/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,gunan/tensorflow,arborh/tensorflow,davidzchen/tensorflow,sarvex/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,arborh/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,arborh/tensorflow,tensorflow/tensorflow,gunan/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,davidzchen/tensorflow,Intel-tensorflow/tensorflow,arborh/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ppwwyyxx/tensorflow,yongtang/tensorflow,petewarden/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,davidzchen/tensorflow,arborh/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,jhseu/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ppwwyyxx/tensorflow,annarev/tensorflow,aam-at/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,jhseu/tensorflow,Intel-Corporation/tensorflow,sarvex/tensorflow,petewarden/tensorflow,xzturn/tensorflow,aldian/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,renyi533/tensorflow,ppwwyyxx/tensorflow,renyi533/tensorflow,annarev/tensorflow,gunan/tensorflow,jhseu/tensorflow,gunan/tensorflow,aldian/tensorflow,ppwwyyxx/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,adit-chandra/tensorflow,jhseu/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,adit-chandra/tensorflow,jhseu/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,renyi533/tensorflow,gunan/tensorflow,xzturn/tensorflow,renyi533/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,xzturn/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,adit-chandra/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,jhseu/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aam-at/tensorflow,sarvex/tensorflow,arborh/tensorflow,sarvex/tensorflow,ppwwyyxx/tensorflow,Intel-tensorflow/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gunan/tensorflow,annarev/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,annarev/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ppwwyyxx/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,arborh/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
)
[tfdbg] Support enable_check_numerics() and enable_dump_debug_info() callback on TPUs
- Skip a set of TPU compilation-specific ops from tfdbg's op callbacks.
PiperOrigin-RevId: 281836861
Change-Id: Ic7ff59a32eba26d5bb3ee2ac4f5f9166c78928c8 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"LoopCond",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
# TPU-specific ops begin.
b"TPUReplicatedInput",
b"TPUReplicateMetadata",
b"TPUCompilationResult",
b"TPUReplicatedOutput",
b"ConfigureDistributedTPU",
)
| <commit_before># Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
)
<commit_msg>[tfdbg] Support enable_check_numerics() and enable_dump_debug_info() callback on TPUs
- Skip a set of TPU compilation-specific ops from tfdbg's op callbacks.
PiperOrigin-RevId: 281836861
Change-Id: Ic7ff59a32eba26d5bb3ee2ac4f5f9166c78928c8<commit_after> | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"LoopCond",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
# TPU-specific ops begin.
b"TPUReplicatedInput",
b"TPUReplicateMetadata",
b"TPUCompilationResult",
b"TPUReplicatedOutput",
b"ConfigureDistributedTPU",
)
| # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
)
[tfdbg] Support enable_check_numerics() and enable_dump_debug_info() callback on TPUs
- Skip a set of TPU compilation-specific ops from tfdbg's op callbacks.
PiperOrigin-RevId: 281836861
Change-Id: Ic7ff59a32eba26d5bb3ee2ac4f5f9166c78928c8# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"LoopCond",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
# TPU-specific ops begin.
b"TPUReplicatedInput",
b"TPUReplicateMetadata",
b"TPUCompilationResult",
b"TPUReplicatedOutput",
b"ConfigureDistributedTPU",
)
| <commit_before># Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
)
<commit_msg>[tfdbg] Support enable_check_numerics() and enable_dump_debug_info() callback on TPUs
- Skip a set of TPU compilation-specific ops from tfdbg's op callbacks.
PiperOrigin-RevId: 281836861
Change-Id: Ic7ff59a32eba26d5bb3ee2ac4f5f9166c78928c8<commit_after># Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Common utilities and settings used by tfdbg v2's op callbacks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# The ops that are skipped by tfdbg v2's op callbacks.
# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf")
# and ops that wrap nested tf.function calls.
OP_CALLBACK_SKIP_OPS = (
# TODO(b/139668453): The following skipped ops are related to a limitation
# in the op callback.
b"Enter",
b"Exit",
b"Identity",
b"If",
b"LoopCond",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
# TPU-specific ops begin.
b"TPUReplicatedInput",
b"TPUReplicateMetadata",
b"TPUCompilationResult",
b"TPUReplicatedOutput",
b"ConfigureDistributedTPU",
)
|
a92121cfdbb94d36d021fb8d1386031829ee86a2 | patterns/solid.py | patterns/solid.py | import blinkypattern
class Solid(blinkypattern.BlinkyPattern):
def __init__(self, blinkytape, solid_color):
super(Solid, self).__init__(blinkytape)
self._pixels = [solid_color] * self._blinkytape.pixel_count
def setup(self):
super(Solid, self).setup()
self._blinkytape.set_pixels(self._pixels)
self._blinkytape.update()
| class Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
| Update Solid pattern for refactor | Update Solid pattern for refactor
| Python | mit | jonspeicher/blinkyfun | import blinkypattern
class Solid(blinkypattern.BlinkyPattern):
def __init__(self, blinkytape, solid_color):
super(Solid, self).__init__(blinkytape)
self._pixels = [solid_color] * self._blinkytape.pixel_count
def setup(self):
super(Solid, self).setup()
self._blinkytape.set_pixels(self._pixels)
self._blinkytape.update()
Update Solid pattern for refactor | class Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
| <commit_before>import blinkypattern
class Solid(blinkypattern.BlinkyPattern):
def __init__(self, blinkytape, solid_color):
super(Solid, self).__init__(blinkytape)
self._pixels = [solid_color] * self._blinkytape.pixel_count
def setup(self):
super(Solid, self).setup()
self._blinkytape.set_pixels(self._pixels)
self._blinkytape.update()
<commit_msg>Update Solid pattern for refactor<commit_after> | class Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
| import blinkypattern
class Solid(blinkypattern.BlinkyPattern):
def __init__(self, blinkytape, solid_color):
super(Solid, self).__init__(blinkytape)
self._pixels = [solid_color] * self._blinkytape.pixel_count
def setup(self):
super(Solid, self).setup()
self._blinkytape.set_pixels(self._pixels)
self._blinkytape.update()
Update Solid pattern for refactorclass Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
| <commit_before>import blinkypattern
class Solid(blinkypattern.BlinkyPattern):
def __init__(self, blinkytape, solid_color):
super(Solid, self).__init__(blinkytape)
self._pixels = [solid_color] * self._blinkytape.pixel_count
def setup(self):
super(Solid, self).setup()
self._blinkytape.set_pixels(self._pixels)
self._blinkytape.update()
<commit_msg>Update Solid pattern for refactor<commit_after>class Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
|
c0ce65ccd7db7e7f34e9d6172f7179cf9ee16ef2 | chandra_aca/tests/test_dark_scale.py | chandra_aca/tests/test_dark_scale.py | import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| import numpy as np
from ..dark_model import dark_temp_scale, get_warm_fracs
def test_get_warm_fracs():
exp = {(100, '2020:001', -11): 341312,
(100, '2017:001', -11): 278627,
(100, '2020:001', -15): 250546,
(100, '2017:001', -15): 200786,
(1000, '2017:001', -11): 1703,
(1000, '2017:001', -15): 558,
(1000, '2020:001', -15): 798,
(1000, '2020:001', -11): 2436}
warmpixs = {}
for warm_threshold in (100, 1000):
for date in ('2017:001', '2020:001'):
for T_ccd in (-11, -15):
key = (warm_threshold, date, T_ccd)
warmpixs[key] = int(get_warm_fracs(*key) * 1024 ** 2)
for key in warmpixs:
assert np.allclose(warmpixs[key], exp[key], rtol=1e-5, atol=1)
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| Add regression test of warm fractions calculation | Add regression test of warm fractions calculation
| Python | bsd-2-clause | sot/chandra_aca,sot/chandra_aca | import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
Add regression test of warm fractions calculation | import numpy as np
from ..dark_model import dark_temp_scale, get_warm_fracs
def test_get_warm_fracs():
exp = {(100, '2020:001', -11): 341312,
(100, '2017:001', -11): 278627,
(100, '2020:001', -15): 250546,
(100, '2017:001', -15): 200786,
(1000, '2017:001', -11): 1703,
(1000, '2017:001', -15): 558,
(1000, '2020:001', -15): 798,
(1000, '2020:001', -11): 2436}
warmpixs = {}
for warm_threshold in (100, 1000):
for date in ('2017:001', '2020:001'):
for T_ccd in (-11, -15):
key = (warm_threshold, date, T_ccd)
warmpixs[key] = int(get_warm_fracs(*key) * 1024 ** 2)
for key in warmpixs:
assert np.allclose(warmpixs[key], exp[key], rtol=1e-5, atol=1)
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| <commit_before>import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
<commit_msg>Add regression test of warm fractions calculation<commit_after> | import numpy as np
from ..dark_model import dark_temp_scale, get_warm_fracs
def test_get_warm_fracs():
exp = {(100, '2020:001', -11): 341312,
(100, '2017:001', -11): 278627,
(100, '2020:001', -15): 250546,
(100, '2017:001', -15): 200786,
(1000, '2017:001', -11): 1703,
(1000, '2017:001', -15): 558,
(1000, '2020:001', -15): 798,
(1000, '2020:001', -11): 2436}
warmpixs = {}
for warm_threshold in (100, 1000):
for date in ('2017:001', '2020:001'):
for T_ccd in (-11, -15):
key = (warm_threshold, date, T_ccd)
warmpixs[key] = int(get_warm_fracs(*key) * 1024 ** 2)
for key in warmpixs:
assert np.allclose(warmpixs[key], exp[key], rtol=1e-5, atol=1)
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
Add regression test of warm fractions calculationimport numpy as np
from ..dark_model import dark_temp_scale, get_warm_fracs
def test_get_warm_fracs():
exp = {(100, '2020:001', -11): 341312,
(100, '2017:001', -11): 278627,
(100, '2020:001', -15): 250546,
(100, '2017:001', -15): 200786,
(1000, '2017:001', -11): 1703,
(1000, '2017:001', -15): 558,
(1000, '2020:001', -15): 798,
(1000, '2020:001', -11): 2436}
warmpixs = {}
for warm_threshold in (100, 1000):
for date in ('2017:001', '2020:001'):
for T_ccd in (-11, -15):
key = (warm_threshold, date, T_ccd)
warmpixs[key] = int(get_warm_fracs(*key) * 1024 ** 2)
for key in warmpixs:
assert np.allclose(warmpixs[key], exp[key], rtol=1e-5, atol=1)
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| <commit_before>import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
<commit_msg>Add regression test of warm fractions calculation<commit_after>import numpy as np
from ..dark_model import dark_temp_scale, get_warm_fracs
def test_get_warm_fracs():
exp = {(100, '2020:001', -11): 341312,
(100, '2017:001', -11): 278627,
(100, '2020:001', -15): 250546,
(100, '2017:001', -15): 200786,
(1000, '2017:001', -11): 1703,
(1000, '2017:001', -15): 558,
(1000, '2020:001', -15): 798,
(1000, '2020:001', -11): 2436}
warmpixs = {}
for warm_threshold in (100, 1000):
for date in ('2017:001', '2020:001'):
for T_ccd in (-11, -15):
key = (warm_threshold, date, T_ccd)
warmpixs[key] = int(get_warm_fracs(*key) * 1024 ** 2)
for key in warmpixs:
assert np.allclose(warmpixs[key], exp[key], rtol=1e-5, atol=1)
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
|
28d5e53da8a92985fa9b1b4a532467dd343cc4b5 | apilisk/junit_formatter.py | apilisk/junit_formatter.py | import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
str(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
self.testcases[str(case["testcase_id"])]["name"],
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name="Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
TestSuite.to_file(f, [self.test_suite], prettyprint=True)
| # -*- coding: utf-8 -*-
import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
unicode(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
u"{0}".format(self.testcases[str(case["testcase_id"])]["name"]),
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name=u"Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
f.write(
TestSuite.to_xml_string(
[self.test_suite], prettyprint=True, encoding="utf-8"
).encode("utf-8")
)
| Fix junit utf-8 output to file | Fix junit utf-8 output to file
| Python | mit | apiwatcher/apilisk | import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
str(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
self.testcases[str(case["testcase_id"])]["name"],
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name="Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
TestSuite.to_file(f, [self.test_suite], prettyprint=True)
Fix junit utf-8 output to file | # -*- coding: utf-8 -*-
import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
unicode(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
u"{0}".format(self.testcases[str(case["testcase_id"])]["name"]),
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name=u"Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
f.write(
TestSuite.to_xml_string(
[self.test_suite], prettyprint=True, encoding="utf-8"
).encode("utf-8")
)
| <commit_before>import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
str(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
self.testcases[str(case["testcase_id"])]["name"],
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name="Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
TestSuite.to_file(f, [self.test_suite], prettyprint=True)
<commit_msg>Fix junit utf-8 output to file<commit_after> | # -*- coding: utf-8 -*-
import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
unicode(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
u"{0}".format(self.testcases[str(case["testcase_id"])]["name"]),
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name=u"Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
f.write(
TestSuite.to_xml_string(
[self.test_suite], prettyprint=True, encoding="utf-8"
).encode("utf-8")
)
| import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
str(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
self.testcases[str(case["testcase_id"])]["name"],
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name="Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
TestSuite.to_file(f, [self.test_suite], prettyprint=True)
Fix junit utf-8 output to file# -*- coding: utf-8 -*-
import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
unicode(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
u"{0}".format(self.testcases[str(case["testcase_id"])]["name"]),
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name=u"Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
f.write(
TestSuite.to_xml_string(
[self.test_suite], prettyprint=True, encoding="utf-8"
).encode("utf-8")
)
| <commit_before>import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
str(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
self.testcases[str(case["testcase_id"])]["name"],
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name="Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
TestSuite.to_file(f, [self.test_suite], prettyprint=True)
<commit_msg>Fix junit utf-8 output to file<commit_after># -*- coding: utf-8 -*-
import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
unicode(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for case in project_result["results"]:
tc = TestCase(
u"{0}".format(self.testcases[str(case["testcase_id"])]["name"]),
elapsed_sec=case["duration_sec"]
)
if case["status"] == "failed":
# Last error and first error message
tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"])
test_cases.append(tc)
self.test_suite = TestSuite(
name=u"Project {0}".format(project_cfg["project_name"]),
test_cases=test_cases
)
def to_file(self, filename):
"""
Output project results to specified filename
"""
with open(filename, 'w') as f:
f.write(
TestSuite.to_xml_string(
[self.test_suite], prettyprint=True, encoding="utf-8"
).encode("utf-8")
)
|
f74ce9c077054119c04ab65fc0afa4c137204770 | comics/comics/basicinstructions.py | comics/comics/basicinstructions.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src('img[src*="/storage/"][src*=".gif"]')
title = entry.title
return CrawlerImage(url, title)
| from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src("img")
title = entry.title
return CrawlerImage(url, title)
| Update "Basic Instructions" after feed change | Update "Basic Instructions" after feed change
| Python | agpl-3.0 | datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src('img[src*="/storage/"][src*=".gif"]')
title = entry.title
return CrawlerImage(url, title)
Update "Basic Instructions" after feed change | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src("img")
title = entry.title
return CrawlerImage(url, title)
| <commit_before>from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src('img[src*="/storage/"][src*=".gif"]')
title = entry.title
return CrawlerImage(url, title)
<commit_msg>Update "Basic Instructions" after feed change<commit_after> | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src("img")
title = entry.title
return CrawlerImage(url, title)
| from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src('img[src*="/storage/"][src*=".gif"]')
title = entry.title
return CrawlerImage(url, title)
Update "Basic Instructions" after feed changefrom comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src("img")
title = entry.title
return CrawlerImage(url, title)
| <commit_before>from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src('img[src*="/storage/"][src*=".gif"]')
title = entry.title
return CrawlerImage(url, title)
<commit_msg>Update "Basic Instructions" after feed change<commit_after>from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(CrawlerBase):
history_capable_days = 100
schedule = "Tu,Th,Su"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed(
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
url = entry.summary.src("img")
title = entry.title
return CrawlerImage(url, title)
|
7c847513155b1bdc29c04a10dbfd2efd669d1507 | async/spam_echo_clients.py | async/spam_echo_clients.py | import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
| import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
data = sock.recv(1024)
if data != msg:
print('Error! No reply to', sock.getsockname())
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
| Add reply checks to the spam client too | Add reply checks to the spam client too
| Python | unlicense | eliben/python3-samples | import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
Add reply checks to the spam client too | import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
data = sock.recv(1024)
if data != msg:
print('Error! No reply to', sock.getsockname())
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
| <commit_before>import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
<commit_msg>Add reply checks to the spam client too<commit_after> | import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
data = sock.recv(1024)
if data != msg:
print('Error! No reply to', sock.getsockname())
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
| import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
Add reply checks to the spam client tooimport socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
data = sock.recv(1024)
if data != msg:
print('Error! No reply to', sock.getsockname())
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
| <commit_before>import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
<commit_msg>Add reply checks to the spam client too<commit_after>import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
sock.send(msg)
time.sleep(0.1)
for sock in sockets:
data = sock.recv(1024)
if data != msg:
print('Error! No reply to', sock.getsockname())
time.sleep(0.1)
for sock in sockets:
sock.close()
time.sleep(0.1)
|
8ffc8cabd5a2ba20997337c101018f3c25faef4e | onadata/apps/fsforms/management/commands/save_version_in_finstance.py | onadata/apps/fsforms/management/commands/save_version_in_finstance.py | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
instance.save()
else:
stop = True
offset += batchsize | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
from onadata.apps.logger.models import Instance
from onadata.settings.local_settings import XML_VERSION_MAX_ITER
import re
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
n = XML_VERSION_MAX_ITER
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
i = Instance.objects.get(fieldsight_instance=instance)
xml = i.xml
pattern = re.compile('version="(.*)">')
m = pattern.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
for i in range(n, 0, -1):
p = re.compile('<_version__00{0}>(.*)</_version__00{1}>'.format(i, i))
m = p.search(instance)
if m:
instance.version = m.group(1)
instance.save()
continue
p = re.compile('<_version_>(.*)</_version_>')
m = p.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
p1 = re.compile('<__version__>(.*)</__version__>')
m1 = p1.search(xml)
if m1:
instance.version = m.group(1)
instance.save()
continue
else:
stop = True
offset += batchsize | Update command to save version in finstance | Update command to save version in finstance
| Python | bsd-2-clause | awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
instance.save()
else:
stop = True
offset += batchsizeUpdate command to save version in finstance | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
from onadata.apps.logger.models import Instance
from onadata.settings.local_settings import XML_VERSION_MAX_ITER
import re
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
n = XML_VERSION_MAX_ITER
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
i = Instance.objects.get(fieldsight_instance=instance)
xml = i.xml
pattern = re.compile('version="(.*)">')
m = pattern.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
for i in range(n, 0, -1):
p = re.compile('<_version__00{0}>(.*)</_version__00{1}>'.format(i, i))
m = p.search(instance)
if m:
instance.version = m.group(1)
instance.save()
continue
p = re.compile('<_version_>(.*)</_version_>')
m = p.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
p1 = re.compile('<__version__>(.*)</__version__>')
m1 = p1.search(xml)
if m1:
instance.version = m.group(1)
instance.save()
continue
else:
stop = True
offset += batchsize | <commit_before>from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
instance.save()
else:
stop = True
offset += batchsize<commit_msg>Update command to save version in finstance<commit_after> | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
from onadata.apps.logger.models import Instance
from onadata.settings.local_settings import XML_VERSION_MAX_ITER
import re
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
n = XML_VERSION_MAX_ITER
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
i = Instance.objects.get(fieldsight_instance=instance)
xml = i.xml
pattern = re.compile('version="(.*)">')
m = pattern.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
for i in range(n, 0, -1):
p = re.compile('<_version__00{0}>(.*)</_version__00{1}>'.format(i, i))
m = p.search(instance)
if m:
instance.version = m.group(1)
instance.save()
continue
p = re.compile('<_version_>(.*)</_version_>')
m = p.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
p1 = re.compile('<__version__>(.*)</__version__>')
m1 = p1.search(xml)
if m1:
instance.version = m.group(1)
instance.save()
continue
else:
stop = True
offset += batchsize | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
instance.save()
else:
stop = True
offset += batchsizeUpdate command to save version in finstancefrom django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
from onadata.apps.logger.models import Instance
from onadata.settings.local_settings import XML_VERSION_MAX_ITER
import re
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
n = XML_VERSION_MAX_ITER
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
i = Instance.objects.get(fieldsight_instance=instance)
xml = i.xml
pattern = re.compile('version="(.*)">')
m = pattern.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
for i in range(n, 0, -1):
p = re.compile('<_version__00{0}>(.*)</_version__00{1}>'.format(i, i))
m = p.search(instance)
if m:
instance.version = m.group(1)
instance.save()
continue
p = re.compile('<_version_>(.*)</_version_>')
m = p.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
p1 = re.compile('<__version__>(.*)</__version__>')
m1 = p1.search(xml)
if m1:
instance.version = m.group(1)
instance.save()
continue
else:
stop = True
offset += batchsize | <commit_before>from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
instance.save()
else:
stop = True
offset += batchsize<commit_msg>Update command to save version in finstance<commit_after>from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
from onadata.apps.logger.models import Instance
from onadata.settings.local_settings import XML_VERSION_MAX_ITER
import re
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
# xls_directory = "/home/xls"
batchsize = options.get("batchsize", 100)
username = options['username']
stop = False
offset = 0
while stop is not True:
n = XML_VERSION_MAX_ITER
limit = offset + batchsize
instances = FInstance.objects.filter(instance__xform__user__username=username, version='')[offset:limit]
inst = list(instances)
if instances:
self.stdout.write("Updating instances from #{} to #{}\n".format(
inst[0].id,
inst[-1].id))
for instance in instances:
i = Instance.objects.get(fieldsight_instance=instance)
xml = i.xml
pattern = re.compile('version="(.*)">')
m = pattern.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
for i in range(n, 0, -1):
p = re.compile('<_version__00{0}>(.*)</_version__00{1}>'.format(i, i))
m = p.search(instance)
if m:
instance.version = m.group(1)
instance.save()
continue
p = re.compile('<_version_>(.*)</_version_>')
m = p.search(xml)
if m:
instance.version = m.group(1)
instance.save()
continue
p1 = re.compile('<__version__>(.*)</__version__>')
m1 = p1.search(xml)
if m1:
instance.version = m.group(1)
instance.save()
continue
else:
stop = True
offset += batchsize |
296b343699a2a37c661937f60d854f6fd4e53e69 | src/waldur_mastermind/common/serializers.py | src/waldur_mastermind/common/serializers.py | from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
fields.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
| from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
field.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
| Fix typo in options serializer. | Fix typo in options serializer.
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur | from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
fields.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
Fix typo in options serializer. | from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
field.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
| <commit_before>from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
fields.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
<commit_msg>Fix typo in options serializer.<commit_after> | from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
field.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
| from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
fields.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
Fix typo in options serializer.from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
field.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
| <commit_before>from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
fields.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
<commit_msg>Fix typo in options serializer.<commit_after>from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
field = serializers.IntegerField()
elif field_type == 'money':
field = serializers.IntegerField()
elif field_type == 'boolean':
field = serializers.BooleanField()
else:
field = serializers.CharField()
default_value = option.get('default')
if default_value:
field.default = default_value
if 'min' in option:
field.min_value = option.get('min')
if 'max' in option:
field.max_value = option.get('max')
if 'choices' in option:
field.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label')
field.help_text = option.get('help_text')
fields[name] = field
serializer_class = type(b'AttributesSerializer', (serializers.Serializer,), fields)
serializer = serializer_class(data=attributes)
serializer.is_valid(raise_exception=True)
|
ff6fbf0821112a0144fbe2d14768cd7a03907438 | rst2pdf/utils.py | rst2pdf/utils.py | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]), int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
| # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(adjustUnits(tokens[1]),
adjustUnits(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
| Add unit support for spacers | Add unit support for spacers
| Python | mit | thomaspurchas/rst2pdf,thomaspurchas/rst2pdf | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]), int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
Add unit support for spacers | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(adjustUnits(tokens[1]),
adjustUnits(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
| <commit_before># -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]), int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
<commit_msg>Add unit support for spacers<commit_after> | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(adjustUnits(tokens[1]),
adjustUnits(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
| # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]), int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
Add unit support for spacers# -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(adjustUnits(tokens[1]),
adjustUnits(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
| <commit_before># -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]), int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
<commit_msg>Add unit support for spacers<commit_after># -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
"""
elements = []
lines = data.splitlines()
for line in lines:
lexer = shlex.shlex(line)
lexer.whitespace += ','
tokens = list(lexer)
command = tokens[0]
if command == 'PageBreak':
if len(tokens) == 1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(adjustUnits(tokens[1]),
adjustUnits(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now:
# def depth(node):
# if node.parent == None:
# return 0
# else:
# return 1 + depth(node.parent)
|
ead5a941efd8b8a41b81f679ad3e6c98e2248409 | dipy/io/tests/test_dicomreaders.py | dipy/io/tests/test_dicomreaders.py | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_equal(aff.shape, (4,4))
yield assert_equal(bs.shape, (2,))
yield assert_equal(gs.shape, (2,3))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
| """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
EXPECTED_PARAMS,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_array_almost_equal(aff, EXPECTED_AFFINE)
yield assert_array_almost_equal(bs, (0, EXPECTED_PARAMS[0]))
yield assert_array_almost_equal(gs,
(np.zeros((3,)) + np.nan,
EXPECTED_PARAMS[1]))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
| TEST - added more explicit tests for directory read | TEST - added more explicit tests for directory read
| Python | bsd-3-clause | FrancoisRheaultUS/dipy,sinkpoint/dipy,StongeEtienne/dipy,samuelstjean/dipy,rfdougherty/dipy,demianw/dipy,samuelstjean/dipy,JohnGriffiths/dipy,mdesco/dipy,rfdougherty/dipy,maurozucchelli/dipy,demianw/dipy,jyeatman/dipy,oesteban/dipy,beni55/dipy,StongeEtienne/dipy,mdesco/dipy,matthieudumont/dipy,FrancoisRheaultUS/dipy,jyeatman/dipy,sinkpoint/dipy,villalonreina/dipy,maurozucchelli/dipy,samuelstjean/dipy,Messaoud-Boudjada/dipy,Messaoud-Boudjada/dipy,maurozucchelli/dipy,matthieudumont/dipy,nilgoyyou/dipy,nilgoyyou/dipy,JohnGriffiths/dipy,oesteban/dipy,villalonreina/dipy,beni55/dipy | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_equal(aff.shape, (4,4))
yield assert_equal(bs.shape, (2,))
yield assert_equal(gs.shape, (2,3))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
TEST - added more explicit tests for directory read | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
EXPECTED_PARAMS,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_array_almost_equal(aff, EXPECTED_AFFINE)
yield assert_array_almost_equal(bs, (0, EXPECTED_PARAMS[0]))
yield assert_array_almost_equal(gs,
(np.zeros((3,)) + np.nan,
EXPECTED_PARAMS[1]))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
| <commit_before>""" Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_equal(aff.shape, (4,4))
yield assert_equal(bs.shape, (2,))
yield assert_equal(gs.shape, (2,3))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
<commit_msg>TEST - added more explicit tests for directory read<commit_after> | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
EXPECTED_PARAMS,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_array_almost_equal(aff, EXPECTED_AFFINE)
yield assert_array_almost_equal(bs, (0, EXPECTED_PARAMS[0]))
yield assert_array_almost_equal(gs,
(np.zeros((3,)) + np.nan,
EXPECTED_PARAMS[1]))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
| """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_equal(aff.shape, (4,4))
yield assert_equal(bs.shape, (2,))
yield assert_equal(gs.shape, (2,3))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
TEST - added more explicit tests for directory read""" Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
EXPECTED_PARAMS,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_array_almost_equal(aff, EXPECTED_AFFINE)
yield assert_array_almost_equal(bs, (0, EXPECTED_PARAMS[0]))
yield assert_array_almost_equal(gs,
(np.zeros((3,)) + np.nan,
EXPECTED_PARAMS[1]))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
| <commit_before>""" Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_equal(aff.shape, (4,4))
yield assert_equal(bs.shape, (2,))
yield assert_equal(gs.shape, (2,3))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
<commit_msg>TEST - added more explicit tests for directory read<commit_after>""" Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
EXPECTED_PARAMS,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing import parametric, IO_DATA_PATH
@parametric
def test_read_dwi():
img = didr.mosaic_to_nii(DATA)
arr = img.get_data()
yield assert_equal(arr.shape, (128,128,48))
yield assert_array_almost_equal(img.get_affine(), EXPECTED_AFFINE)
@parametric
def test_read_dwis():
data, aff, bs, gs = didr.read_mosaic_dwi_dir(IO_DATA_PATH, '*.dcm.gz')
yield assert_equal(data.ndim, 4)
yield assert_array_almost_equal(aff, EXPECTED_AFFINE)
yield assert_array_almost_equal(bs, (0, EXPECTED_PARAMS[0]))
yield assert_array_almost_equal(gs,
(np.zeros((3,)) + np.nan,
EXPECTED_PARAMS[1]))
yield assert_raises(IOError, didr.read_mosaic_dwi_dir, 'improbable')
|
697bf0c23786794e35b0b9f72c878bb762d296b9 | benches/cprofile_pyproj.py | benches/cprofile_pyproj.py | import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
osgb36 = Proj(init='epsg:27700')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
| import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
# osgb36 = Proj(init='epsg:27700')
osgb36 = Proj('+init=EPSG:27700 +nadgrids=OSTN02_NTv2.gsb')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
| Use NTv2 transform for Pyproj | Use NTv2 transform for Pyproj
| Python | mit | urschrei/lonlat_bng,urschrei/rust_bng,urschrei/lonlat_bng,urschrei/rust_bng,urschrei/lonlat_bng | import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
osgb36 = Proj(init='epsg:27700')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
Use NTv2 transform for Pyproj | import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
# osgb36 = Proj(init='epsg:27700')
osgb36 = Proj('+init=EPSG:27700 +nadgrids=OSTN02_NTv2.gsb')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
| <commit_before>import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
osgb36 = Proj(init='epsg:27700')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
<commit_msg>Use NTv2 transform for Pyproj<commit_after> | import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
# osgb36 = Proj(init='epsg:27700')
osgb36 = Proj('+init=EPSG:27700 +nadgrids=OSTN02_NTv2.gsb')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
| import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
osgb36 = Proj(init='epsg:27700')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
Use NTv2 transform for Pyprojimport numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
# osgb36 = Proj(init='epsg:27700')
osgb36 = Proj('+init=EPSG:27700 +nadgrids=OSTN02_NTv2.gsb')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
| <commit_before>import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
osgb36 = Proj(init='epsg:27700')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
<commit_msg>Use NTv2 transform for Pyproj<commit_after>import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
# osgb36 = Proj(init='epsg:27700')
osgb36 = Proj('+init=EPSG:27700 +nadgrids=OSTN02_NTv2.gsb')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random.uniform(S, N, [num_coords])
if __name__ == "__main__":
for x in xrange(50):
transform(wgs84, osgb36, lon_ls, lat_ls)
|
98f4ca1cdf5b5f68a3d8e785ec50756653444843 | pyconcz_2016/speakers/views.py | pyconcz_2016/speakers/views.py | from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0207', then=Value(2)),
When(room='d0206', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
| from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0206', then=Value(2)),
When(room='d0207', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
| Fix sorting of rooms in schedule | Fix sorting of rooms in schedule
| Python | mit | pyvec/cz.pycon.org-2016,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2016,pyvec/cz.pycon.org-2016,pyvec/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2017,pyvec/cz.pycon.org-2017 | from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0207', then=Value(2)),
When(room='d0206', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
Fix sorting of rooms in schedule | from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0206', then=Value(2)),
When(room='d0207', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
| <commit_before>from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0207', then=Value(2)),
When(room='d0206', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
<commit_msg>Fix sorting of rooms in schedule<commit_after> | from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0206', then=Value(2)),
When(room='d0207', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
| from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0207', then=Value(2)),
When(room='d0206', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
Fix sorting of rooms in schedulefrom django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0206', then=Value(2)),
When(room='d0207', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
| <commit_before>from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0207', then=Value(2)),
When(room='d0206', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
<commit_msg>Fix sorting of rooms in schedule<commit_after>from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(request, type):
speakers = (Speaker.objects.all()
.exclude(**{type: None})
.prefetch_related(type)
.order_by('full_name'))
return TemplateResponse(
request,
template='speakers/{}_list.html'.format(type),
context={'speakers': speakers}
)
def talks_timeline(request):
talks = (Slot.objects.all()
.select_related('talk')
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
When(room='d0206', then=Value(2)),
When(room='d0207', then=Value(3)),
default=Value(0),
output_field=IntegerField()
))
.order_by('date', 'order'))
return TemplateResponse(
request,
template='speakers/talks_timeline.html',
context={
'talks': talks
}
)
|
1fce663e37823d985d00d1700aba5e067157b789 | profiles/tests.py | profiles/tests.py | from django.contrib.auth.models import User
from django.test import TestCase
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
| from django.contrib.auth.models import User
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
@classmethod
def _prepare(cls, create, **kwargs):
password = kwargs.pop('password', 'password')
user = super(UserFactory, cls)._prepare(create=False, **kwargs)
user.set_password(password)
user.raw_password = password
if create:
user.save()
return user
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
| Add password handling to default factory. | Add password handling to default factory.
| Python | bsd-2-clause | incuna/django-extensible-profiles | from django.contrib.auth.models import User
from django.test import TestCase
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
Add password handling to default factory. | from django.contrib.auth.models import User
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
@classmethod
def _prepare(cls, create, **kwargs):
password = kwargs.pop('password', 'password')
user = super(UserFactory, cls)._prepare(create=False, **kwargs)
user.set_password(password)
user.raw_password = password
if create:
user.save()
return user
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
| <commit_before>from django.contrib.auth.models import User
from django.test import TestCase
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
<commit_msg>Add password handling to default factory.<commit_after> | from django.contrib.auth.models import User
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
@classmethod
def _prepare(cls, create, **kwargs):
password = kwargs.pop('password', 'password')
user = super(UserFactory, cls)._prepare(create=False, **kwargs)
user.set_password(password)
user.raw_password = password
if create:
user.save()
return user
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
| from django.contrib.auth.models import User
from django.test import TestCase
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
Add password handling to default factory.from django.contrib.auth.models import User
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
@classmethod
def _prepare(cls, create, **kwargs):
password = kwargs.pop('password', 'password')
user = super(UserFactory, cls)._prepare(create=False, **kwargs)
user.set_password(password)
user.raw_password = password
if create:
user.save()
return user
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
| <commit_before>from django.contrib.auth.models import User
from django.test import TestCase
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
<commit_msg>Add password handling to default factory.<commit_after>from django.contrib.auth.models import User
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower())
@classmethod
def _prepare(cls, create, **kwargs):
password = kwargs.pop('password', 'password')
user = super(UserFactory, cls)._prepare(create=False, **kwargs)
user.set_password(password)
user.raw_password = password
if create:
user.save()
return user
class ProfileFactory(UserFactory):
FACTORY_FOR = Profile
user_ptr = factory.SubFactory(UserFactory)
class ProfileUtils(object):
def generate_profile(self, **kwargs):
password = kwargs.pop('password', 'test')
profile = ProfileFactory.build(**kwargs)
profile.set_password(password)
profile.save()
return profile
def login(self, user=None, password='test'):
user = user or self.user
self.client.login(username=user.username, password=password)
|
d369b2ba967643d16c58fbad0be5b3a24785f602 | neurodsp/tests/test_spectral_utils.py | neurodsp/tests/test_spectral_utils.py | """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
| """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_trim_spectrogram():
freqs = np.array([5, 6, 7, 8])
times = np.array([0, 1, 2,])
pows = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
freqs_new, t_new, pows_new = trim_spectrogram(freqs, times, pows, f_range=[6, 8], t_range=[0,1])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(t_new, np.array([0, 1]))
assert_equal(pows_new, np.array([[4, 5], [7, 8], [10, 11]]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
| Add smoke test for trim_spectrogram | Add smoke test for trim_spectrogram
| Python | apache-2.0 | voytekresearch/neurodsp | """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
Add smoke test for trim_spectrogram | """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_trim_spectrogram():
freqs = np.array([5, 6, 7, 8])
times = np.array([0, 1, 2,])
pows = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
freqs_new, t_new, pows_new = trim_spectrogram(freqs, times, pows, f_range=[6, 8], t_range=[0,1])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(t_new, np.array([0, 1]))
assert_equal(pows_new, np.array([[4, 5], [7, 8], [10, 11]]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
| <commit_before>"""Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
<commit_msg>Add smoke test for trim_spectrogram<commit_after> | """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_trim_spectrogram():
freqs = np.array([5, 6, 7, 8])
times = np.array([0, 1, 2,])
pows = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
freqs_new, t_new, pows_new = trim_spectrogram(freqs, times, pows, f_range=[6, 8], t_range=[0,1])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(t_new, np.array([0, 1]))
assert_equal(pows_new, np.array([[4, 5], [7, 8], [10, 11]]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
| """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
Add smoke test for trim_spectrogram"""Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_trim_spectrogram():
freqs = np.array([5, 6, 7, 8])
times = np.array([0, 1, 2,])
pows = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
freqs_new, t_new, pows_new = trim_spectrogram(freqs, times, pows, f_range=[6, 8], t_range=[0,1])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(t_new, np.array([0, 1]))
assert_equal(pows_new, np.array([[4, 5], [7, 8], [10, 11]]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
| <commit_before>"""Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
<commit_msg>Add smoke test for trim_spectrogram<commit_after>"""Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
###################################################################################################
def test_trim_spectrum():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
freqs_new, pows_new = trim_spectrum(freqs, pows, [6, 8])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
def test_trim_spectrogram():
freqs = np.array([5, 6, 7, 8])
times = np.array([0, 1, 2,])
pows = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
freqs_new, t_new, pows_new = trim_spectrogram(freqs, times, pows, f_range=[6, 8], t_range=[0,1])
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(t_new, np.array([0, 1]))
assert_equal(pows_new, np.array([[4, 5], [7, 8], [10, 11]]))
def test_rotate_powerlaw():
freqs = np.array([5, 6, 7, 8, 9])
pows = np.array([1, 2, 3, 4, 5])
d_exp = 1
pows_new = rotate_powerlaw(freqs, pows, d_exp)
assert pows.shape == pows_new.shape
|
325256e7be56e5be951c98583ff79ca44ae14940 | server/server.py | server/server.py | from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True) | from flask import Flask, url_for , request
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
@app.route('/beat/<tone_id>' , methods=['POST'])
def api_change_beat(tone_id):
return 'Changed beat of ' + tone_id + ' to ' + request.form['value']
@app.route('/volume/<tone_id>' , methods=['POST'])
def api_change_volume(tone_id):
return 'Changed Volume of ' + tone_id + ' to ' + request.form['value']
if __name__ == '__main__':
app.run(debug=True) | Add methods to change the beat and volume of tone | Add methods to change the beat and volume of tone
| Python | artistic-2.0 | axay/eigen,axay/eigen | from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True)Add methods to change the beat and volume of tone | from flask import Flask, url_for , request
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
@app.route('/beat/<tone_id>' , methods=['POST'])
def api_change_beat(tone_id):
return 'Changed beat of ' + tone_id + ' to ' + request.form['value']
@app.route('/volume/<tone_id>' , methods=['POST'])
def api_change_volume(tone_id):
return 'Changed Volume of ' + tone_id + ' to ' + request.form['value']
if __name__ == '__main__':
app.run(debug=True) | <commit_before>from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True)<commit_msg>Add methods to change the beat and volume of tone<commit_after> | from flask import Flask, url_for , request
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
@app.route('/beat/<tone_id>' , methods=['POST'])
def api_change_beat(tone_id):
return 'Changed beat of ' + tone_id + ' to ' + request.form['value']
@app.route('/volume/<tone_id>' , methods=['POST'])
def api_change_volume(tone_id):
return 'Changed Volume of ' + tone_id + ' to ' + request.form['value']
if __name__ == '__main__':
app.run(debug=True) | from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True)Add methods to change the beat and volume of tonefrom flask import Flask, url_for , request
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
@app.route('/beat/<tone_id>' , methods=['POST'])
def api_change_beat(tone_id):
return 'Changed beat of ' + tone_id + ' to ' + request.form['value']
@app.route('/volume/<tone_id>' , methods=['POST'])
def api_change_volume(tone_id):
return 'Changed Volume of ' + tone_id + ' to ' + request.form['value']
if __name__ == '__main__':
app.run(debug=True) | <commit_before>from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True)<commit_msg>Add methods to change the beat and volume of tone<commit_after>from flask import Flask, url_for , request
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
@app.route('/beat/<tone_id>' , methods=['POST'])
def api_change_beat(tone_id):
return 'Changed beat of ' + tone_id + ' to ' + request.form['value']
@app.route('/volume/<tone_id>' , methods=['POST'])
def api_change_volume(tone_id):
return 'Changed Volume of ' + tone_id + ' to ' + request.form['value']
if __name__ == '__main__':
app.run(debug=True) |
5ac1dce80d0bfe4c52a2de5de4beefe235b8ad66 | post_process.py | post_process.py | #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
PICKLE = 'data.pkl'
def results():
with open(PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
net.save_params_to('/tmp/net.params')
| #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
NN_PICKLE = 'nn_data.pkl'
SVM_PICKLE = 'svm_data.pkl'
def results():
with open(NN_PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
grid_search.save_params_to('/tmp/grid_search.params')
net.save_params_to('/tmp/net.params')
with open(SVM_PICKLE, 'rb') as file:
mean_abs = pickle.load(file)
mean_sq = pickle.load(file)
median_abs = pickle.load(file)
r2 = pickle.load(file)
print mean_abs, mean_sq, median_abs, r2
| Load SVM pickle and print metrics | Load SVM pickle and print metrics
| Python | bsd-3-clause | BeckResearchLab/USP-inhibition,pearlphilip/USP-inhibition | #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
PICKLE = 'data.pkl'
def results():
with open(PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
net.save_params_to('/tmp/net.params')
Load SVM pickle and print metrics | #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
NN_PICKLE = 'nn_data.pkl'
SVM_PICKLE = 'svm_data.pkl'
def results():
with open(NN_PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
grid_search.save_params_to('/tmp/grid_search.params')
net.save_params_to('/tmp/net.params')
with open(SVM_PICKLE, 'rb') as file:
mean_abs = pickle.load(file)
mean_sq = pickle.load(file)
median_abs = pickle.load(file)
r2 = pickle.load(file)
print mean_abs, mean_sq, median_abs, r2
| <commit_before>#!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
PICKLE = 'data.pkl'
def results():
with open(PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
net.save_params_to('/tmp/net.params')
<commit_msg>Load SVM pickle and print metrics<commit_after> | #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
NN_PICKLE = 'nn_data.pkl'
SVM_PICKLE = 'svm_data.pkl'
def results():
with open(NN_PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
grid_search.save_params_to('/tmp/grid_search.params')
net.save_params_to('/tmp/net.params')
with open(SVM_PICKLE, 'rb') as file:
mean_abs = pickle.load(file)
mean_sq = pickle.load(file)
median_abs = pickle.load(file)
r2 = pickle.load(file)
print mean_abs, mean_sq, median_abs, r2
| #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
PICKLE = 'data.pkl'
def results():
with open(PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
net.save_params_to('/tmp/net.params')
Load SVM pickle and print metrics#!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
NN_PICKLE = 'nn_data.pkl'
SVM_PICKLE = 'svm_data.pkl'
def results():
with open(NN_PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
grid_search.save_params_to('/tmp/grid_search.params')
net.save_params_to('/tmp/net.params')
with open(SVM_PICKLE, 'rb') as file:
mean_abs = pickle.load(file)
mean_sq = pickle.load(file)
median_abs = pickle.load(file)
r2 = pickle.load(file)
print mean_abs, mean_sq, median_abs, r2
| <commit_before>#!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
PICKLE = 'data.pkl'
def results():
with open(PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
net.save_params_to('/tmp/net.params')
<commit_msg>Load SVM pickle and print metrics<commit_after>#!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
NN_PICKLE = 'nn_data.pkl'
SVM_PICKLE = 'svm_data.pkl'
def results():
with open(NN_PICKLE, 'rb') as file:
grid_search = pickle.load(file)
net = pickle.load(file)
print(grid_search.grid_scores_)
print(grid_search.best_estimator_)
print(grid_search.best_score_)
print(grid_search.best_params_)
grid_search.save_params_to('/tmp/grid_search.params')
net.save_params_to('/tmp/net.params')
with open(SVM_PICKLE, 'rb') as file:
mean_abs = pickle.load(file)
mean_sq = pickle.load(file)
median_abs = pickle.load(file)
r2 = pickle.load(file)
print mean_abs, mean_sq, median_abs, r2
|
9bd044297e1ef0f6383e39f376eec92885897406 | kansha/alembic/versions/2b0edcfa57b4_add_templates.py | kansha/alembic/versions/2b0edcfa57b4_add_templates.py | """Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
def downgrade():
op.drop_column('board', 'is_template')
| """Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
from alembic import op
import elixir
import sqlalchemy as sa
from nagare import database, local, security
from kansha.board.boardsmanager import BoardsManager
from kansha.security import SecurityManager
from kansha.services.dummyassetsmanager.dummyassetsmanager import DummyAssetsManager
from kansha.services.services_repository import ServicesRepository
from kansha.services.mail import DummyMailSender
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
# Setup models
elixir.metadata.bind = op.get_bind()
elixir.setup_all()
# Add column
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
# Create default template
local.request = local.Thread()
security.set_manager(SecurityManager(''))
services = ServicesRepository()
services.register('assets_manager', DummyAssetsManager())
services.register('mail_sender', DummyMailSender())
bm = BoardsManager('', '', '', None, services)
bm.create_template_todo()
def downgrade():
op.drop_column('board', 'is_template')
| Add default template creation into migration script | Add default template creation into migration script
| Python | bsd-3-clause | Net-ng/kansha,bcroq/kansha,bcroq/kansha,Net-ng/kansha,Net-ng/kansha,bcroq/kansha,Net-ng/kansha,bcroq/kansha | """Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
def downgrade():
op.drop_column('board', 'is_template')
Add default template creation into migration script | """Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
from alembic import op
import elixir
import sqlalchemy as sa
from nagare import database, local, security
from kansha.board.boardsmanager import BoardsManager
from kansha.security import SecurityManager
from kansha.services.dummyassetsmanager.dummyassetsmanager import DummyAssetsManager
from kansha.services.services_repository import ServicesRepository
from kansha.services.mail import DummyMailSender
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
# Setup models
elixir.metadata.bind = op.get_bind()
elixir.setup_all()
# Add column
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
# Create default template
local.request = local.Thread()
security.set_manager(SecurityManager(''))
services = ServicesRepository()
services.register('assets_manager', DummyAssetsManager())
services.register('mail_sender', DummyMailSender())
bm = BoardsManager('', '', '', None, services)
bm.create_template_todo()
def downgrade():
op.drop_column('board', 'is_template')
| <commit_before>"""Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
def downgrade():
op.drop_column('board', 'is_template')
<commit_msg>Add default template creation into migration script<commit_after> | """Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
from alembic import op
import elixir
import sqlalchemy as sa
from nagare import database, local, security
from kansha.board.boardsmanager import BoardsManager
from kansha.security import SecurityManager
from kansha.services.dummyassetsmanager.dummyassetsmanager import DummyAssetsManager
from kansha.services.services_repository import ServicesRepository
from kansha.services.mail import DummyMailSender
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
# Setup models
elixir.metadata.bind = op.get_bind()
elixir.setup_all()
# Add column
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
# Create default template
local.request = local.Thread()
security.set_manager(SecurityManager(''))
services = ServicesRepository()
services.register('assets_manager', DummyAssetsManager())
services.register('mail_sender', DummyMailSender())
bm = BoardsManager('', '', '', None, services)
bm.create_template_todo()
def downgrade():
op.drop_column('board', 'is_template')
| """Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
def downgrade():
op.drop_column('board', 'is_template')
Add default template creation into migration script"""Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
from alembic import op
import elixir
import sqlalchemy as sa
from nagare import database, local, security
from kansha.board.boardsmanager import BoardsManager
from kansha.security import SecurityManager
from kansha.services.dummyassetsmanager.dummyassetsmanager import DummyAssetsManager
from kansha.services.services_repository import ServicesRepository
from kansha.services.mail import DummyMailSender
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
# Setup models
elixir.metadata.bind = op.get_bind()
elixir.setup_all()
# Add column
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
# Create default template
local.request = local.Thread()
security.set_manager(SecurityManager(''))
services = ServicesRepository()
services.register('assets_manager', DummyAssetsManager())
services.register('mail_sender', DummyMailSender())
bm = BoardsManager('', '', '', None, services)
bm.create_template_todo()
def downgrade():
op.drop_column('board', 'is_template')
| <commit_before>"""Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
def downgrade():
op.drop_column('board', 'is_template')
<commit_msg>Add default template creation into migration script<commit_after>"""Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
from alembic import op
import elixir
import sqlalchemy as sa
from nagare import database, local, security
from kansha.board.boardsmanager import BoardsManager
from kansha.security import SecurityManager
from kansha.services.dummyassetsmanager.dummyassetsmanager import DummyAssetsManager
from kansha.services.services_repository import ServicesRepository
from kansha.services.mail import DummyMailSender
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
# Setup models
elixir.metadata.bind = op.get_bind()
elixir.setup_all()
# Add column
op.add_column('board', sa.Column('is_template', sa.Boolean, default=False))
# Create default template
local.request = local.Thread()
security.set_manager(SecurityManager(''))
services = ServicesRepository()
services.register('assets_manager', DummyAssetsManager())
services.register('mail_sender', DummyMailSender())
bm = BoardsManager('', '', '', None, services)
bm.create_template_todo()
def downgrade():
op.drop_column('board', 'is_template')
|
19ce6528a722deec9f0080c229c329e15b843614 | src/pyqa.py | src/pyqa.py | def main():
pass
if __name__ == '__main__':
main()
| from __future__ import with_statement
import yaml
def load_file(source):
with open(source) as f:
return map(lambda a: a, yaml.load_all(f))
def main():
pass
if __name__ == '__main__':
main()
| Make it possible to load questions | Make it possible to load questions
| Python | mit | bebraw/pyqa | def main():
pass
if __name__ == '__main__':
main()
Make it possible to load questions | from __future__ import with_statement
import yaml
def load_file(source):
with open(source) as f:
return map(lambda a: a, yaml.load_all(f))
def main():
pass
if __name__ == '__main__':
main()
| <commit_before>def main():
pass
if __name__ == '__main__':
main()
<commit_msg>Make it possible to load questions<commit_after> | from __future__ import with_statement
import yaml
def load_file(source):
with open(source) as f:
return map(lambda a: a, yaml.load_all(f))
def main():
pass
if __name__ == '__main__':
main()
| def main():
pass
if __name__ == '__main__':
main()
Make it possible to load questionsfrom __future__ import with_statement
import yaml
def load_file(source):
with open(source) as f:
return map(lambda a: a, yaml.load_all(f))
def main():
pass
if __name__ == '__main__':
main()
| <commit_before>def main():
pass
if __name__ == '__main__':
main()
<commit_msg>Make it possible to load questions<commit_after>from __future__ import with_statement
import yaml
def load_file(source):
with open(source) as f:
return map(lambda a: a, yaml.load_all(f))
def main():
pass
if __name__ == '__main__':
main()
|
5fc393a96cb580b7c4ec617cdc33f1e9ccbbb1c6 | core/descriptives.py | core/descriptives.py | from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( data )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
| from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( datasets = [data] )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
| Refactor timeline method call to use kwargs | Refactor timeline method call to use kwargs
| Python | mit | HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core | from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( data )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
Refactor timeline method call to use kwargs | from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( datasets = [data] )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
| <commit_before>from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( data )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
<commit_msg>Refactor timeline method call to use kwargs<commit_after> | from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( datasets = [data] )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
| from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( data )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
Refactor timeline method call to use kwargsfrom __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( datasets = [data] )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
| <commit_before>from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( data )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
<commit_msg>Refactor timeline method call to use kwargs<commit_after>from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( datasets = [data] )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
|
28bc35bc8ed2646faf0d6662b54a5324c0fd1e31 | pspec/cli.py | pspec/cli.py | """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
| """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
# When run as a console script (i.e. ``pspec``), the CWD isn't
# ``sys.path[0]``, but it should be.
cwd = os.getcwd()
if sys.path[0] not in ('', cwd):
sys.path.insert(0, cwd)
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
| Put CWD at start of sys.path | Put CWD at start of sys.path
| Python | bsd-3-clause | bfirsh/pspec | """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
Put CWD at start of sys.path | """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
# When run as a console script (i.e. ``pspec``), the CWD isn't
# ``sys.path[0]``, but it should be.
cwd = os.getcwd()
if sys.path[0] not in ('', cwd):
sys.path.insert(0, cwd)
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
| <commit_before>"""
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
<commit_msg>Put CWD at start of sys.path<commit_after> | """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
# When run as a console script (i.e. ``pspec``), the CWD isn't
# ``sys.path[0]``, but it should be.
cwd = os.getcwd()
if sys.path[0] not in ('', cwd):
sys.path.insert(0, cwd)
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
| """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
Put CWD at start of sys.path"""
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
# When run as a console script (i.e. ``pspec``), the CWD isn't
# ``sys.path[0]``, but it should be.
cwd = os.getcwd()
if sys.path[0] not in ('', cwd):
sys.path.insert(0, cwd)
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
| <commit_before>"""
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
<commit_msg>Put CWD at start of sys.path<commit_after>"""
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
# When run as a console script (i.e. ``pspec``), the CWD isn't
# ``sys.path[0]``, but it should be.
cwd = os.getcwd()
if sys.path[0] not in ('', cwd):
sys.path.insert(0, cwd)
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
paths = [name for name in os.listdir('.')
if os.path.isfile('%s/__init__.py' % name)]
with AssertImportHook():
tests = PSpecTests(paths)
tests.run()
if __name__ == '__main__':
main()
|
6e9e6c0fbba6b1f6e97c40181ec58c55e4980995 | pyipmi/fw.py | pyipmi/fw.py | """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
| """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
def __eq__(self, other):
if isinstance(other, self.__class__):
return (self.slot == other.slot and \
self.type == other.type and \
self.offset == other.offset and \
self.size == other.size and \
self.flags == other.flags)
else:
return False
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
| Add equality operator to FWInfo | Add equality operator to FWInfo
| Python | bsd-3-clause | Cynerva/pyipmi,emaadmanzoor/pyipmi | """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
Add equality operator to FWInfo | """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
def __eq__(self, other):
if isinstance(other, self.__class__):
return (self.slot == other.slot and \
self.type == other.type and \
self.offset == other.offset and \
self.size == other.size and \
self.flags == other.flags)
else:
return False
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
| <commit_before>"""FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
<commit_msg>Add equality operator to FWInfo<commit_after> | """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
def __eq__(self, other):
if isinstance(other, self.__class__):
return (self.slot == other.slot and \
self.type == other.type and \
self.offset == other.offset and \
self.size == other.size and \
self.flags == other.flags)
else:
return False
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
| """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
Add equality operator to FWInfo"""FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
def __eq__(self, other):
if isinstance(other, self.__class__):
return (self.slot == other.slot and \
self.type == other.type and \
self.offset == other.offset and \
self.size == other.size and \
self.flags == other.flags)
else:
return False
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
| <commit_before>"""FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
<commit_msg>Add equality operator to FWInfo<commit_after>"""FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
def __eq__(self, other):
if isinstance(other, self.__class__):
return (self.slot == other.slot and \
self.type == other.type and \
self.offset == other.offset and \
self.size == other.size and \
self.flags == other.flags)
else:
return False
class FWDownloadResult(object):
"""Object to hold firmware update results"""
start_fw_download_failed = None
class FWUploadResult(object):
"""Object to hold firmware retrieve results"""
pass
class FWActivateResult(object):
"""Object to hold firmware activate results"""
pass
class FWDeactivateResult(object):
"""Object to hold firmware deactivate results"""
pass
class FWFlagsResult(object):
"""Object to hold firmware flag command results"""
pass
class FWStatus(object):
"""Object to hold firmware operation status"""
pass
class FWCancelResult(object):
"""Object to hold firmware operation cancelation results"""
pass
class FWCheckResult(object):
"""Object to hold firmware CRC check results"""
pass
class FWBlowResult(object):
"""Object to hold firmware blow results"""
pass
|
c870f68c77652a11f8401bbbb981797694174288 | src/py/crankshaft/setup.py | src/py/crankshaft/setup.py |
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['scipy==0.17.1', 'pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['scipy', 'pysal', 'numpy', 'sklearn'],
test_suite='test'
)
|
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['pysal', 'numpy', 'sklearn' ],
test_suite='test'
)
| Revert "Declare scipy as dep" | Revert "Declare scipy as dep"
This reverts commit 1e8bc12e0a6ea2ffefe580b63133b88f4db045a7.
| Python | bsd-3-clause | CartoDB/crankshaft,CartoDB/crankshaft |
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['scipy==0.17.1', 'pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['scipy', 'pysal', 'numpy', 'sklearn'],
test_suite='test'
)
Revert "Declare scipy as dep"
This reverts commit 1e8bc12e0a6ea2ffefe580b63133b88f4db045a7. |
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['pysal', 'numpy', 'sklearn' ],
test_suite='test'
)
| <commit_before>
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['scipy==0.17.1', 'pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['scipy', 'pysal', 'numpy', 'sklearn'],
test_suite='test'
)
<commit_msg>Revert "Declare scipy as dep"
This reverts commit 1e8bc12e0a6ea2ffefe580b63133b88f4db045a7.<commit_after> |
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['pysal', 'numpy', 'sklearn' ],
test_suite='test'
)
|
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['scipy==0.17.1', 'pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['scipy', 'pysal', 'numpy', 'sklearn'],
test_suite='test'
)
Revert "Declare scipy as dep"
This reverts commit 1e8bc12e0a6ea2ffefe580b63133b88f4db045a7.
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['pysal', 'numpy', 'sklearn' ],
test_suite='test'
)
| <commit_before>
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['scipy==0.17.1', 'pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['scipy', 'pysal', 'numpy', 'sklearn'],
test_suite='test'
)
<commit_msg>Revert "Declare scipy as dep"
This reverts commit 1e8bc12e0a6ea2ffefe580b63133b88f4db045a7.<commit_after>
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Mapping comunity',
'Topic :: Maps :: Mapping Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='maps mapping tools spatial analysis geostatistics',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
extras_require={
'dev': ['unittest'],
'test': ['unittest', 'nose', 'mock'],
},
# The choice of component versions is dictated by what's
# provisioned in the production servers.
install_requires=['pysal==1.9.1', 'scikit-learn==0.17.1'],
requires=['pysal', 'numpy', 'sklearn' ],
test_suite='test'
)
|
ff800f11b948808e4574ec3a893ed4e259707dcf | stubs/python2-urllib2/run.py | stubs/python2-urllib2/run.py | import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except ssl.CertificateError:
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
| import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except getattr(ssl, "CertificateError", ()):
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
| Make python2-urllib2 compatible with more Python 2.7 versions | Make python2-urllib2 compatible with more Python 2.7 versions
Try to catch ssl.CertificateError only if CertificateError is
defined. Otherwise bail out by effectively doing a dummy
"catch ():".
| Python | mit | ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls | import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except ssl.CertificateError:
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
Make python2-urllib2 compatible with more Python 2.7 versions
Try to catch ssl.CertificateError only if CertificateError is
defined. Otherwise bail out by effectively doing a dummy
"catch ():". | import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except getattr(ssl, "CertificateError", ()):
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
| <commit_before>import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except ssl.CertificateError:
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
<commit_msg>Make python2-urllib2 compatible with more Python 2.7 versions
Try to catch ssl.CertificateError only if CertificateError is
defined. Otherwise bail out by effectively doing a dummy
"catch ():".<commit_after> | import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except getattr(ssl, "CertificateError", ()):
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
| import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except ssl.CertificateError:
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
Make python2-urllib2 compatible with more Python 2.7 versions
Try to catch ssl.CertificateError only if CertificateError is
defined. Otherwise bail out by effectively doing a dummy
"catch ():".import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except getattr(ssl, "CertificateError", ()):
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
| <commit_before>import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except ssl.CertificateError:
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
<commit_msg>Make python2-urllib2 compatible with more Python 2.7 versions
Try to catch ssl.CertificateError only if CertificateError is
defined. Otherwise bail out by effectively doing a dummy
"catch ():".<commit_after>import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except getattr(ssl, "CertificateError", ()):
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError):
raise
print("REJECT")
else:
print("ACCEPT")
|
4f1354f6e917a4a90a56f3c2545aa678809334c3 | scripts/release/rethreshold_family.py | scripts/release/rethreshold_family.py | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return:
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
if __name__== '__main__':
pass | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return: None
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
def submit_new_rfsearch_job(family_dir):
"""
Submits a new lsf job that runs rfsearch to update SCORES for a new release
family_dir: The physical location of the family directory
return: None
"""
# use the pre-process command to change directory to family_dir
cmd = """
bsub -M %s -R \"rusage[mem=%s]\" -o %s -e %s -n %8 -g %s -R \"span[hosts=1]\"
cd %s && rfsearch.pl -cnompi
"""
# ----------------------------------------------------------------------------------
if __name__ == '__main__':
pass | Add function to run rfsearch on the cluster | Add function to run rfsearch on the cluster
| Python | apache-2.0 | Rfam/rfam-production,Rfam/rfam-production,Rfam/rfam-production | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return:
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
if __name__== '__main__':
passAdd function to run rfsearch on the cluster | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return: None
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
def submit_new_rfsearch_job(family_dir):
"""
Submits a new lsf job that runs rfsearch to update SCORES for a new release
family_dir: The physical location of the family directory
return: None
"""
# use the pre-process command to change directory to family_dir
cmd = """
bsub -M %s -R \"rusage[mem=%s]\" -o %s -e %s -n %8 -g %s -R \"span[hosts=1]\"
cd %s && rfsearch.pl -cnompi
"""
# ----------------------------------------------------------------------------------
if __name__ == '__main__':
pass | <commit_before>"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return:
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
if __name__== '__main__':
pass<commit_msg>Add function to run rfsearch on the cluster<commit_after> | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return: None
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
def submit_new_rfsearch_job(family_dir):
"""
Submits a new lsf job that runs rfsearch to update SCORES for a new release
family_dir: The physical location of the family directory
return: None
"""
# use the pre-process command to change directory to family_dir
cmd = """
bsub -M %s -R \"rusage[mem=%s]\" -o %s -e %s -n %8 -g %s -R \"span[hosts=1]\"
cd %s && rfsearch.pl -cnompi
"""
# ----------------------------------------------------------------------------------
if __name__ == '__main__':
pass | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return:
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
if __name__== '__main__':
passAdd function to run rfsearch on the cluster"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return: None
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
def submit_new_rfsearch_job(family_dir):
"""
Submits a new lsf job that runs rfsearch to update SCORES for a new release
family_dir: The physical location of the family directory
return: None
"""
# use the pre-process command to change directory to family_dir
cmd = """
bsub -M %s -R \"rusage[mem=%s]\" -o %s -e %s -n %8 -g %s -R \"span[hosts=1]\"
cd %s && rfsearch.pl -cnompi
"""
# ----------------------------------------------------------------------------------
if __name__ == '__main__':
pass | <commit_before>"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return:
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
if __name__== '__main__':
pass<commit_msg>Add function to run rfsearch on the cluster<commit_after>"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 os
import sys
import subprocess
import argparse
# ------------------------------------- GLOBALS ------------------------------------
LSF_GROUP = "/family_srch"
MEMORY = 8000
# ----------------------------------------------------------------------------------
def checkout_family(rfam_acc):
"""
Checks out a family from Rfam based on a valid Rfam accession.
rfam_acc: A valid Rfam accession
return: None
"""
cmd = "rfco.pl %s" % rfam_acc
subprocess.call(cmd, shell=True)
# add some checks here
# ----------------------------------------------------------------------------------
def submit_new_rfsearch_job(family_dir):
"""
Submits a new lsf job that runs rfsearch to update SCORES for a new release
family_dir: The physical location of the family directory
return: None
"""
# use the pre-process command to change directory to family_dir
cmd = """
bsub -M %s -R \"rusage[mem=%s]\" -o %s -e %s -n %8 -g %s -R \"span[hosts=1]\"
cd %s && rfsearch.pl -cnompi
"""
# ----------------------------------------------------------------------------------
if __name__ == '__main__':
pass |
76bda324fcd617677a3f107e6b7c162a81e88db9 | tests/test_vector2_negation.py | tests/test_vector2_negation.py | import pytest
from ppb_vector import Vector2
negation_data = (
(Vector2(1, 1), Vector2(-1, -1)),
(Vector2(2, -3), Vector2(-2, 3)),
(Vector2(-4, 18), Vector2(4, -18))
)
@pytest.mark.parametrize('test_vector, expected_result', negation_data)
def test_negation(test_vector, expected_result):
assert -test_vector == expected_result
| from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
@given(vector=vectors())
def test_negation_coordinates(vector: Vector2):
assert - vector.x == (- vector).x
assert - vector.y == (- vector).y
| Replace with an Hypothesis test | tests/negation: Replace with an Hypothesis test
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | import pytest
from ppb_vector import Vector2
negation_data = (
(Vector2(1, 1), Vector2(-1, -1)),
(Vector2(2, -3), Vector2(-2, 3)),
(Vector2(-4, 18), Vector2(4, -18))
)
@pytest.mark.parametrize('test_vector, expected_result', negation_data)
def test_negation(test_vector, expected_result):
assert -test_vector == expected_result
tests/negation: Replace with an Hypothesis test | from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
@given(vector=vectors())
def test_negation_coordinates(vector: Vector2):
assert - vector.x == (- vector).x
assert - vector.y == (- vector).y
| <commit_before>import pytest
from ppb_vector import Vector2
negation_data = (
(Vector2(1, 1), Vector2(-1, -1)),
(Vector2(2, -3), Vector2(-2, 3)),
(Vector2(-4, 18), Vector2(4, -18))
)
@pytest.mark.parametrize('test_vector, expected_result', negation_data)
def test_negation(test_vector, expected_result):
assert -test_vector == expected_result
<commit_msg>tests/negation: Replace with an Hypothesis test<commit_after> | from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
@given(vector=vectors())
def test_negation_coordinates(vector: Vector2):
assert - vector.x == (- vector).x
assert - vector.y == (- vector).y
| import pytest
from ppb_vector import Vector2
negation_data = (
(Vector2(1, 1), Vector2(-1, -1)),
(Vector2(2, -3), Vector2(-2, 3)),
(Vector2(-4, 18), Vector2(4, -18))
)
@pytest.mark.parametrize('test_vector, expected_result', negation_data)
def test_negation(test_vector, expected_result):
assert -test_vector == expected_result
tests/negation: Replace with an Hypothesis testfrom hypothesis import given
from ppb_vector import Vector2
from utils import vectors
@given(vector=vectors())
def test_negation_coordinates(vector: Vector2):
assert - vector.x == (- vector).x
assert - vector.y == (- vector).y
| <commit_before>import pytest
from ppb_vector import Vector2
negation_data = (
(Vector2(1, 1), Vector2(-1, -1)),
(Vector2(2, -3), Vector2(-2, 3)),
(Vector2(-4, 18), Vector2(4, -18))
)
@pytest.mark.parametrize('test_vector, expected_result', negation_data)
def test_negation(test_vector, expected_result):
assert -test_vector == expected_result
<commit_msg>tests/negation: Replace with an Hypothesis test<commit_after>from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
@given(vector=vectors())
def test_negation_coordinates(vector: Vector2):
assert - vector.x == (- vector).x
assert - vector.y == (- vector).y
|
8bb60a82f903126068434df3a464cdde5d894d0c | serverless_helpers/__init__.py | serverless_helpers/__init__.py | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
| # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import os
import logging
logger = logging.getLogger()
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
| Add logger to env loader | Add logger to env loader
| Python | mit | serverless/serverless-helpers-py | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
Add logger to env loader | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import os
import logging
logger = logging.getLogger()
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
| <commit_before># -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
<commit_msg>Add logger to env loader<commit_after> | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import os
import logging
logger = logging.getLogger()
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
| # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
Add logger to env loader# -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import os
import logging
logger = logging.getLogger()
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
| <commit_before># -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
<commit_msg>Add logger to env loader<commit_after># -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import os
import logging
logger = logging.getLogger()
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load_envs with the value __file__ to
give it the current location as a place to start looking for .env files.
import serverless_helpers
serverless_helpers.load_envs(__file__)
Given the path "foo/bar/myfile.py" and a directory structure like:
foo
\---.env
\---bar
\---.env
\---myfile.py
Values from foo/bar/.env and foo/.env will both be loaded, but values in
foo/bar/.env will take precedence over values from foo/.env
"""
import os
path = os.path.abspath(path)
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'))
return
# load higher envs first
# closer-to-base environments need higher precedence.
load_envs(path)
load_dotenv(os.path.join(path, '.env'))
|
8dadb34bdfe6d85d3016a59a9441ed8a552d1149 | octane_fuelclient/octaneclient/commands.py | octane_fuelclient/octaneclient/commands.py | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/changes".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
| from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/upgrade/clone".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
| Fix endpoint for clone operation | Fix endpoint for clone operation
| Python | apache-2.0 | stackforge/fuel-octane,Mirantis/octane,Mirantis/octane,stackforge/fuel-octane | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/changes".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
Fix endpoint for clone operation | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/upgrade/clone".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
| <commit_before>from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/changes".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
<commit_msg>Fix endpoint for clone operation<commit_after> | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/upgrade/clone".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
| from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/changes".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
Fix endpoint for clone operationfrom fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/upgrade/clone".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
| <commit_before>from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/changes".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
<commit_msg>Fix endpoint for clone operation<commit_after>from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
def get_parser(self, prog_name):
parser = super(EnvClone, self).get_parser(prog_name)
parser.add_argument('name',
type=str,
help='Name of the new environment.')
parser.add_argument('release',
type=int,
help='ID of the release of the new environment.')
return parser
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
"clusters/{0}/upgrade/clone".format(parsed_args.id),
{
'name': parsed_args.name,
'release_id': parsed_args.release,
}
)
new_env = data_utils.get_display_data_single(self.columns, new_env)
return (self.columns, new_env)
|
d0cc528f7e69422515ae1507b01266b1686d1452 | ddsc/sdk/__init__.py | ddsc/sdk/__init__.py | from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = [Client]
| from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = ['Client']
| Fix sdk module all declaration | Fix sdk module all declaration
| Python | mit | Duke-GCB/DukeDSClient,Duke-GCB/DukeDSClient | from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = [Client]
Fix sdk module all declaration | from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = ['Client']
| <commit_before>from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = [Client]
<commit_msg>Fix sdk module all declaration<commit_after> | from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = ['Client']
| from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = [Client]
Fix sdk module all declarationfrom __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = ['Client']
| <commit_before>from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = [Client]
<commit_msg>Fix sdk module all declaration<commit_after>from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = ['Client']
|
e538f2862a875afc58071a9fc6419e4290f8b00d | rouver/types.py | rouver/types.py | from types import TracebackType
from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping, Optional, Type
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
_exc_info = Tuple[Optional[Type[BaseException]],
Optional[BaseException],
Optional[TracebackType]]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
| from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
| Remove obsolete aliases and imports | Remove obsolete aliases and imports
| Python | mit | srittau/rouver | from types import TracebackType
from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping, Optional, Type
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
_exc_info = Tuple[Optional[Type[BaseException]],
Optional[BaseException],
Optional[TracebackType]]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
Remove obsolete aliases and imports | from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
| <commit_before>from types import TracebackType
from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping, Optional, Type
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
_exc_info = Tuple[Optional[Type[BaseException]],
Optional[BaseException],
Optional[TracebackType]]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
<commit_msg>Remove obsolete aliases and imports<commit_after> | from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
| from types import TracebackType
from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping, Optional, Type
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
_exc_info = Tuple[Optional[Type[BaseException]],
Optional[BaseException],
Optional[TracebackType]]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
Remove obsolete aliases and importsfrom typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
| <commit_before>from types import TracebackType
from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping, Optional, Type
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
_exc_info = Tuple[Optional[Type[BaseException]],
Optional[BaseException],
Optional[TracebackType]]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
<commit_msg>Remove obsolete aliases and imports<commit_after>from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> response
StartResponse = Callable[..., StartResponseReturnType]
WSGIResponse = Iterable[bytes]
WSGIApplication = Callable[[WSGIEnvironment, StartResponse], WSGIResponse]
# (method, path, callback)
RouteDescription = Tuple[str, str, WSGIApplication]
# (request, previous_args, path_part) -> result
RouteTemplateHandler = Callable[[Request, Sequence[Any], str], Any]
BadArgumentsDict = Mapping[str, str]
|
e7724935ce4d07cd28a231c5e849be2a123a5502 | tools/encrypt.py | tools/encrypt.py | #!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
passphrase = getpass("Choose a passphrase: ")
verifypass = getpass("Re-enter passphrase: ")
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret)
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
print(combined.encode('hex'))
| #!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
import codecs
passphrase = getpass("Choose a passphrase: ").encode('utf-8')
verifypass = getpass("Re-enter passphrase: ").encode('utf-8')
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret.encode('utf-8'))
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
if not _PY3:
print(combined.encode('hex')
else:
codecs.encode(combined.encode('utf-8'), 'hex'))
| Update for Python 3 encoding | Update for Python 3 encoding
Fixes https://github.com/cranklin/crankycoin/issues/12 | Python | mit | cranklin/crankycoin | #!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
passphrase = getpass("Choose a passphrase: ")
verifypass = getpass("Re-enter passphrase: ")
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret)
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
print(combined.encode('hex'))
Update for Python 3 encoding
Fixes https://github.com/cranklin/crankycoin/issues/12 | #!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
import codecs
passphrase = getpass("Choose a passphrase: ").encode('utf-8')
verifypass = getpass("Re-enter passphrase: ").encode('utf-8')
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret.encode('utf-8'))
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
if not _PY3:
print(combined.encode('hex')
else:
codecs.encode(combined.encode('utf-8'), 'hex'))
| <commit_before>#!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
passphrase = getpass("Choose a passphrase: ")
verifypass = getpass("Re-enter passphrase: ")
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret)
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
print(combined.encode('hex'))
<commit_msg>Update for Python 3 encoding
Fixes https://github.com/cranklin/crankycoin/issues/12<commit_after> | #!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
import codecs
passphrase = getpass("Choose a passphrase: ").encode('utf-8')
verifypass = getpass("Re-enter passphrase: ").encode('utf-8')
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret.encode('utf-8'))
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
if not _PY3:
print(combined.encode('hex')
else:
codecs.encode(combined.encode('utf-8'), 'hex'))
| #!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
passphrase = getpass("Choose a passphrase: ")
verifypass = getpass("Re-enter passphrase: ")
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret)
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
print(combined.encode('hex'))
Update for Python 3 encoding
Fixes https://github.com/cranklin/crankycoin/issues/12#!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
import codecs
passphrase = getpass("Choose a passphrase: ").encode('utf-8')
verifypass = getpass("Re-enter passphrase: ").encode('utf-8')
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret.encode('utf-8'))
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
if not _PY3:
print(combined.encode('hex')
else:
codecs.encode(combined.encode('utf-8'), 'hex'))
| <commit_before>#!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
passphrase = getpass("Choose a passphrase: ")
verifypass = getpass("Re-enter passphrase: ")
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret)
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
print(combined.encode('hex'))
<commit_msg>Update for Python 3 encoding
Fixes https://github.com/cranklin/crankycoin/issues/12<commit_after>#!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
import codecs
passphrase = getpass("Choose a passphrase: ").encode('utf-8')
verifypass = getpass("Re-enter passphrase: ").encode('utf-8')
if passphrase != verifypass:
print("Passphrases do not match")
sys.exit(1)
secret = raw_input("Secret: ")
hashedpass = hashlib.sha256(passphrase).digest()
cipher = AES.new(hashedpass, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(secret.encode('utf-8'))
combined = "{}{}{}".format(cipher.nonce, tag, ciphertext)
print("Encrypted private key: ")
if not _PY3:
print(combined.encode('hex')
else:
codecs.encode(combined.encode('utf-8'), 'hex'))
|
e69962de56cb5eaa12f908a74edca4c225dcee9c | run-tests.py | run-tests.py | #!/usr/bin/python
import os;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracle = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
runNode(sourceFilename, testFilename, markupFilename);
| #!/usr/bin/python
import os;
import subprocess;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def compareOutputs(oracleFilename, destinationFilename):
metric = "mae";
cmd = ["gm","compare","-metric",metric,oracleFilename,destinationFilename];
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE);
(out, err) = proc.communicate();
print out;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
return ret == 0;
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracleFilename = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
success = runNode(sourceFilename, testFilename, markupFilename);
if success:
compareOutputs(oracleFilename, testFilename);
| Add automated 'gm compare' invocation | Add automated 'gm compare' invocation
| Python | mit | iFixit/node-markup,iFixit/node-markup,iFixit/node-markup | #!/usr/bin/python
import os;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracle = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
runNode(sourceFilename, testFilename, markupFilename);
Add automated 'gm compare' invocation | #!/usr/bin/python
import os;
import subprocess;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def compareOutputs(oracleFilename, destinationFilename):
metric = "mae";
cmd = ["gm","compare","-metric",metric,oracleFilename,destinationFilename];
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE);
(out, err) = proc.communicate();
print out;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
return ret == 0;
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracleFilename = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
success = runNode(sourceFilename, testFilename, markupFilename);
if success:
compareOutputs(oracleFilename, testFilename);
| <commit_before>#!/usr/bin/python
import os;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracle = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
runNode(sourceFilename, testFilename, markupFilename);
<commit_msg>Add automated 'gm compare' invocation<commit_after> | #!/usr/bin/python
import os;
import subprocess;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def compareOutputs(oracleFilename, destinationFilename):
metric = "mae";
cmd = ["gm","compare","-metric",metric,oracleFilename,destinationFilename];
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE);
(out, err) = proc.communicate();
print out;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
return ret == 0;
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracleFilename = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
success = runNode(sourceFilename, testFilename, markupFilename);
if success:
compareOutputs(oracleFilename, testFilename);
| #!/usr/bin/python
import os;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracle = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
runNode(sourceFilename, testFilename, markupFilename);
Add automated 'gm compare' invocation#!/usr/bin/python
import os;
import subprocess;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def compareOutputs(oracleFilename, destinationFilename):
metric = "mae";
cmd = ["gm","compare","-metric",metric,oracleFilename,destinationFilename];
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE);
(out, err) = proc.communicate();
print out;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
return ret == 0;
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracleFilename = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
success = runNode(sourceFilename, testFilename, markupFilename);
if success:
compareOutputs(oracleFilename, testFilename);
| <commit_before>#!/usr/bin/python
import os;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracle = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
runNode(sourceFilename, testFilename, markupFilename);
<commit_msg>Add automated 'gm compare' invocation<commit_after>#!/usr/bin/python
import os;
import subprocess;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def compareOutputs(oracleFilename, destinationFilename):
metric = "mae";
cmd = ["gm","compare","-metric",metric,oracleFilename,destinationFilename];
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE);
(out, err) = proc.communicate();
print out;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd = "node ImageMarkupCall.js --input " + sourceFilename + " --output " + \
destinationFilename + " --markup \"" + markup + "\"";
ret = os.system(cmd);
if ret != 0:
sys.stderr.write('node-markup encountered an error while processing ' \
+ sourceFilename);
else:
print(sourceFilename + ' -> ' + destinationFilename);
return ret == 0;
for filename in os.listdir(testDirectory):
if filename.endswith(".markup"):
markupFilename = testDirectory + filename;
basename = regex.sub(r'(.+)\.markup', r'\1', filename);
sourceFilename = testDirectory + basename + '.source.jpg';
oracleFilename = testDirectory + basename + '.node.oracle.jpg';
testFilename = testDirectory + basename + '.node.test.jpg';
success = runNode(sourceFilename, testFilename, markupFilename);
if success:
compareOutputs(oracleFilename, testFilename);
|
e22360f13fd3b582e7b0898549f656a76a038306 | scripting.py | scripting.py | #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message, color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
| #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message + '\n', color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
| Fix a formatting error in print_error_and_die(). | Fix a formatting error in print_error_and_die().
| Python | mit | Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab | #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message, color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
Fix a formatting error in print_error_and_die(). | #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message + '\n', color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
| <commit_before>#!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message, color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
<commit_msg>Fix a formatting error in print_error_and_die().<commit_after> | #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message + '\n', color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
| #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message, color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
Fix a formatting error in print_error_and_die().#!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message + '\n', color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
| <commit_before>#!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message, color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
<commit_msg>Fix a formatting error in print_error_and_die().<commit_after>#!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message + '\n', color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, **kwargs)
raise SystemExit(1)
def clear_directory(directory):
if os.path.exists(directory): shutil.rmtree(directory)
os.makedirs(directory)
def mkdir(newdir):
if os.path.isdir(newdir):
pass
elif os.path.isfile(newdir):
raise OSError("a file with the same name as the desired " \
"dir, '%s', already exists." % newdir)
else:
os.makedirs(newdir)
|
ccda4cd859b512d8694eba4261439bb52574f099 | cities/Sample_City.py | cities/Sample_City.py | from bs4 import BeautifulSoup
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
| from bs4 import BeautifulSoup
import json
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
def get_geodata_for_lot(lot_name):
geofile = open("./cities/" + file_name + ".geojson")
geodata = geofile.read()
geofile.close()
geodata = json.loads(geodata)
for feature in geodata["features"]:
if feature["properties"]["name"] == lot_name:
return {
"lon": feature["geometry"]["coordinates"][0],
"lat": feature["geometry"]["coordinates"][1]
}
return []
if __name__ == "__main__":
file = open("../tests/sample_city.html")
html_data = file.read()
file.close()
parse_html(html_data)
| Add geodata parsing to sample city file | Add geodata parsing to sample city file
| Python | mit | Mic92/ParkAPI,Mic92/ParkAPI,offenesdresden/ParkAPI,offenesdresden/ParkAPI | from bs4 import BeautifulSoup
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
Add geodata parsing to sample city file | from bs4 import BeautifulSoup
import json
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
def get_geodata_for_lot(lot_name):
geofile = open("./cities/" + file_name + ".geojson")
geodata = geofile.read()
geofile.close()
geodata = json.loads(geodata)
for feature in geodata["features"]:
if feature["properties"]["name"] == lot_name:
return {
"lon": feature["geometry"]["coordinates"][0],
"lat": feature["geometry"]["coordinates"][1]
}
return []
if __name__ == "__main__":
file = open("../tests/sample_city.html")
html_data = file.read()
file.close()
parse_html(html_data)
| <commit_before>from bs4 import BeautifulSoup
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
<commit_msg>Add geodata parsing to sample city file<commit_after> | from bs4 import BeautifulSoup
import json
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
def get_geodata_for_lot(lot_name):
geofile = open("./cities/" + file_name + ".geojson")
geodata = geofile.read()
geofile.close()
geodata = json.loads(geodata)
for feature in geodata["features"]:
if feature["properties"]["name"] == lot_name:
return {
"lon": feature["geometry"]["coordinates"][0],
"lat": feature["geometry"]["coordinates"][1]
}
return []
if __name__ == "__main__":
file = open("../tests/sample_city.html")
html_data = file.read()
file.close()
parse_html(html_data)
| from bs4 import BeautifulSoup
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
Add geodata parsing to sample city filefrom bs4 import BeautifulSoup
import json
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
def get_geodata_for_lot(lot_name):
geofile = open("./cities/" + file_name + ".geojson")
geodata = geofile.read()
geofile.close()
geodata = json.loads(geodata)
for feature in geodata["features"]:
if feature["properties"]["name"] == lot_name:
return {
"lon": feature["geometry"]["coordinates"][0],
"lat": feature["geometry"]["coordinates"][1]
}
return []
if __name__ == "__main__":
file = open("../tests/sample_city.html")
html_data = file.read()
file.close()
parse_html(html_data)
| <commit_before>from bs4 import BeautifulSoup
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
<commit_msg>Add geodata parsing to sample city file<commit_after>from bs4 import BeautifulSoup
import json
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
file_name = "Sample_City"
def parse_html(html):
soup = BeautifulSoup(html)
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
def get_geodata_for_lot(lot_name):
geofile = open("./cities/" + file_name + ".geojson")
geodata = geofile.read()
geofile.close()
geodata = json.loads(geodata)
for feature in geodata["features"]:
if feature["properties"]["name"] == lot_name:
return {
"lon": feature["geometry"]["coordinates"][0],
"lat": feature["geometry"]["coordinates"][1]
}
return []
if __name__ == "__main__":
file = open("../tests/sample_city.html")
html_data = file.read()
file.close()
parse_html(html_data)
|
fca9028a189b55e2c6b6775999e98c9d453477be | config.sample.py | config.sample.py | # -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
| # -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# Disable Flask's swallowing of unhandled exceptions
PROPAGATE_EXCEPTIONS = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
| Add non-dangerous debugging option to config | Add non-dangerous debugging option to config
| Python | mit | raquo/hnapp,raquo/hnapp,raquo/hnapp | # -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
Add non-dangerous debugging option to config | # -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# Disable Flask's swallowing of unhandled exceptions
PROPAGATE_EXCEPTIONS = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
| <commit_before># -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
<commit_msg>Add non-dangerous debugging option to config<commit_after> | # -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# Disable Flask's swallowing of unhandled exceptions
PROPAGATE_EXCEPTIONS = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
| # -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
Add non-dangerous debugging option to config# -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# Disable Flask's swallowing of unhandled exceptions
PROPAGATE_EXCEPTIONS = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
| <commit_before># -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
<commit_msg>Add non-dangerous debugging option to config<commit_after># -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# Disable Flask's swallowing of unhandled exceptions
PROPAGATE_EXCEPTIONS = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID (UA-XXXXXXXX-X). Set to None to disable tracking
GA_ID = None
# Number of items per page to show in GUI and RSS / JSON feeds
ITEMS_PER_PAGE = 30;
# Database connection string in the format engine://db_user:db_password@db_server/db_name
# Documentation: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
SQLALCHEMY_DATABASE_URI = 'engine://db_user:%s@db_server/db_name' % urllib.quote_plus('password')
|
51029137cddaebeb3d84b7fa766c5e3914a02504 | multilingual_model/admin.py | multilingual_model/admin.py | import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
| import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInlineMixin(object):
def __init__(self, *args, **kwargs):
super(TranslationInlineMixin, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationStackedInline(TranslationInlineMixin, admin.StackedInline):
pass
class TranslationTabularInline(TranslationInlineMixin, admin.TabularInline):
pass
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
| Use a Mixin for Admin inlines; less code duplication. | Use a Mixin for Admin inlines; less code duplication.
| Python | agpl-3.0 | dokterbob/django-multilingual-model | import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
Use a Mixin for Admin inlines; less code duplication. | import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInlineMixin(object):
def __init__(self, *args, **kwargs):
super(TranslationInlineMixin, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationStackedInline(TranslationInlineMixin, admin.StackedInline):
pass
class TranslationTabularInline(TranslationInlineMixin, admin.TabularInline):
pass
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
| <commit_before>import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
<commit_msg>Use a Mixin for Admin inlines; less code duplication.<commit_after> | import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInlineMixin(object):
def __init__(self, *args, **kwargs):
super(TranslationInlineMixin, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationStackedInline(TranslationInlineMixin, admin.StackedInline):
pass
class TranslationTabularInline(TranslationInlineMixin, admin.TabularInline):
pass
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
| import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
Use a Mixin for Admin inlines; less code duplication.import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInlineMixin(object):
def __init__(self, *args, **kwargs):
super(TranslationInlineMixin, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationStackedInline(TranslationInlineMixin, admin.StackedInline):
pass
class TranslationTabularInline(TranslationInlineMixin, admin.TabularInline):
pass
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
| <commit_before>import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationTabularInline(admin.TabularInline):
def __init__(self, *args, **kwargs):
super(TranslationTabularInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
<commit_msg>Use a Mixin for Admin inlines; less code duplication.<commit_after>import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInlineMixin(object):
def __init__(self, *args, **kwargs):
super(TranslationInlineMixin, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('language_code', )
self.can_delete = False
extra = 1
formset = TranslationFormSet
max_num = len(settings.LANGUAGES)
class TranslationStackedInline(TranslationInlineMixin, admin.StackedInline):
pass
class TranslationTabularInline(TranslationInlineMixin, admin.TabularInline):
pass
class TranslationInline(TranslationStackedInline):
def __init__(self, *args, **kwargs):
warnings.warn(DeprecationWarning(
"TranslationInline is deprecated; "
"use TranslationStackedInline or TranslationTabularInline instead."
))
return super(TranslationInline, self).__init__(*args, **kwargs)
|
5e4b9c8c056f16613440c92945fe25e75c952b79 | src/boarbot/modules/groups/cmd.py | src/boarbot/modules/groups/cmd.py | import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
| import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (list | create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
| Add group list command to docs | Add group list command to docs
| Python | mit | fsufitch/discord-boar-bot,fsufitch/discord-boar-bot | import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
Add group list command to docs | import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (list | create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
| <commit_before>import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
<commit_msg>Add group list command to docs<commit_after> | import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (list | create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
| import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
Add group list command to docsimport argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (list | create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
| <commit_before>import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
<commit_msg>Add group list command to docs<commit_after>import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (list | create | delete | join | leave)')
GROUPS_PARSER.add_argument('group', metavar='GROUP', type=str, nargs='?', default=None, help='the group name to operate on')
GROUPS_PARSER.add_argument('users', metavar='USER', type=str, nargs='*', help='@mentions of the target users (available only for managers)')
GROUPS_PARSER.add_argument('-h', '--help', action='store_true', help='print help/usage instructions')
|
c362d5477eb2bcd8720149c84e2a0f8578975fb7 | tests/test_file.py | tests/test_file.py | # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(ValueError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
| # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(IOError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
| Fix exception type in a test | Fix exception type in a test
| Python | mit | aldanor/blox | # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(ValueError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
Fix exception type in a test | # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(IOError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
| <commit_before># -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(ValueError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
<commit_msg>Fix exception type in a test<commit_after> | # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(IOError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
| # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(ValueError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
Fix exception type in a test# -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(IOError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
| <commit_before># -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(ValueError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
<commit_msg>Fix exception type in a test<commit_after># -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_filename(self, tmpfile):
raises_regexp(IOError, 'No such file', File, '/foo/bar/baz')
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
raises_regexp(IOError, 'file is not writable',
File(tmpfile).create_dataset, 'a', [])
|
3e20365624f02b70d8332ba7ff7da23961337f86 | quickstart/python/understand/example-3/create_joke_samples.6.x.py | quickstart/python/understand/example-3/create_joke_samples.6.x.py | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('tell-a-joke') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| Update samples creation for intent rename | Update samples creation for intent rename
Update intent --> task, code comment | Python | mit | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('tell-a-joke') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
Update samples creation for intent rename
Update intent --> task, code comment | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| <commit_before># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('tell-a-joke') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
<commit_msg>Update samples creation for intent rename
Update intent --> task, code comment<commit_after> | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('tell-a-joke') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
Update samples creation for intent rename
Update intent --> task, code comment# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
| <commit_before># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('tell-a-joke') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
<commit_msg>Update samples creation for intent rename
Update intent --> task, code comment<commit_after># Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a joke',
'Tell me a joke',
'I\'d like to hear a joke',
'Do you know any good jokes?',
'Joke',
'Tell joke',
'Tell me something funny',
'Make me laugh',
'I want to hear a joke',
'Can I hear a joke?',
'I like jokes',
'I\'d like to hear a punny joke'
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.tasks('UDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.samples \
.create(language='en-us', tagged_text=phrase)
print(sample.sid)
|
9144e6011df4aebd74db152dad2bb07a8eebf6ee | setup_egg.py | setup_egg.py | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
execfile('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
| #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
exec('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
| Use `exec` instead of `execfile`. | Use `exec` instead of `execfile`.
| Python | bsd-3-clause | FrancoisRheaultUS/dipy,FrancoisRheaultUS/dipy | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
execfile('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
Use `exec` instead of `execfile`. | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
exec('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
| <commit_before>#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
execfile('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
<commit_msg>Use `exec` instead of `execfile`.<commit_after> | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
exec('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
| #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
execfile('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
Use `exec` instead of `execfile`.#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
exec('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
| <commit_before>#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
execfile('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
<commit_msg>Use `exec` instead of `execfile`.<commit_after>#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
exec('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in setup.py
force_setuptools=True))
|
27557975023003e2d56943221f422a148cb0efa2 | models/scorefeedback.py | models/scorefeedback.py | from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(10, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
| from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(20, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
| Fix verdict field max length | Fix verdict field max length
| Python | mit | hatbot-team/hatbot,hatbot-team/hatbot,hatbot-team/hatbot,hatbot-team/hatbot | from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(10, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
Fix verdict field max length | from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(20, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
| <commit_before>from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(10, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
<commit_msg>Fix verdict field max length<commit_after> | from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(20, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
| from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(10, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
Fix verdict field max lengthfrom models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(20, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
| <commit_before>from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(10, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
<commit_msg>Fix verdict field max length<commit_after>from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(20, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50)
|
f800d11aa5a198fcb2193773b30e4e066a226321 | code/handle-output.py | code/handle-output.py | import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
| import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
for repeat_idx in xrange(args.num_repeats) :
resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx)
data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
| Set resu dir and data dir | Set resu dir and data dir
| Python | mit | chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan | import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
Set resu dir and data dir | import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
for repeat_idx in xrange(args.num_repeats) :
resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx)
data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
| <commit_before>import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
<commit_msg>Set resu dir and data dir<commit_after> | import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
for repeat_idx in xrange(args.num_repeats) :
resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx)
data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
| import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
Set resu dir and data dirimport synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
for repeat_idx in xrange(args.num_repeats) :
resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx)
data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
| <commit_before>import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
<commit_msg>Set resu dir and data dir<commit_after>import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
for repeat_idx in xrange(args.num_repeats) :
resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx)
data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
|
2fe315e1753aca8215228091e3a64af057020bc2 | celery/loaders/__init__.py | celery/loaders/__init__.py | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
| import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
try:
# A settings module may be defined, but Django didn't attempt to
# load it yet. As an alternative to calling the private _setup(),
# we could also check whether DJANGO_SETTINGS_MODULE is set.
settings._setup()
except ImportError:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
else:
Loader = DjangoLoader
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
| Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command. | Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
| Python | bsd-3-clause | frac/celery,WoLpH/celery,cbrepo/celery,frac/celery,mitsuhiko/celery,mitsuhiko/celery,ask/celery,WoLpH/celery,cbrepo/celery,ask/celery | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command. | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
try:
# A settings module may be defined, but Django didn't attempt to
# load it yet. As an alternative to calling the private _setup(),
# we could also check whether DJANGO_SETTINGS_MODULE is set.
settings._setup()
except ImportError:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
else:
Loader = DjangoLoader
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
| <commit_before>import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
<commit_msg>Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.<commit_after> | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
try:
# A settings module may be defined, but Django didn't attempt to
# load it yet. As an alternative to calling the private _setup(),
# we could also check whether DJANGO_SETTINGS_MODULE is set.
settings._setup()
except ImportError:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
else:
Loader = DjangoLoader
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
| import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
try:
# A settings module may be defined, but Django didn't attempt to
# load it yet. As an alternative to calling the private _setup(),
# we could also check whether DJANGO_SETTINGS_MODULE is set.
settings._setup()
except ImportError:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
else:
Loader = DjangoLoader
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
| <commit_before>import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
<commit_msg>Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.<commit_after>import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loader = DjangoLoader
else:
try:
# A settings module may be defined, but Django didn't attempt to
# load it yet. As an alternative to calling the private _setup(),
# we could also check whether DJANGO_SETTINGS_MODULE is set.
settings._setup()
except ImportError:
if not callable(getattr(os, "fork", None)):
# Platform doesn't support fork()
# XXX On systems without fork, multiprocessing seems to be launching
# the processes in some other way which does not copy the memory
# of the parent process. This means that any configured env might
# be lost. This is a hack to make it work on Windows.
# A better way might be to use os.environ to set the currently
# used configuration method so to propogate it to the "child"
# processes. But this has to be experimented with.
# [asksol/heyman]
try:
settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings")
project_settings = __import__(settings_mod, {}, {}, [''])
setup_environ(project_settings)
Loader = DjangoLoader
except ImportError:
pass
else:
Loader = DjangoLoader
"""
.. data:: current_loader
The current loader instance.
"""
current_loader = Loader()
"""
.. data:: settings
The global settings object.
"""
settings = current_loader.conf
|
7d130a447786c61c7bfbe6bfe2d87b2c28e32eb6 | shut-up-bird.py | shut-up-bird.py | #!/usr/bin/env python
#
from __future__ import print_function
import os
import sys
import argparse
import logging
| #!/usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
import json
import tweepy
import pystache
import webbrowser
CONFIG_FILE = '.shut-up-bird.conf'
def tweep_login(consumer_key, consumer_secret, token='', secret=''):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
if token and secret:
auth.set_access_token(token, secret)
else:
try:
print ("Authenticating ...please wait")
redirect_url = auth.get_authorization_url()
print ("Opening url - {0} ...".format(redirect_url))
webbrowser.open(redirect_url)
verify_code = raw_input("Verification PIN code: ".format(redirect_url))
auth.get_access_token(verify_code)
except tweepy.TweepError as e:
raise Exception("Failed to get request token!", e)
return auth
def tweep_getAPI(auth):
api = tweepy.API(auth)
print("Authenticated as: {0}".format(api.me().screen_name))
return api
def tweep_delete(api):
print ("TEST")
def config_load(config_path):
if not os.path.exists(config_path):
return False
with open(config_path, 'r') as infile:
return json.load(infile)
def config_save(config_path, consumer_key, consumer_secret, token, secret):
data = {'ck': consumer_key, 'cs': consumer_secret, \
't': token, 's': secret }
with open(config_path, 'w') as outfile:
json.dump(data, outfile, indent=2, ensure_ascii=False)
def get_input(message):
return raw_input(message)
###########################
# Main
#
if __name__ == "__main__":
try:
home_dir = os.path.expanduser('~')
config = config_load(os.path.join(home_dir, CONFIG_FILE))
if (config and config['t'] and config['s']):
auth = tweep_login(config['ck'], config['cs'], config['t'], config['s'])
else:
print ("Please provide your Twitter app access keys\n")
consumer_key = get_input("Consumer Key (API Key): ")
consumer_secret = get_input("Consumer Secret (API Secret): ")
auth = tweep_login(consumer_key, consumer_secret)
config_save(os.path.join(home_dir, CONFIG_FILE), consumer_key, \
consumer_secret, auth.access_token, auth.access_token_secret)
api = tweep_getAPI(auth)
except Exception as e:
print ("[ERROR] {0}".format(e))
| Add OAuth authentication and config settings load/save | Add OAuth authentication and config settings load/save
| Python | mit | petarov/shut-up-bird | #!/usr/bin/env python
#
from __future__ import print_function
import os
import sys
import argparse
import logging
Add OAuth authentication and config settings load/save | #!/usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
import json
import tweepy
import pystache
import webbrowser
CONFIG_FILE = '.shut-up-bird.conf'
def tweep_login(consumer_key, consumer_secret, token='', secret=''):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
if token and secret:
auth.set_access_token(token, secret)
else:
try:
print ("Authenticating ...please wait")
redirect_url = auth.get_authorization_url()
print ("Opening url - {0} ...".format(redirect_url))
webbrowser.open(redirect_url)
verify_code = raw_input("Verification PIN code: ".format(redirect_url))
auth.get_access_token(verify_code)
except tweepy.TweepError as e:
raise Exception("Failed to get request token!", e)
return auth
def tweep_getAPI(auth):
api = tweepy.API(auth)
print("Authenticated as: {0}".format(api.me().screen_name))
return api
def tweep_delete(api):
print ("TEST")
def config_load(config_path):
if not os.path.exists(config_path):
return False
with open(config_path, 'r') as infile:
return json.load(infile)
def config_save(config_path, consumer_key, consumer_secret, token, secret):
data = {'ck': consumer_key, 'cs': consumer_secret, \
't': token, 's': secret }
with open(config_path, 'w') as outfile:
json.dump(data, outfile, indent=2, ensure_ascii=False)
def get_input(message):
return raw_input(message)
###########################
# Main
#
if __name__ == "__main__":
try:
home_dir = os.path.expanduser('~')
config = config_load(os.path.join(home_dir, CONFIG_FILE))
if (config and config['t'] and config['s']):
auth = tweep_login(config['ck'], config['cs'], config['t'], config['s'])
else:
print ("Please provide your Twitter app access keys\n")
consumer_key = get_input("Consumer Key (API Key): ")
consumer_secret = get_input("Consumer Secret (API Secret): ")
auth = tweep_login(consumer_key, consumer_secret)
config_save(os.path.join(home_dir, CONFIG_FILE), consumer_key, \
consumer_secret, auth.access_token, auth.access_token_secret)
api = tweep_getAPI(auth)
except Exception as e:
print ("[ERROR] {0}".format(e))
| <commit_before>#!/usr/bin/env python
#
from __future__ import print_function
import os
import sys
import argparse
import logging
<commit_msg>Add OAuth authentication and config settings load/save<commit_after> | #!/usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
import json
import tweepy
import pystache
import webbrowser
CONFIG_FILE = '.shut-up-bird.conf'
def tweep_login(consumer_key, consumer_secret, token='', secret=''):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
if token and secret:
auth.set_access_token(token, secret)
else:
try:
print ("Authenticating ...please wait")
redirect_url = auth.get_authorization_url()
print ("Opening url - {0} ...".format(redirect_url))
webbrowser.open(redirect_url)
verify_code = raw_input("Verification PIN code: ".format(redirect_url))
auth.get_access_token(verify_code)
except tweepy.TweepError as e:
raise Exception("Failed to get request token!", e)
return auth
def tweep_getAPI(auth):
api = tweepy.API(auth)
print("Authenticated as: {0}".format(api.me().screen_name))
return api
def tweep_delete(api):
print ("TEST")
def config_load(config_path):
if not os.path.exists(config_path):
return False
with open(config_path, 'r') as infile:
return json.load(infile)
def config_save(config_path, consumer_key, consumer_secret, token, secret):
data = {'ck': consumer_key, 'cs': consumer_secret, \
't': token, 's': secret }
with open(config_path, 'w') as outfile:
json.dump(data, outfile, indent=2, ensure_ascii=False)
def get_input(message):
return raw_input(message)
###########################
# Main
#
if __name__ == "__main__":
try:
home_dir = os.path.expanduser('~')
config = config_load(os.path.join(home_dir, CONFIG_FILE))
if (config and config['t'] and config['s']):
auth = tweep_login(config['ck'], config['cs'], config['t'], config['s'])
else:
print ("Please provide your Twitter app access keys\n")
consumer_key = get_input("Consumer Key (API Key): ")
consumer_secret = get_input("Consumer Secret (API Secret): ")
auth = tweep_login(consumer_key, consumer_secret)
config_save(os.path.join(home_dir, CONFIG_FILE), consumer_key, \
consumer_secret, auth.access_token, auth.access_token_secret)
api = tweep_getAPI(auth)
except Exception as e:
print ("[ERROR] {0}".format(e))
| #!/usr/bin/env python
#
from __future__ import print_function
import os
import sys
import argparse
import logging
Add OAuth authentication and config settings load/save#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
import json
import tweepy
import pystache
import webbrowser
CONFIG_FILE = '.shut-up-bird.conf'
def tweep_login(consumer_key, consumer_secret, token='', secret=''):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
if token and secret:
auth.set_access_token(token, secret)
else:
try:
print ("Authenticating ...please wait")
redirect_url = auth.get_authorization_url()
print ("Opening url - {0} ...".format(redirect_url))
webbrowser.open(redirect_url)
verify_code = raw_input("Verification PIN code: ".format(redirect_url))
auth.get_access_token(verify_code)
except tweepy.TweepError as e:
raise Exception("Failed to get request token!", e)
return auth
def tweep_getAPI(auth):
api = tweepy.API(auth)
print("Authenticated as: {0}".format(api.me().screen_name))
return api
def tweep_delete(api):
print ("TEST")
def config_load(config_path):
if not os.path.exists(config_path):
return False
with open(config_path, 'r') as infile:
return json.load(infile)
def config_save(config_path, consumer_key, consumer_secret, token, secret):
data = {'ck': consumer_key, 'cs': consumer_secret, \
't': token, 's': secret }
with open(config_path, 'w') as outfile:
json.dump(data, outfile, indent=2, ensure_ascii=False)
def get_input(message):
return raw_input(message)
###########################
# Main
#
if __name__ == "__main__":
try:
home_dir = os.path.expanduser('~')
config = config_load(os.path.join(home_dir, CONFIG_FILE))
if (config and config['t'] and config['s']):
auth = tweep_login(config['ck'], config['cs'], config['t'], config['s'])
else:
print ("Please provide your Twitter app access keys\n")
consumer_key = get_input("Consumer Key (API Key): ")
consumer_secret = get_input("Consumer Secret (API Secret): ")
auth = tweep_login(consumer_key, consumer_secret)
config_save(os.path.join(home_dir, CONFIG_FILE), consumer_key, \
consumer_secret, auth.access_token, auth.access_token_secret)
api = tweep_getAPI(auth)
except Exception as e:
print ("[ERROR] {0}".format(e))
| <commit_before>#!/usr/bin/env python
#
from __future__ import print_function
import os
import sys
import argparse
import logging
<commit_msg>Add OAuth authentication and config settings load/save<commit_after>#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
import json
import tweepy
import pystache
import webbrowser
CONFIG_FILE = '.shut-up-bird.conf'
def tweep_login(consumer_key, consumer_secret, token='', secret=''):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
if token and secret:
auth.set_access_token(token, secret)
else:
try:
print ("Authenticating ...please wait")
redirect_url = auth.get_authorization_url()
print ("Opening url - {0} ...".format(redirect_url))
webbrowser.open(redirect_url)
verify_code = raw_input("Verification PIN code: ".format(redirect_url))
auth.get_access_token(verify_code)
except tweepy.TweepError as e:
raise Exception("Failed to get request token!", e)
return auth
def tweep_getAPI(auth):
api = tweepy.API(auth)
print("Authenticated as: {0}".format(api.me().screen_name))
return api
def tweep_delete(api):
print ("TEST")
def config_load(config_path):
if not os.path.exists(config_path):
return False
with open(config_path, 'r') as infile:
return json.load(infile)
def config_save(config_path, consumer_key, consumer_secret, token, secret):
data = {'ck': consumer_key, 'cs': consumer_secret, \
't': token, 's': secret }
with open(config_path, 'w') as outfile:
json.dump(data, outfile, indent=2, ensure_ascii=False)
def get_input(message):
return raw_input(message)
###########################
# Main
#
if __name__ == "__main__":
try:
home_dir = os.path.expanduser('~')
config = config_load(os.path.join(home_dir, CONFIG_FILE))
if (config and config['t'] and config['s']):
auth = tweep_login(config['ck'], config['cs'], config['t'], config['s'])
else:
print ("Please provide your Twitter app access keys\n")
consumer_key = get_input("Consumer Key (API Key): ")
consumer_secret = get_input("Consumer Secret (API Secret): ")
auth = tweep_login(consumer_key, consumer_secret)
config_save(os.path.join(home_dir, CONFIG_FILE), consumer_key, \
consumer_secret, auth.access_token, auth.access_token_secret)
api = tweep_getAPI(auth)
except Exception as e:
print ("[ERROR] {0}".format(e))
|
f2a31c4a203d06fd83086f3789e52be94320c691 | tests/test_utils/__init__.py | tests/test_utils/__init__.py | import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
self.app = app.app.test_client()
configobj.backup()
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
| import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "deployment"))
import fix_paths
import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
configobj.backup()
self.app = app.app.test_client()
app.app.config["SECRET_KEY"] = "testing_key"
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
| Fix tests for new deployment | Fix tests for new deployment
| Python | mit | getslash/mailboxer,getslash/mailboxer,getslash/mailboxer,vmalloc/mailboxer,vmalloc/mailboxer,vmalloc/mailboxer | import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
self.app = app.app.test_client()
configobj.backup()
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
Fix tests for new deployment | import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "deployment"))
import fix_paths
import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
configobj.backup()
self.app = app.app.test_client()
app.app.config["SECRET_KEY"] = "testing_key"
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
| <commit_before>import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
self.app = app.app.test_client()
configobj.backup()
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
<commit_msg>Fix tests for new deployment<commit_after> | import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "deployment"))
import fix_paths
import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
configobj.backup()
self.app = app.app.test_client()
app.app.config["SECRET_KEY"] = "testing_key"
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
| import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
self.app = app.app.test_client()
configobj.backup()
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
Fix tests for new deploymentimport sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "deployment"))
import fix_paths
import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
configobj.backup()
self.app = app.app.test_client()
app.app.config["SECRET_KEY"] = "testing_key"
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
| <commit_before>import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
self.app = app.app.test_client()
configobj.backup()
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
<commit_msg>Fix tests for new deployment<commit_after>import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "deployment"))
import fix_paths
import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
configobj.backup()
self.app = app.app.test_client()
app.app.config["SECRET_KEY"] = "testing_key"
def tearDown(self):
configobj.restore()
super(TestCase, self).setUp()
|
7f9c9b947948654d7557aa0fcfbb1c015521da9b | tests/modular_templates/routing.py | tests/modular_templates/routing.py | import unittest
from framework.routing import Rule
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func'),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func)) | import unittest
from framework.routing import Rule, json_renderer
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func', json_renderer),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func))
| Fix RuleTestCase -> tests passing | Fix RuleTestCase -> tests passing
| Python | apache-2.0 | caneruguz/osf.io,brandonPurvis/osf.io,rdhyee/osf.io,KAsante95/osf.io,pattisdr/osf.io,KAsante95/osf.io,barbour-em/osf.io,HarryRybacki/osf.io,mluke93/osf.io,aaxelb/osf.io,jinluyuan/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,sbt9uc/osf.io,ticklemepierce/osf.io,jnayak1/osf.io,caseyrygt/osf.io,kwierman/osf.io,adlius/osf.io,baylee-d/osf.io,alexschiller/osf.io,rdhyee/osf.io,DanielSBrown/osf.io,danielneis/osf.io,leb2dg/osf.io,alexschiller/osf.io,ZobairAlijan/osf.io,jinluyuan/osf.io,danielneis/osf.io,emetsger/osf.io,DanielSBrown/osf.io,samchrisinger/osf.io,zamattiac/osf.io,amyshi188/osf.io,dplorimer/osf,brianjgeiger/osf.io,kwierman/osf.io,danielneis/osf.io,cosenal/osf.io,arpitar/osf.io,njantrania/osf.io,caneruguz/osf.io,saradbowman/osf.io,KAsante95/osf.io,Nesiehr/osf.io,adlius/osf.io,mluke93/osf.io,billyhunt/osf.io,jmcarp/osf.io,bdyetton/prettychart,baylee-d/osf.io,fabianvf/osf.io,zachjanicki/osf.io,hmoco/osf.io,zamattiac/osf.io,cwisecarver/osf.io,brandonPurvis/osf.io,lamdnhan/osf.io,zkraime/osf.io,HarryRybacki/osf.io,sbt9uc/osf.io,mattclark/osf.io,acshi/osf.io,haoyuchen1992/osf.io,mluo613/osf.io,caseyrygt/osf.io,Nesiehr/osf.io,zkraime/osf.io,zamattiac/osf.io,alexschiller/osf.io,acshi/osf.io,ckc6cz/osf.io,zkraime/osf.io,himanshuo/osf.io,ckc6cz/osf.io,monikagrabowska/osf.io,brandonPurvis/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,DanielSBrown/osf.io,lamdnhan/osf.io,Ghalko/osf.io,chrisseto/osf.io,jolene-esposito/osf.io,mfraezz/osf.io,erinspace/osf.io,njantrania/osf.io,lamdnhan/osf.io,GaryKriebel/osf.io,abought/osf.io,brandonPurvis/osf.io,jnayak1/osf.io,RomanZWang/osf.io,mfraezz/osf.io,TomBaxter/osf.io,sloria/osf.io,acshi/osf.io,jolene-esposito/osf.io,jeffreyliu3230/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,Ghalko/osf.io,TomHeatwole/osf.io,bdyetton/prettychart,mluo613/osf.io,RomanZWang/osf.io,himanshuo/osf.io,erinspace/osf.io,barbour-em/osf.io,crcresearch/osf.io,doublebits/osf.io,RomanZWang/osf.io,Johnetordoff/osf.io,doublebits/osf.io,abought/osf.io,chennan47/osf.io,lamdnhan/osf.io,revanthkolli/osf.io,hmoco/osf.io,asanfilippo7/osf.io,ckc6cz/osf.io,caseyrygt/osf.io,AndrewSallans/osf.io,doublebits/osf.io,caseyrygt/osf.io,baylee-d/osf.io,cldershem/osf.io,HarryRybacki/osf.io,dplorimer/osf,felliott/osf.io,leb2dg/osf.io,MerlinZhang/osf.io,DanielSBrown/osf.io,haoyuchen1992/osf.io,petermalcolm/osf.io,ticklemepierce/osf.io,emetsger/osf.io,jnayak1/osf.io,doublebits/osf.io,dplorimer/osf,amyshi188/osf.io,GaryKriebel/osf.io,billyhunt/osf.io,CenterForOpenScience/osf.io,njantrania/osf.io,asanfilippo7/osf.io,rdhyee/osf.io,SSJohns/osf.io,zachjanicki/osf.io,GageGaskins/osf.io,brianjgeiger/osf.io,hmoco/osf.io,aaxelb/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,MerlinZhang/osf.io,billyhunt/osf.io,icereval/osf.io,monikagrabowska/osf.io,revanthkolli/osf.io,cldershem/osf.io,mattclark/osf.io,jinluyuan/osf.io,pattisdr/osf.io,brandonPurvis/osf.io,danielneis/osf.io,fabianvf/osf.io,arpitar/osf.io,jeffreyliu3230/osf.io,billyhunt/osf.io,laurenrevere/osf.io,samanehsan/osf.io,adlius/osf.io,ZobairAlijan/osf.io,kushG/osf.io,amyshi188/osf.io,mluo613/osf.io,reinaH/osf.io,mluo613/osf.io,petermalcolm/osf.io,kushG/osf.io,mfraezz/osf.io,himanshuo/osf.io,abought/osf.io,cosenal/osf.io,GaryKriebel/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,TomHeatwole/osf.io,cosenal/osf.io,jmcarp/osf.io,fabianvf/osf.io,acshi/osf.io,icereval/osf.io,monikagrabowska/osf.io,binoculars/osf.io,caseyrollins/osf.io,doublebits/osf.io,SSJohns/osf.io,acshi/osf.io,cslzchen/osf.io,aaxelb/osf.io,binoculars/osf.io,adlius/osf.io,himanshuo/osf.io,ticklemepierce/osf.io,GageGaskins/osf.io,TomBaxter/osf.io,TomHeatwole/osf.io,abought/osf.io,fabianvf/osf.io,reinaH/osf.io,alexschiller/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,HarryRybacki/osf.io,GageGaskins/osf.io,monikagrabowska/osf.io,billyhunt/osf.io,brianjgeiger/osf.io,kwierman/osf.io,felliott/osf.io,samanehsan/osf.io,RomanZWang/osf.io,mluo613/osf.io,caneruguz/osf.io,lyndsysimon/osf.io,cldershem/osf.io,cslzchen/osf.io,kushG/osf.io,barbour-em/osf.io,lyndsysimon/osf.io,chrisseto/osf.io,zachjanicki/osf.io,crcresearch/osf.io,zachjanicki/osf.io,sbt9uc/osf.io,KAsante95/osf.io,sbt9uc/osf.io,hmoco/osf.io,zamattiac/osf.io,zkraime/osf.io,jnayak1/osf.io,emetsger/osf.io,asanfilippo7/osf.io,jeffreyliu3230/osf.io,ticklemepierce/osf.io,kch8qx/osf.io,cosenal/osf.io,dplorimer/osf,jolene-esposito/osf.io,laurenrevere/osf.io,jeffreyliu3230/osf.io,GaryKriebel/osf.io,lyndsysimon/osf.io,samanehsan/osf.io,lyndsysimon/osf.io,wearpants/osf.io,saradbowman/osf.io,bdyetton/prettychart,caseyrollins/osf.io,jinluyuan/osf.io,TomBaxter/osf.io,samchrisinger/osf.io,icereval/osf.io,ckc6cz/osf.io,samchrisinger/osf.io,caseyrollins/osf.io,laurenrevere/osf.io,njantrania/osf.io,chrisseto/osf.io,caneruguz/osf.io,arpitar/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,haoyuchen1992/osf.io,kch8qx/osf.io,SSJohns/osf.io,chrisseto/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,felliott/osf.io,petermalcolm/osf.io,emetsger/osf.io,cwisecarver/osf.io,kushG/osf.io,petermalcolm/osf.io,erinspace/osf.io,kch8qx/osf.io,arpitar/osf.io,jolene-esposito/osf.io,cldershem/osf.io,KAsante95/osf.io,binoculars/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,SSJohns/osf.io,felliott/osf.io,wearpants/osf.io,Nesiehr/osf.io,reinaH/osf.io,crcresearch/osf.io,Ghalko/osf.io,kch8qx/osf.io,RomanZWang/osf.io,barbour-em/osf.io,Nesiehr/osf.io,kwierman/osf.io,revanthkolli/osf.io,cwisecarver/osf.io,chennan47/osf.io,haoyuchen1992/osf.io,samanehsan/osf.io,alexschiller/osf.io,Ghalko/osf.io,rdhyee/osf.io,sloria/osf.io,reinaH/osf.io,kch8qx/osf.io,amyshi188/osf.io,cslzchen/osf.io,jmcarp/osf.io,bdyetton/prettychart,mluke93/osf.io,cslzchen/osf.io,chennan47/osf.io,sloria/osf.io,GageGaskins/osf.io,jmcarp/osf.io,AndrewSallans/osf.io,TomHeatwole/osf.io,wearpants/osf.io,mluke93/osf.io,samchrisinger/osf.io,CenterForOpenScience/osf.io,revanthkolli/osf.io,asanfilippo7/osf.io,CenterForOpenScience/osf.io,MerlinZhang/osf.io,MerlinZhang/osf.io | import unittest
from framework.routing import Rule
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func'),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func))Fix RuleTestCase -> tests passing | import unittest
from framework.routing import Rule, json_renderer
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func', json_renderer),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func))
| <commit_before>import unittest
from framework.routing import Rule
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func'),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func))<commit_msg>Fix RuleTestCase -> tests passing<commit_after> | import unittest
from framework.routing import Rule, json_renderer
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func', json_renderer),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func))
| import unittest
from framework.routing import Rule
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func'),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func))Fix RuleTestCase -> tests passingimport unittest
from framework.routing import Rule, json_renderer
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func', json_renderer),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func))
| <commit_before>import unittest
from framework.routing import Rule
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func'),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func))<commit_msg>Fix RuleTestCase -> tests passing<commit_after>import unittest
from framework.routing import Rule, json_renderer
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),
kwargs.get('render_func', json_renderer),
kwargs.get('view_kwargs'),
)
def test_rule_single_route(self):
r = self._make_rule(routes='/')
self.assertEqual(r.routes, ['/', ])
def test_rule_single_method(self):
r = self._make_rule(methods='GET')
self.assertEqual(r.methods, ['GET', ])
def test_rule_lambda_view(self):
r = self._make_rule(view_func=lambda: '')
self.assertTrue(callable(r.view_func))
|
507b8bb0910ef6fae9c7d9cb1405a33c4e4b6e8e | synapse/config/password.py | synapse/config/password.py | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
""" | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# Change to a secret random string.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
""" | Add comment to prompt changing of pepper | Add comment to prompt changing of pepper
| Python | apache-2.0 | matrix-org/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,TribeMedia/synapse,TribeMedia/synapse,TribeMedia/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
"""Add comment to prompt changing of pepper | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# Change to a secret random string.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
""" | <commit_before># -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
"""<commit_msg>Add comment to prompt changing of pepper<commit_after> | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# Change to a secret random string.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
""" | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
"""Add comment to prompt changing of pepper# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# Change to a secret random string.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
""" | <commit_before># -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
"""<commit_msg>Add comment to prompt changing of pepper<commit_after># -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# 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 ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# Change to a secret random string.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
""" |
389679c0fc575bb03bfa4e625de16eb7ed9c3a04 | testdoc/formatter.py | testdoc/formatter.py | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
| """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('')
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
| Put a blank line before section headings, courtesy spiv. | Put a blank line before section headings, courtesy spiv.
| Python | mit | testing-cabal/testdoc | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
Put a blank line before section headings, courtesy spiv. | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('')
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
| <commit_before>"""Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
<commit_msg>Put a blank line before section headings, courtesy spiv.<commit_after> | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('')
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
| """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
Put a blank line before section headings, courtesy spiv."""Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('')
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
| <commit_before>"""Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
<commit_msg>Put a blank line before section headings, courtesy spiv.<commit_after>"""Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('')
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
|
20ed56d04f029fa4121b23db94dda19167fd054e | uchicagohvz/production_settings.py | uchicagohvz/production_settings.py | from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True | from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
#EMAIL_HOST = 'smtp.mandrillapp.com'
#EMAIL_PORT = '587'
EMAIL_HOST = 'localhost'
#EMAIL_USE_TLS = True
| Change over to local email server in production | Change over to local email server in production
| Python | mit | kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz | from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = TrueChange over to local email server in production | from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
#EMAIL_HOST = 'smtp.mandrillapp.com'
#EMAIL_PORT = '587'
EMAIL_HOST = 'localhost'
#EMAIL_USE_TLS = True
| <commit_before>from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True<commit_msg>Change over to local email server in production<commit_after> | from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
#EMAIL_HOST = 'smtp.mandrillapp.com'
#EMAIL_PORT = '587'
EMAIL_HOST = 'localhost'
#EMAIL_USE_TLS = True
| from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = TrueChange over to local email server in productionfrom local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
#EMAIL_HOST = 'smtp.mandrillapp.com'
#EMAIL_PORT = '587'
EMAIL_HOST = 'localhost'
#EMAIL_USE_TLS = True
| <commit_before>from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.mandrillapp.com'
from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
EMAIL_PORT = '587'
EMAIL_USE_TLS = True<commit_msg>Change over to local email server in production<commit_after>from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'uchicagohvz', # Or path to database file if using sqlite3.
'USER': 'user', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# REST framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
#EMAIL_HOST = 'smtp.mandrillapp.com'
#EMAIL_PORT = '587'
EMAIL_HOST = 'localhost'
#EMAIL_USE_TLS = True
|
30b6d886670b7ba65aee9b130ec50d577c778649 | run_server.py | run_server.py | #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
| Add a message with a socket on server start | Add a message with a socket on server start
| Python | mit | bondarevts/flucalc,bondarevts/flucalc,bondarevts/flucalc | #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
Add a message with a socket on server start | #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
<commit_msg>Add a message with a socket on server start<commit_after> | #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
Add a message with a socket on server start#!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
<commit_msg>Add a message with a socket on server start<commit_after>#!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
|
dc09143973640b2873dae7434ce654535fbfdd8c | qtpy/tests/test_qtwebenginewidgets.py | qtpy/tests/test_qtwebenginewidgets.py | from __future__ import absolute_import
import pytest
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
from qtpy import QtWebEngineWidgets
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
| from __future__ import absolute_import
import pytest
from qtpy import QtWebEngineWidgets
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
| Fix failing tests in Python 2 | Tesitng: Fix failing tests in Python 2
| Python | mit | goanpeca/qtpy,goanpeca/qtpy,davvid/qtpy,spyder-ide/qtpy,davvid/qtpy | from __future__ import absolute_import
import pytest
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
from qtpy import QtWebEngineWidgets
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
Tesitng: Fix failing tests in Python 2 | from __future__ import absolute_import
import pytest
from qtpy import QtWebEngineWidgets
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
| <commit_before>from __future__ import absolute_import
import pytest
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
from qtpy import QtWebEngineWidgets
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
<commit_msg>Tesitng: Fix failing tests in Python 2<commit_after> | from __future__ import absolute_import
import pytest
from qtpy import QtWebEngineWidgets
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
| from __future__ import absolute_import
import pytest
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
from qtpy import QtWebEngineWidgets
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
Tesitng: Fix failing tests in Python 2from __future__ import absolute_import
import pytest
from qtpy import QtWebEngineWidgets
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
| <commit_before>from __future__ import absolute_import
import pytest
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
from qtpy import QtWebEngineWidgets
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
<commit_msg>Tesitng: Fix failing tests in Python 2<commit_after>from __future__ import absolute_import
import pytest
from qtpy import QtWebEngineWidgets
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebEngineSettings is not None
|
722b588629fa0986e8d7c06ff135d81c08ad8fab | tensorflow_datasets/object_detection/waymo_open_dataset_test.py | tensorflow_datasets/object_detection/waymo_open_dataset_test.py | # coding=utf-8
# Copyright 2020 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.
"""TODO(waymo_open_dataset): Add a description here."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
| # coding=utf-8
# Copyright 2020 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.
# Lint as: python3
"""Test for waymo_open_dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
| Add doc string for waymo open dataset | Add doc string for waymo open dataset | Python | apache-2.0 | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets | # coding=utf-8
# Copyright 2020 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.
"""TODO(waymo_open_dataset): Add a description here."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
Add doc string for waymo open dataset | # coding=utf-8
# Copyright 2020 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.
# Lint as: python3
"""Test for waymo_open_dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
| <commit_before># coding=utf-8
# Copyright 2020 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.
"""TODO(waymo_open_dataset): Add a description here."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
<commit_msg>Add doc string for waymo open dataset<commit_after> | # coding=utf-8
# Copyright 2020 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.
# Lint as: python3
"""Test for waymo_open_dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
| # coding=utf-8
# Copyright 2020 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.
"""TODO(waymo_open_dataset): Add a description here."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
Add doc string for waymo open dataset# coding=utf-8
# Copyright 2020 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.
# Lint as: python3
"""Test for waymo_open_dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
| <commit_before># coding=utf-8
# Copyright 2020 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.
"""TODO(waymo_open_dataset): Add a description here."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
<commit_msg>Add doc string for waymo open dataset<commit_after># coding=utf-8
# Copyright 2020 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.
# Lint as: python3
"""Test for waymo_open_dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow_datasets import testing
from tensorflow_datasets.object_detection import waymo_open_dataset
class WaymoOpenDatasetTest(testing.DatasetBuilderTestCase):
DATASET_CLASS = waymo_open_dataset.WaymoOpenDataset
SPLITS = {
"train": 1, # Number of fake train example
"validation": 1, # Number of fake test example
}
def setUp(self):
super(WaymoOpenDatasetTest, self).setUp()
self.builder._CLOUD_BUCKET = self.example_dir
if __name__ == "__main__":
testing.test_main()
|
3d83904e409eecfd44b0c0ca053f78da5c9c89a4 | tests/test-vext-cmdline.py | tests/test-vext-cmdline.py | import unittest
from vext.cmdline import do_check
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
if __name__ == "__main__":
unittest.main()
| import unittest
from vext.cmdline import do_check, do_status
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
def test_do_status(self):
# Stub check: verifies no exceptions are thrown.
# TODO, trigger different statuses and check messages printed.
do_status()
if __name__ == "__main__":
unittest.main()
| Add stub test for do_status | Add stub test for do_status
| Python | mit | stuaxo/vext | import unittest
from vext.cmdline import do_check
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
if __name__ == "__main__":
unittest.main()
Add stub test for do_status | import unittest
from vext.cmdline import do_check, do_status
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
def test_do_status(self):
# Stub check: verifies no exceptions are thrown.
# TODO, trigger different statuses and check messages printed.
do_status()
if __name__ == "__main__":
unittest.main()
| <commit_before>import unittest
from vext.cmdline import do_check
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
if __name__ == "__main__":
unittest.main()
<commit_msg>Add stub test for do_status<commit_after> | import unittest
from vext.cmdline import do_check, do_status
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
def test_do_status(self):
# Stub check: verifies no exceptions are thrown.
# TODO, trigger different statuses and check messages printed.
do_status()
if __name__ == "__main__":
unittest.main()
| import unittest
from vext.cmdline import do_check
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
if __name__ == "__main__":
unittest.main()
Add stub test for do_statusimport unittest
from vext.cmdline import do_check, do_status
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
def test_do_status(self):
# Stub check: verifies no exceptions are thrown.
# TODO, trigger different statuses and check messages printed.
do_status()
if __name__ == "__main__":
unittest.main()
| <commit_before>import unittest
from vext.cmdline import do_check
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
if __name__ == "__main__":
unittest.main()
<commit_msg>Add stub test for do_status<commit_after>import unittest
from vext.cmdline import do_check, do_status
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
def test_do_status(self):
# Stub check: verifies no exceptions are thrown.
# TODO, trigger different statuses and check messages printed.
do_status()
if __name__ == "__main__":
unittest.main()
|
35a7e3e892135d805dfe73b8ce66f986651354f5 | tests/test_gutenbergweb.py | tests/test_gutenbergweb.py | from nose import *
import gutenberweb
def test_foo():
print "BAR"
if __name__ == "__main__":
main()
| import gutenbrowse.gutenbergweb as gutenbergweb
def test_search_author():
r = gutenbergweb.search(author='Nietzsche')
assert len(r) >= 4, r
assert any(eid == 19634 for eid,au,tt,lng in r), r
assert all(isinstance(eid, int) and isinstance(au, unicode)
and isinstance(tt, unicode) and isinstance(lng, unicode)
for eid,au,tt,lng in r), r
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert any(u"Thus Spake Zarathustra" in tt for eid,au,tt,lng in r), r
assert any(u"English" == lng for eid,au,tt,lng in r), r
assert any(u"German" == lng for eid,au,tt,lng in r), r
def test_search_title():
r = gutenbergweb.search(title="Beyond Good and Evil")
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert all(u"English" == lng for eid,au,tt,lng in r), r
def test_search_etextnr():
r = gutenbergweb.search(etextnr=1234)
assert len(r) == 1
eid, au, tt, lng = r[0]
assert eid == 1234, r
assert au == u"Conant, James Bryant, 1893-1978 [Editor]", r
assert tt == u"Organic Syntheses", r
assert lng == u"English", r
def test_info():
r = gutenbergweb.etext_info(19634)
assert len(r) >= 4, r
assert any('19634' in url for url,fmt,enc,comp in r), r
assert any(fmt == 'plain text' for url,fmt,enc,comp in r), r
assert any(enc == 'us-ascii' for url,fmt,enc,comp in r), r
assert any(comp == 'none' for url,fmt,enc,comp in r), r
| Add proper tests for gutenbergweb | Add proper tests for gutenbergweb
| Python | bsd-3-clause | pv/mgutenberg,pv/mgutenberg | from nose import *
import gutenberweb
def test_foo():
print "BAR"
if __name__ == "__main__":
main()
Add proper tests for gutenbergweb | import gutenbrowse.gutenbergweb as gutenbergweb
def test_search_author():
r = gutenbergweb.search(author='Nietzsche')
assert len(r) >= 4, r
assert any(eid == 19634 for eid,au,tt,lng in r), r
assert all(isinstance(eid, int) and isinstance(au, unicode)
and isinstance(tt, unicode) and isinstance(lng, unicode)
for eid,au,tt,lng in r), r
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert any(u"Thus Spake Zarathustra" in tt for eid,au,tt,lng in r), r
assert any(u"English" == lng for eid,au,tt,lng in r), r
assert any(u"German" == lng for eid,au,tt,lng in r), r
def test_search_title():
r = gutenbergweb.search(title="Beyond Good and Evil")
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert all(u"English" == lng for eid,au,tt,lng in r), r
def test_search_etextnr():
r = gutenbergweb.search(etextnr=1234)
assert len(r) == 1
eid, au, tt, lng = r[0]
assert eid == 1234, r
assert au == u"Conant, James Bryant, 1893-1978 [Editor]", r
assert tt == u"Organic Syntheses", r
assert lng == u"English", r
def test_info():
r = gutenbergweb.etext_info(19634)
assert len(r) >= 4, r
assert any('19634' in url for url,fmt,enc,comp in r), r
assert any(fmt == 'plain text' for url,fmt,enc,comp in r), r
assert any(enc == 'us-ascii' for url,fmt,enc,comp in r), r
assert any(comp == 'none' for url,fmt,enc,comp in r), r
| <commit_before>from nose import *
import gutenberweb
def test_foo():
print "BAR"
if __name__ == "__main__":
main()
<commit_msg>Add proper tests for gutenbergweb<commit_after> | import gutenbrowse.gutenbergweb as gutenbergweb
def test_search_author():
r = gutenbergweb.search(author='Nietzsche')
assert len(r) >= 4, r
assert any(eid == 19634 for eid,au,tt,lng in r), r
assert all(isinstance(eid, int) and isinstance(au, unicode)
and isinstance(tt, unicode) and isinstance(lng, unicode)
for eid,au,tt,lng in r), r
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert any(u"Thus Spake Zarathustra" in tt for eid,au,tt,lng in r), r
assert any(u"English" == lng for eid,au,tt,lng in r), r
assert any(u"German" == lng for eid,au,tt,lng in r), r
def test_search_title():
r = gutenbergweb.search(title="Beyond Good and Evil")
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert all(u"English" == lng for eid,au,tt,lng in r), r
def test_search_etextnr():
r = gutenbergweb.search(etextnr=1234)
assert len(r) == 1
eid, au, tt, lng = r[0]
assert eid == 1234, r
assert au == u"Conant, James Bryant, 1893-1978 [Editor]", r
assert tt == u"Organic Syntheses", r
assert lng == u"English", r
def test_info():
r = gutenbergweb.etext_info(19634)
assert len(r) >= 4, r
assert any('19634' in url for url,fmt,enc,comp in r), r
assert any(fmt == 'plain text' for url,fmt,enc,comp in r), r
assert any(enc == 'us-ascii' for url,fmt,enc,comp in r), r
assert any(comp == 'none' for url,fmt,enc,comp in r), r
| from nose import *
import gutenberweb
def test_foo():
print "BAR"
if __name__ == "__main__":
main()
Add proper tests for gutenbergwebimport gutenbrowse.gutenbergweb as gutenbergweb
def test_search_author():
r = gutenbergweb.search(author='Nietzsche')
assert len(r) >= 4, r
assert any(eid == 19634 for eid,au,tt,lng in r), r
assert all(isinstance(eid, int) and isinstance(au, unicode)
and isinstance(tt, unicode) and isinstance(lng, unicode)
for eid,au,tt,lng in r), r
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert any(u"Thus Spake Zarathustra" in tt for eid,au,tt,lng in r), r
assert any(u"English" == lng for eid,au,tt,lng in r), r
assert any(u"German" == lng for eid,au,tt,lng in r), r
def test_search_title():
r = gutenbergweb.search(title="Beyond Good and Evil")
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert all(u"English" == lng for eid,au,tt,lng in r), r
def test_search_etextnr():
r = gutenbergweb.search(etextnr=1234)
assert len(r) == 1
eid, au, tt, lng = r[0]
assert eid == 1234, r
assert au == u"Conant, James Bryant, 1893-1978 [Editor]", r
assert tt == u"Organic Syntheses", r
assert lng == u"English", r
def test_info():
r = gutenbergweb.etext_info(19634)
assert len(r) >= 4, r
assert any('19634' in url for url,fmt,enc,comp in r), r
assert any(fmt == 'plain text' for url,fmt,enc,comp in r), r
assert any(enc == 'us-ascii' for url,fmt,enc,comp in r), r
assert any(comp == 'none' for url,fmt,enc,comp in r), r
| <commit_before>from nose import *
import gutenberweb
def test_foo():
print "BAR"
if __name__ == "__main__":
main()
<commit_msg>Add proper tests for gutenbergweb<commit_after>import gutenbrowse.gutenbergweb as gutenbergweb
def test_search_author():
r = gutenbergweb.search(author='Nietzsche')
assert len(r) >= 4, r
assert any(eid == 19634 for eid,au,tt,lng in r), r
assert all(isinstance(eid, int) and isinstance(au, unicode)
and isinstance(tt, unicode) and isinstance(lng, unicode)
for eid,au,tt,lng in r), r
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert any(u"Thus Spake Zarathustra" in tt for eid,au,tt,lng in r), r
assert any(u"English" == lng for eid,au,tt,lng in r), r
assert any(u"German" == lng for eid,au,tt,lng in r), r
def test_search_title():
r = gutenbergweb.search(title="Beyond Good and Evil")
assert all(u'Nietzsche, Friedrich Wilhelm' in au for eid,au,tt,lng in r), r
assert all(u"English" == lng for eid,au,tt,lng in r), r
def test_search_etextnr():
r = gutenbergweb.search(etextnr=1234)
assert len(r) == 1
eid, au, tt, lng = r[0]
assert eid == 1234, r
assert au == u"Conant, James Bryant, 1893-1978 [Editor]", r
assert tt == u"Organic Syntheses", r
assert lng == u"English", r
def test_info():
r = gutenbergweb.etext_info(19634)
assert len(r) >= 4, r
assert any('19634' in url for url,fmt,enc,comp in r), r
assert any(fmt == 'plain text' for url,fmt,enc,comp in r), r
assert any(enc == 'us-ascii' for url,fmt,enc,comp in r), r
assert any(comp == 'none' for url,fmt,enc,comp in r), r
|
c1928c65c308410205ff89a4be8910cd54614be0 | bbb/adc.py | bbb/adc.py | """Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self):
with open(self.sysfs, 'r') as f:
f.read()
val = None
# Read a second time to ensure current value (bug in ADC driver)
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
| """Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, repeat=8, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
self.repeat = repeat
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self, repeat=None):
if not repeat:
repeat = self.repeat
for i in range(repeat):
val = None
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
| Add repeat support when reading ADC values. | Add repeat support when reading ADC values.
- There is a bug in the ADC driver which allows reads to return stale or
otherwise incorrect readings. Though there doesn't appear to be a
guaranteed minimum count, repeating the read a number of times will
eventually yeild the correct value.
- Object initializtion now takes a default repeat count, which can
optionally be overridden in the read() call.
| Python | mit | IEEERobotics/pybbb | """Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self):
with open(self.sysfs, 'r') as f:
f.read()
val = None
# Read a second time to ensure current value (bug in ADC driver)
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
Add repeat support when reading ADC values.
- There is a bug in the ADC driver which allows reads to return stale or
otherwise incorrect readings. Though there doesn't appear to be a
guaranteed minimum count, repeating the read a number of times will
eventually yeild the correct value.
- Object initializtion now takes a default repeat count, which can
optionally be overridden in the read() call. | """Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, repeat=8, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
self.repeat = repeat
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self, repeat=None):
if not repeat:
repeat = self.repeat
for i in range(repeat):
val = None
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
| <commit_before>"""Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self):
with open(self.sysfs, 'r') as f:
f.read()
val = None
# Read a second time to ensure current value (bug in ADC driver)
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
<commit_msg>Add repeat support when reading ADC values.
- There is a bug in the ADC driver which allows reads to return stale or
otherwise incorrect readings. Though there doesn't appear to be a
guaranteed minimum count, repeating the read a number of times will
eventually yeild the correct value.
- Object initializtion now takes a default repeat count, which can
optionally be overridden in the read() call.<commit_after> | """Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, repeat=8, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
self.repeat = repeat
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self, repeat=None):
if not repeat:
repeat = self.repeat
for i in range(repeat):
val = None
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
| """Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self):
with open(self.sysfs, 'r') as f:
f.read()
val = None
# Read a second time to ensure current value (bug in ADC driver)
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
Add repeat support when reading ADC values.
- There is a bug in the ADC driver which allows reads to return stale or
otherwise incorrect readings. Though there doesn't appear to be a
guaranteed minimum count, repeating the read a number of times will
eventually yeild the correct value.
- Object initializtion now takes a default repeat count, which can
optionally be overridden in the read() call."""Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, repeat=8, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
self.repeat = repeat
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self, repeat=None):
if not repeat:
repeat = self.repeat
for i in range(repeat):
val = None
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
| <commit_before>"""Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self):
with open(self.sysfs, 'r') as f:
f.read()
val = None
# Read a second time to ensure current value (bug in ADC driver)
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
<commit_msg>Add repeat support when reading ADC values.
- There is a bug in the ADC driver which allows reads to return stale or
otherwise incorrect readings. Though there doesn't appear to be a
guaranteed minimum count, repeating the read a number of times will
eventually yeild the correct value.
- Object initializtion now takes a default repeat count, which can
optionally be overridden in the read() call.<commit_after>"""Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, repeat=8, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.glob(base_filename + str(num))[0]
self.repeat = repeat
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self, repeat=None):
if not repeat:
repeat = self.repeat
for i in range(repeat):
val = None
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
|
730aaf64635268df8d3c5cd3e1d5e2448644c907 | problem-static/Intro-Eval_50/admin/eval.py | problem-static/Intro-Eval_50/admin/eval.py | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(raw_input("What would you like to do? "))
result = str(eval(command))
print "This is the result: %s" %(result)
except Exception, e:
print "Invalid command!!!! EXITING!!!!!"
return
main() | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(input("What would you like to do? "))
print command
except Exception, e:
print "Invalid command!"
continue
main()
| Make Intro Eval use input instead of raw_input | Make Intro Eval use input instead of raw_input
| Python | mit | james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(raw_input("What would you like to do? "))
result = str(eval(command))
print "This is the result: %s" %(result)
except Exception, e:
print "Invalid command!!!! EXITING!!!!!"
return
main()Make Intro Eval use input instead of raw_input | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(input("What would you like to do? "))
print command
except Exception, e:
print "Invalid command!"
continue
main()
| <commit_before>#!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(raw_input("What would you like to do? "))
result = str(eval(command))
print "This is the result: %s" %(result)
except Exception, e:
print "Invalid command!!!! EXITING!!!!!"
return
main()<commit_msg>Make Intro Eval use input instead of raw_input<commit_after> | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(input("What would you like to do? "))
print command
except Exception, e:
print "Invalid command!"
continue
main()
| #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(raw_input("What would you like to do? "))
result = str(eval(command))
print "This is the result: %s" %(result)
except Exception, e:
print "Invalid command!!!! EXITING!!!!!"
return
main()Make Intro Eval use input instead of raw_input#!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(input("What would you like to do? "))
print command
except Exception, e:
print "Invalid command!"
continue
main()
| <commit_before>#!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(raw_input("What would you like to do? "))
result = str(eval(command))
print "This is the result: %s" %(result)
except Exception, e:
print "Invalid command!!!! EXITING!!!!!"
return
main()<commit_msg>Make Intro Eval use input instead of raw_input<commit_after>#!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
def main():
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
command = str(input("What would you like to do? "))
print command
except Exception, e:
print "Invalid command!"
continue
main()
|
4b687d702face412330580ed88f71c897dfa5e6a | nipy/core/image/__init__.py | nipy/core/image/__init__.py | """
The L{Image<image.Image>} class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
Class structure::
Application Level
TODO: I think this graph is unnecessary and wrong after removing
BaseImage, JT
----------------------
Image
|
o
|
BaseImage
|
|
------------
| |
Formats ArrayImage
|
Binary
|
------------------
| | |
Nifti Analyze ECAT
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| """
The Image class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from image import Image
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| Remove old doc. Import Image into core.image | Remove old doc. Import Image into core.image | Python | bsd-3-clause | bthirion/nipy,arokem/nipy,alexis-roche/register,alexis-roche/nireg,alexis-roche/register,arokem/nipy,nipy/nipy-labs,arokem/nipy,alexis-roche/niseg,alexis-roche/nipy,alexis-roche/nipy,alexis-roche/nireg,nipy/nireg,alexis-roche/register,bthirion/nipy,arokem/nipy,alexis-roche/niseg,nipy/nireg,bthirion/nipy,alexis-roche/nipy,alexis-roche/nipy,nipy/nipy-labs,bthirion/nipy | """
The L{Image<image.Image>} class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
Class structure::
Application Level
TODO: I think this graph is unnecessary and wrong after removing
BaseImage, JT
----------------------
Image
|
o
|
BaseImage
|
|
------------
| |
Formats ArrayImage
|
Binary
|
------------------
| | |
Nifti Analyze ECAT
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
Remove old doc. Import Image into core.image | """
The Image class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from image import Image
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| <commit_before>"""
The L{Image<image.Image>} class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
Class structure::
Application Level
TODO: I think this graph is unnecessary and wrong after removing
BaseImage, JT
----------------------
Image
|
o
|
BaseImage
|
|
------------
| |
Formats ArrayImage
|
Binary
|
------------------
| | |
Nifti Analyze ECAT
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
<commit_msg>Remove old doc. Import Image into core.image<commit_after> | """
The Image class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from image import Image
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| """
The L{Image<image.Image>} class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
Class structure::
Application Level
TODO: I think this graph is unnecessary and wrong after removing
BaseImage, JT
----------------------
Image
|
o
|
BaseImage
|
|
------------
| |
Formats ArrayImage
|
Binary
|
------------------
| | |
Nifti Analyze ECAT
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
Remove old doc. Import Image into core.image"""
The Image class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from image import Image
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| <commit_before>"""
The L{Image<image.Image>} class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
Class structure::
Application Level
TODO: I think this graph is unnecessary and wrong after removing
BaseImage, JT
----------------------
Image
|
o
|
BaseImage
|
|
------------
| |
Formats ArrayImage
|
Binary
|
------------------
| | |
Nifti Analyze ECAT
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
<commit_msg>Remove old doc. Import Image into core.image<commit_after>"""
The Image class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from image import Image
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
|
b682ff69d5cbfa0529e4d231d5337be7f8fbfaf4 | non_logged_in_area/views.py | non_logged_in_area/views.py | # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
context['facilities'] = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
return context
| # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
facilities = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
facilities_with_shifts = []
for i in facilities:
if len(i.open_shifts) > 0:
facilities_with_shifts.append(i)
context['facilities'] = facilities_with_shifts
return context
| Add filter do not display facilities without shifts | Add filter do not display facilities without shifts
| Python | agpl-3.0 | coders4help/volunteer_planner,christophmeissner/volunteer_planner,pitpalme/volunteer_planner,volunteer-planner/volunteer_planner,volunteer-planner/volunteer_planner,christophmeissner/volunteer_planner,volunteer-planner/volunteer_planner,pitpalme/volunteer_planner,pitpalme/volunteer_planner,volunteer-planner/volunteer_planner,pitpalme/volunteer_planner,christophmeissner/volunteer_planner,coders4help/volunteer_planner,christophmeissner/volunteer_planner,coders4help/volunteer_planner,coders4help/volunteer_planner | # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
context['facilities'] = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
return context
Add filter do not display facilities without shifts | # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
facilities = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
facilities_with_shifts = []
for i in facilities:
if len(i.open_shifts) > 0:
facilities_with_shifts.append(i)
context['facilities'] = facilities_with_shifts
return context
| <commit_before># coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
context['facilities'] = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
return context
<commit_msg>Add filter do not display facilities without shifts<commit_after> | # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
facilities = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
facilities_with_shifts = []
for i in facilities:
if len(i.open_shifts) > 0:
facilities_with_shifts.append(i)
context['facilities'] = facilities_with_shifts
return context
| # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
context['facilities'] = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
return context
Add filter do not display facilities without shifts# coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
facilities = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
facilities_with_shifts = []
for i in facilities:
if len(i.open_shifts) > 0:
facilities_with_shifts.append(i)
context['facilities'] = facilities_with_shifts
return context
| <commit_before># coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
context['facilities'] = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
return context
<commit_msg>Add filter do not display facilities without shifts<commit_after># coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__name__)
class HomeView(TemplateView):
template_name = "base_non_logged_in.html"
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
return HttpResponseRedirect(reverse('helpdesk'))
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
facilities = Facility.objects.select_related('place',
'place__area',
'place__area__region').order_by('place').all()
facilities_with_shifts = []
for i in facilities:
if len(i.open_shifts) > 0:
facilities_with_shifts.append(i)
context['facilities'] = facilities_with_shifts
return context
|
13c6748313e1114853a45e25bcc8135a8b5f5240 | slowpoke/decorator.py | slowpoke/decorator.py | # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
settings.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = settings.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
| # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
self.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = self.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
| Store the standard on the class, not in settings - or else it's captured incorrectly as things process. | Store the standard on the class, not in settings - or else it's captured incorrectly as things process. | Python | bsd-3-clause | adamfast/django-slowpoke | # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
settings.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = settings.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
Store the standard on the class, not in settings - or else it's captured incorrectly as things process. | # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
self.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = self.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
| <commit_before># modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
settings.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = settings.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
<commit_msg>Store the standard on the class, not in settings - or else it's captured incorrectly as things process.<commit_after> | # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
self.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = self.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
| # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
settings.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = settings.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
Store the standard on the class, not in settings - or else it's captured incorrectly as things process.# modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
self.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = self.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
| <commit_before># modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
settings.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = settings.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
<commit_msg>Store the standard on the class, not in settings - or else it's captured incorrectly as things process.<commit_after># modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
self.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
def to_time(*args, **kwargs):
ts = time.time()
result = func(*args, **kwargs)
te = time.time()
# check this against TIME_STANDARDS for the level of function. Log if it was too slow.
sr = TestSuiteRun.objects.using('slowpokelogs').get(pk=settings.CURRENT_SLOWPOKE_RUN)
tr = TestRun()
tr.suite_run = sr
tr.test_standard = self.CURRENT_SLOWPOKE_STANDARD
tr.function_name = str(func.__name__)
tr.args = str(args)
tr.kwargs = str(kwargs)
tr.runtime_ms = (te - ts) * 1000
tr.save(using='slowpokelogs')
return result
return to_time
|
2995accb21d9b8c45792d12402470cfcf322d6a1 | models/phase3_eval/process_sparser.py | models/phase3_eval/process_sparser.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170210')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
xml_bytes = fh.read()
xml_bytes = xml_bytes.replace(b'hmsid', b'pmid')
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
| from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
| Update Sparser script for phase3 | Update Sparser script for phase3
| Python | bsd-2-clause | johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170210')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
xml_bytes = fh.read()
xml_bytes = xml_bytes.replace(b'hmsid', b'pmid')
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
Update Sparser script for phase3 | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
| <commit_before>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170210')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
xml_bytes = fh.read()
xml_bytes = xml_bytes.replace(b'hmsid', b'pmid')
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
<commit_msg>Update Sparser script for phase3<commit_after> | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
| from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170210')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
xml_bytes = fh.read()
xml_bytes = xml_bytes.replace(b'hmsid', b'pmid')
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
Update Sparser script for phase3from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
| <commit_before>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170210')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
xml_bytes = fh.read()
xml_bytes = xml_bytes.replace(b'hmsid', b'pmid')
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
<commit_msg>Update Sparser script for phase3<commit_after>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
|
f758513880cca46937833779ddf099b2ac88afc9 | utilities/ticker-update.py | utilities/ticker-update.py | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = "ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
| import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = r"G:\system\ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
| Fix config PATH for windows batch file | Fix config PATH for windows batch file | Python | mit | daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = "ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
Fix config PATH for windows batch file | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = r"G:\system\ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
| <commit_before>import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = "ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
<commit_msg>Fix config PATH for windows batch file<commit_after> | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = r"G:\system\ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
| import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = "ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
Fix config PATH for windows batch fileimport requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = r"G:\system\ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
| <commit_before>import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = "ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
<commit_msg>Fix config PATH for windows batch file<commit_after>import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = r"G:\system\ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def update_information(security):
symbol, sell_price = security.split(',')
query = URL + symbol
page = requests.get(query)
soup = BeautifulSoup(page.content, 'html.parser')
span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"})
table_row = soup.select('table td')
sell_price = float(sell_price)
price = float(span.get_text())
open_price = float(table_row[3].text)
print(f"{symbol:>6}: {open_price:<6} {price:<6} "
f"{sell_price:<6} {sell_price - price:<6.3f} "
f"{(sell_price - price) / sell_price :<6.2f}"
)
############
### MAIN ###
############
securities = get_securities_list()
for security in securities:
update_information(security)
# EOF
|
3ffaf00e18208a1877c3d2286ba284071d5d3e09 | wafer/pages/serializers.py | wafer/pages/serializers.py | from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.save()
return page
| from django.contrib.auth import get_user_model
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user_model().objects.all())
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.include_in_menu = validated_data['include_in_menu']
page.exclude_from_static = validated_data['exclude_from_static']
page.people = validated_data.get('people')
page.save()
return page
| Add people and other fields to page update options | Add people and other fields to page update options
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.save()
return page
Add people and other fields to page update options | from django.contrib.auth import get_user_model
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user_model().objects.all())
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.include_in_menu = validated_data['include_in_menu']
page.exclude_from_static = validated_data['exclude_from_static']
page.people = validated_data.get('people')
page.save()
return page
| <commit_before>from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.save()
return page
<commit_msg>Add people and other fields to page update options<commit_after> | from django.contrib.auth import get_user_model
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user_model().objects.all())
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.include_in_menu = validated_data['include_in_menu']
page.exclude_from_static = validated_data['exclude_from_static']
page.people = validated_data.get('people')
page.save()
return page
| from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.save()
return page
Add people and other fields to page update optionsfrom django.contrib.auth import get_user_model
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user_model().objects.all())
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.include_in_menu = validated_data['include_in_menu']
page.exclude_from_static = validated_data['exclude_from_static']
page.people = validated_data.get('people')
page.save()
return page
| <commit_before>from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.save()
return page
<commit_msg>Add people and other fields to page update options<commit_after>from django.contrib.auth import get_user_model
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user_model().objects.all())
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(PageSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, page, validated_data):
revisions.set_comment("Changed via REST api")
page.parent = validated_data['parent']
page.content = validated_data['content']
page.include_in_menu = validated_data['include_in_menu']
page.exclude_from_static = validated_data['exclude_from_static']
page.people = validated_data.get('people')
page.save()
return page
|
3570f3a1681cf2b5ad1ba31026ae9d13fcc3e9c2 | test_base.py | test_base.py | import pytest
from pynoaa import PyNOAA
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == id | import pytest
from pynoaa import PyNOAA
from time import sleep
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
sleep(0.2)
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == id
sleep(0.2)
| Add some sleep in tests to not exceed allowed request limits | Add some sleep in tests to not exceed allowed request limits
| Python | mit | lincis/pynoaa | import pytest
from pynoaa import PyNOAA
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == idAdd some sleep in tests to not exceed allowed request limits | import pytest
from pynoaa import PyNOAA
from time import sleep
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
sleep(0.2)
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == id
sleep(0.2)
| <commit_before>import pytest
from pynoaa import PyNOAA
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == id<commit_msg>Add some sleep in tests to not exceed allowed request limits<commit_after> | import pytest
from pynoaa import PyNOAA
from time import sleep
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
sleep(0.2)
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == id
sleep(0.2)
| import pytest
from pynoaa import PyNOAA
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == idAdd some sleep in tests to not exceed allowed request limitsimport pytest
from pynoaa import PyNOAA
from time import sleep
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
sleep(0.2)
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == id
sleep(0.2)
| <commit_before>import pytest
from pynoaa import PyNOAA
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == id<commit_msg>Add some sleep in tests to not exceed allowed request limits<commit_after>import pytest
from pynoaa import PyNOAA
from time import sleep
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid = locationid)
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert results[0]["id"] == "GHCND"
sleep(0.2)
@pytest.mark.parametrize('fun,id',(
['datasets','NEXRAD2',],
['datacategories','ANNPRCP',],
['datatypes','ANN-DUTR-NORMAL',],
['locationcategories','CNTRY',],
['locations','CITY:AG000007',],
['stations','COOP:010148',],
))
def test_id(fun, id):
results = getattr(noaa, fun)(id=id)
assert results["id"] == id
sleep(0.2)
|
ef2f5bf541ab2938f19b11c0845610ccce5e496e | test/__init__.py | test/__init__.py | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
class TestCase(unittest.TestCase):
pass
| # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import platform
(major, minor, patch) = platform.python_version_tuple()
if int(major) == 2 and int(minor) < 7:
import unittest2 as unittest
else:
import unittest
class TestCase(unittest.TestCase):
pass
| Make unit tests run on RHEL boxes better via the python-unittest2 library | Make unit tests run on RHEL boxes better via the python-unittest2 library
| Python | agpl-3.0 | pombredanne/re-core,RHInception/re-core | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
class TestCase(unittest.TestCase):
pass
Make unit tests run on RHEL boxes better via the python-unittest2 library | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import platform
(major, minor, patch) = platform.python_version_tuple()
if int(major) == 2 and int(minor) < 7:
import unittest2 as unittest
else:
import unittest
class TestCase(unittest.TestCase):
pass
| <commit_before># Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
class TestCase(unittest.TestCase):
pass
<commit_msg>Make unit tests run on RHEL boxes better via the python-unittest2 library<commit_after> | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import platform
(major, minor, patch) = platform.python_version_tuple()
if int(major) == 2 and int(minor) < 7:
import unittest2 as unittest
else:
import unittest
class TestCase(unittest.TestCase):
pass
| # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
class TestCase(unittest.TestCase):
pass
Make unit tests run on RHEL boxes better via the python-unittest2 library# Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import platform
(major, minor, patch) = platform.python_version_tuple()
if int(major) == 2 and int(minor) < 7:
import unittest2 as unittest
else:
import unittest
class TestCase(unittest.TestCase):
pass
| <commit_before># Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
class TestCase(unittest.TestCase):
pass
<commit_msg>Make unit tests run on RHEL boxes better via the python-unittest2 library<commit_after># Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import platform
(major, minor, patch) = platform.python_version_tuple()
if int(major) == 2 and int(minor) < 7:
import unittest2 as unittest
else:
import unittest
class TestCase(unittest.TestCase):
pass
|
6d52364c44cf7244b920d04fe6f5917cd99b7377 | linkatos/utils.py | linkatos/utils.py | import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
| import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
def is_fresh_url(expecting_confirmation, message_type):
return (not expecting_confirmation) and message_type is 'url'
| Add back is_fresh_url which was deleted by mistake | fix: Add back is_fresh_url which was deleted by mistake
| Python | mit | iwi/linkatos,iwi/linkatos | import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
fix: Add back is_fresh_url which was deleted by mistake | import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
def is_fresh_url(expecting_confirmation, message_type):
return (not expecting_confirmation) and message_type is 'url'
| <commit_before>import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
<commit_msg>fix: Add back is_fresh_url which was deleted by mistake<commit_after> | import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
def is_fresh_url(expecting_confirmation, message_type):
return (not expecting_confirmation) and message_type is 'url'
| import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
fix: Add back is_fresh_url which was deleted by mistakeimport re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
def is_fresh_url(expecting_confirmation, message_type):
return (not expecting_confirmation) and message_type is 'url'
| <commit_before>import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
<commit_msg>fix: Add back is_fresh_url which was deleted by mistake<commit_after>import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no regex
"""
return no_re.search(message) is not None
def from_bot(message, BOT_ID):
return (message['user'] == BOT_ID)
def has_text(message):
return ('text' in message)
def has_channel(message):
return ('channel' in message)
def has_text_keys(message):
return not ('text' in message and \
'channel' in message and \
'ts' in message and \
'user' in message)
def has_reaction_keys(message):
return ('reaction' in message and \
'item' in message and \
'ts' in message['item'] and \
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
def is_fresh_url(expecting_confirmation, message_type):
return (not expecting_confirmation) and message_type is 'url'
|
f6d17ba769357ad0dfb8766728349d0fce60efe8 | Bookie/fabfile/development.py | Bookie/fabfile/development.py | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(bootstrap_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
| """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
upload_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
chrome_bin = '/usr/bin/google-chrome'
chrome_path = 'extensions/chrome_ext'
key = "/home/rharding/.ssh/chrome_ext.pem"
chrome_ext_server = '/var/www/bookie_chrome.crx'
chrome_ext_local = 'extensions/chrome_ext.crx'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(upload_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
def build_chrome_ext():
"""Package the chrome extension into a .crx file"""
local('{0} --pack-extension={1} --pack-extension-key={2}'.format(chrome_bin,
chrome_path,
key))
@hosts(upload_host)
def push_chrome_ext():
"""Upload the chrome extension to the server"""
rsync_project(chrome_ext_server, chrome_ext_local)
| Add fab functions to build the chrome extension and upload to bmark.us | Add fab functions to build the chrome extension and upload to bmark.us
| Python | agpl-3.0 | bookieio/Bookie,wangjun/Bookie,charany1/Bookie,pombredanne/Bookie,wangjun/Bookie,GreenLunar/Bookie,charany1/Bookie,teodesson/Bookie,charany1/Bookie,teodesson/Bookie,wangjun/Bookie,adamlincoln/Bookie,pombredanne/Bookie,wangjun/Bookie,skmezanul/Bookie,teodesson/Bookie,bookieio/Bookie,GreenLunar/Bookie,bookieio/Bookie,adamlincoln/Bookie,pombredanne/Bookie,GreenLunar/Bookie,skmezanul/Bookie,bookieio/Bookie,skmezanul/Bookie,teodesson/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,GreenLunar/Bookie,skmezanul/Bookie | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(bootstrap_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
Add fab functions to build the chrome extension and upload to bmark.us | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
upload_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
chrome_bin = '/usr/bin/google-chrome'
chrome_path = 'extensions/chrome_ext'
key = "/home/rharding/.ssh/chrome_ext.pem"
chrome_ext_server = '/var/www/bookie_chrome.crx'
chrome_ext_local = 'extensions/chrome_ext.crx'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(upload_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
def build_chrome_ext():
"""Package the chrome extension into a .crx file"""
local('{0} --pack-extension={1} --pack-extension-key={2}'.format(chrome_bin,
chrome_path,
key))
@hosts(upload_host)
def push_chrome_ext():
"""Upload the chrome extension to the server"""
rsync_project(chrome_ext_server, chrome_ext_local)
| <commit_before>"""Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(bootstrap_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
<commit_msg>Add fab functions to build the chrome extension and upload to bmark.us<commit_after> | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
upload_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
chrome_bin = '/usr/bin/google-chrome'
chrome_path = 'extensions/chrome_ext'
key = "/home/rharding/.ssh/chrome_ext.pem"
chrome_ext_server = '/var/www/bookie_chrome.crx'
chrome_ext_local = 'extensions/chrome_ext.crx'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(upload_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
def build_chrome_ext():
"""Package the chrome extension into a .crx file"""
local('{0} --pack-extension={1} --pack-extension-key={2}'.format(chrome_bin,
chrome_path,
key))
@hosts(upload_host)
def push_chrome_ext():
"""Upload the chrome extension to the server"""
rsync_project(chrome_ext_server, chrome_ext_local)
| """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(bootstrap_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
Add fab functions to build the chrome extension and upload to bmark.us"""Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
upload_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
chrome_bin = '/usr/bin/google-chrome'
chrome_path = 'extensions/chrome_ext'
key = "/home/rharding/.ssh/chrome_ext.pem"
chrome_ext_server = '/var/www/bookie_chrome.crx'
chrome_ext_local = 'extensions/chrome_ext.crx'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(upload_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
def build_chrome_ext():
"""Package the chrome extension into a .crx file"""
local('{0} --pack-extension={1} --pack-extension-key={2}'.format(chrome_bin,
chrome_path,
key))
@hosts(upload_host)
def push_chrome_ext():
"""Upload the chrome extension to the server"""
rsync_project(chrome_ext_server, chrome_ext_local)
| <commit_before>"""Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(bootstrap_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
<commit_msg>Add fab functions to build the chrome extension and upload to bmark.us<commit_after>"""Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
upload_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
chrome_bin = '/usr/bin/google-chrome'
chrome_path = 'extensions/chrome_ext'
key = "/home/rharding/.ssh/chrome_ext.pem"
chrome_ext_server = '/var/www/bookie_chrome.crx'
chrome_ext_local = 'extensions/chrome_ext.crx'
def gen_bootstrap():
"""Run the generator that builds a custom virtualenv bootstrap file"""
local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False)
@hosts(upload_host)
def push_bootstrap():
"""Sync the bootstrap.py up to the server for download"""
rsync_project(bootstrap_server, bootstrap_local)
def jstest():
"""Launch the JS tests we have in the system
Currently only the ones there are for extensions
"""
cwd = os.path.dirname(os.path.dirname(__file__))
local('cd {0}/extensions/tests/ && google-chrome index.html'.format(cwd))
def build_chrome_ext():
"""Package the chrome extension into a .crx file"""
local('{0} --pack-extension={1} --pack-extension-key={2}'.format(chrome_bin,
chrome_path,
key))
@hosts(upload_host)
def push_chrome_ext():
"""Upload the chrome extension to the server"""
rsync_project(chrome_ext_server, chrome_ext_local)
|
e811b1ca77f7b8ae090be369fd89d4fe8c7c3f6e | test/functional/rpc_deprecated.py | test/functional/rpc_deprecated.py | #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
# from test_framework.util import assert_raises_rpc_error
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], []]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("No tested deprecated RPC methods")
if __name__ == '__main__':
DeprecatedRpcTest().main()
| #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], ["-deprecatedrpc=banscore"]]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("Test deprecated banscore")
assert 'banscore' not in self.nodes[0].getpeerinfo()[0]
assert 'banscore' in self.nodes[1].getpeerinfo()[0]
if __name__ == '__main__':
DeprecatedRpcTest().main()
| Add a test for the banscore deprecation | Add a test for the banscore deprecation
Summary: This is what the `rpc_deprecated.py` test is for.
Test Plan:
./test/functional/test_runner.py rpc_deprecated
Reviewers: #bitcoin_abc, majcosta
Reviewed By: #bitcoin_abc, majcosta
Differential Revision: https://reviews.bitcoinabc.org/D8915
| Python | mit | Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc | #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
# from test_framework.util import assert_raises_rpc_error
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], []]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("No tested deprecated RPC methods")
if __name__ == '__main__':
DeprecatedRpcTest().main()
Add a test for the banscore deprecation
Summary: This is what the `rpc_deprecated.py` test is for.
Test Plan:
./test/functional/test_runner.py rpc_deprecated
Reviewers: #bitcoin_abc, majcosta
Reviewed By: #bitcoin_abc, majcosta
Differential Revision: https://reviews.bitcoinabc.org/D8915 | #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], ["-deprecatedrpc=banscore"]]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("Test deprecated banscore")
assert 'banscore' not in self.nodes[0].getpeerinfo()[0]
assert 'banscore' in self.nodes[1].getpeerinfo()[0]
if __name__ == '__main__':
DeprecatedRpcTest().main()
| <commit_before>#!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
# from test_framework.util import assert_raises_rpc_error
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], []]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("No tested deprecated RPC methods")
if __name__ == '__main__':
DeprecatedRpcTest().main()
<commit_msg>Add a test for the banscore deprecation
Summary: This is what the `rpc_deprecated.py` test is for.
Test Plan:
./test/functional/test_runner.py rpc_deprecated
Reviewers: #bitcoin_abc, majcosta
Reviewed By: #bitcoin_abc, majcosta
Differential Revision: https://reviews.bitcoinabc.org/D8915<commit_after> | #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], ["-deprecatedrpc=banscore"]]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("Test deprecated banscore")
assert 'banscore' not in self.nodes[0].getpeerinfo()[0]
assert 'banscore' in self.nodes[1].getpeerinfo()[0]
if __name__ == '__main__':
DeprecatedRpcTest().main()
| #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
# from test_framework.util import assert_raises_rpc_error
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], []]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("No tested deprecated RPC methods")
if __name__ == '__main__':
DeprecatedRpcTest().main()
Add a test for the banscore deprecation
Summary: This is what the `rpc_deprecated.py` test is for.
Test Plan:
./test/functional/test_runner.py rpc_deprecated
Reviewers: #bitcoin_abc, majcosta
Reviewed By: #bitcoin_abc, majcosta
Differential Revision: https://reviews.bitcoinabc.org/D8915#!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], ["-deprecatedrpc=banscore"]]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("Test deprecated banscore")
assert 'banscore' not in self.nodes[0].getpeerinfo()[0]
assert 'banscore' in self.nodes[1].getpeerinfo()[0]
if __name__ == '__main__':
DeprecatedRpcTest().main()
| <commit_before>#!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
# from test_framework.util import assert_raises_rpc_error
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], []]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("No tested deprecated RPC methods")
if __name__ == '__main__':
DeprecatedRpcTest().main()
<commit_msg>Add a test for the banscore deprecation
Summary: This is what the `rpc_deprecated.py` test is for.
Test Plan:
./test/functional/test_runner.py rpc_deprecated
Reviewers: #bitcoin_abc, majcosta
Reviewed By: #bitcoin_abc, majcosta
Differential Revision: https://reviews.bitcoinabc.org/D8915<commit_after>#!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
class DeprecatedRpcTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.extra_args = [[], ["-deprecatedrpc=banscore"]]
def run_test(self):
# This test should be used to verify correct behaviour of deprecated
# RPC methods with and without the -deprecatedrpc flags. For example:
#
# In set_test_params:
# self.extra_args = [[], ["-deprecatedrpc=generate"]]
#
# In run_test:
# self.log.info("Test generate RPC")
# assert_raises_rpc_error(-32, 'The wallet generate rpc method is deprecated', self.nodes[0].rpc.generate, 1)
# self.nodes[1].generate(1)
self.log.info("Test deprecated banscore")
assert 'banscore' not in self.nodes[0].getpeerinfo()[0]
assert 'banscore' in self.nodes[1].getpeerinfo()[0]
if __name__ == '__main__':
DeprecatedRpcTest().main()
|
3a7f9520fce968d8292581caf6b94a6ce833b335 | migrations/versions/51775a13339d_patch_hash_column.py | migrations/versions/51775a13339d_patch_hash_column.py | """patch hash column
Revision ID: 51775a13339d
Revises: 016f138b2da8
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
| """patch hash column
Revision ID: 51775a13339d
Revises: 187eade64ef0
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
| Fix revision number in comment | Fix revision number in comment
Summary:
The revision number in the comment of the alembic revision didn't
match the actual revision number.
Reviewers: amandine, paulruan
Reviewed By: paulruan
Subscribers: changesbot, kylec
Differential Revision: https://tails.corp.dropbox.com/D209280
| Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes | """patch hash column
Revision ID: 51775a13339d
Revises: 016f138b2da8
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
Fix revision number in comment
Summary:
The revision number in the comment of the alembic revision didn't
match the actual revision number.
Reviewers: amandine, paulruan
Reviewed By: paulruan
Subscribers: changesbot, kylec
Differential Revision: https://tails.corp.dropbox.com/D209280 | """patch hash column
Revision ID: 51775a13339d
Revises: 187eade64ef0
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
| <commit_before>"""patch hash column
Revision ID: 51775a13339d
Revises: 016f138b2da8
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
<commit_msg>Fix revision number in comment
Summary:
The revision number in the comment of the alembic revision didn't
match the actual revision number.
Reviewers: amandine, paulruan
Reviewed By: paulruan
Subscribers: changesbot, kylec
Differential Revision: https://tails.corp.dropbox.com/D209280<commit_after> | """patch hash column
Revision ID: 51775a13339d
Revises: 187eade64ef0
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
| """patch hash column
Revision ID: 51775a13339d
Revises: 016f138b2da8
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
Fix revision number in comment
Summary:
The revision number in the comment of the alembic revision didn't
match the actual revision number.
Reviewers: amandine, paulruan
Reviewed By: paulruan
Subscribers: changesbot, kylec
Differential Revision: https://tails.corp.dropbox.com/D209280"""patch hash column
Revision ID: 51775a13339d
Revises: 187eade64ef0
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
| <commit_before>"""patch hash column
Revision ID: 51775a13339d
Revises: 016f138b2da8
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
<commit_msg>Fix revision number in comment
Summary:
The revision number in the comment of the alembic revision didn't
match the actual revision number.
Reviewers: amandine, paulruan
Reviewed By: paulruan
Subscribers: changesbot, kylec
Differential Revision: https://tails.corp.dropbox.com/D209280<commit_after>"""patch hash column
Revision ID: 51775a13339d
Revises: 187eade64ef0
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True))
def downgrade():
op.drop_column('revision', 'patch_hash')
|
ce86f13553e97e3e86f8c07bf09228895aacd3c5 | scripts/master/factory/syzygy_commands.py | scripts/master/factory/syzygy_commands.py | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin('internal', 'build', 'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target]
self.factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=cmd,
timeout=timeout)
| # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin(self._build_dir, 'internal', 'build',
'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target,
'--verbose']
self._factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=command,
timeout=timeout)
| Fix typos and paths broken in previous CL. | Fix typos and paths broken in previous CL.
Review URL: http://codereview.chromium.org/7085037
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@87249 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin('internal', 'build', 'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target]
self.factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=cmd,
timeout=timeout)
Fix typos and paths broken in previous CL.
Review URL: http://codereview.chromium.org/7085037
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@87249 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin(self._build_dir, 'internal', 'build',
'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target,
'--verbose']
self._factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=command,
timeout=timeout)
| <commit_before># Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin('internal', 'build', 'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target]
self.factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=cmd,
timeout=timeout)
<commit_msg>Fix typos and paths broken in previous CL.
Review URL: http://codereview.chromium.org/7085037
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@87249 0039d316-1c4b-4281-b951-d872f2087c98<commit_after> | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin(self._build_dir, 'internal', 'build',
'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target,
'--verbose']
self._factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=command,
timeout=timeout)
| # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin('internal', 'build', 'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target]
self.factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=cmd,
timeout=timeout)
Fix typos and paths broken in previous CL.
Review URL: http://codereview.chromium.org/7085037
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@87249 0039d316-1c4b-4281-b951-d872f2087c98# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin(self._build_dir, 'internal', 'build',
'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target,
'--verbose']
self._factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=command,
timeout=timeout)
| <commit_before># Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin('internal', 'build', 'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target]
self.factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=cmd,
timeout=timeout)
<commit_msg>Fix typos and paths broken in previous CL.
Review URL: http://codereview.chromium.org/7085037
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@87249 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps import shell
from master.factory import commands
class SyzygyCommands(commands.FactoryCommands):
"""Encapsulates methods to add Syzygy commands to a buildbot factory."""
def __init__(self, factory=None, target=None, build_dir=None,
target_platform=None, target_arch=None):
commands.FactoryCommands.__init__(self, factory, target, build_dir,
target_platform)
self._arch = target_arch
self._factory = factory
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
script_path = self.PathJoin(self._build_dir, 'internal', 'build',
'randomize_chrome.py')
command = [self._python, script_path,
'--build-dir=%s' % self._build_dir,
'--target=%s' % self._target,
'--verbose']
self._factory.addStep(shell.ShellCommand,
name='randomize',
description=['Randomly', 'Reordering', 'Chrome'],
command=command,
timeout=timeout)
|
c94b8ce6bc451fbc0740120e0cf6e6680e97f69c | src/settings.py | src/settings.py | DEBUG = True
STOPS = [
{'line_name':'12', 'stop_id':'14657', 'stop_name':'Folsom St & 3rd St'},
{'line_name':'10', 'stop_id':'13009', 'stop_name':'2nd St & Harrison St'},
{'line_name':'8X', 'stop_id':'13723', 'stop_name':'Bryan St & 4th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
| DEBUG = True
STOPS = [
{'line_name':'KT', 'stop_id':'17361', 'stop_name':'KT Inbound'},
{'line_name':'22', 'stop_id':'16657', 'stop_name':'Tennessee St & 18th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
| Update stops for new office | Update stops for new office
| Python | mit | albertyw/wilo,albertyw/wilo,albertyw/wilo,albertyw/wilo,albertyw/wilo | DEBUG = True
STOPS = [
{'line_name':'12', 'stop_id':'14657', 'stop_name':'Folsom St & 3rd St'},
{'line_name':'10', 'stop_id':'13009', 'stop_name':'2nd St & Harrison St'},
{'line_name':'8X', 'stop_id':'13723', 'stop_name':'Bryan St & 4th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
Update stops for new office | DEBUG = True
STOPS = [
{'line_name':'KT', 'stop_id':'17361', 'stop_name':'KT Inbound'},
{'line_name':'22', 'stop_id':'16657', 'stop_name':'Tennessee St & 18th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
| <commit_before>DEBUG = True
STOPS = [
{'line_name':'12', 'stop_id':'14657', 'stop_name':'Folsom St & 3rd St'},
{'line_name':'10', 'stop_id':'13009', 'stop_name':'2nd St & Harrison St'},
{'line_name':'8X', 'stop_id':'13723', 'stop_name':'Bryan St & 4th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
<commit_msg>Update stops for new office<commit_after> | DEBUG = True
STOPS = [
{'line_name':'KT', 'stop_id':'17361', 'stop_name':'KT Inbound'},
{'line_name':'22', 'stop_id':'16657', 'stop_name':'Tennessee St & 18th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
| DEBUG = True
STOPS = [
{'line_name':'12', 'stop_id':'14657', 'stop_name':'Folsom St & 3rd St'},
{'line_name':'10', 'stop_id':'13009', 'stop_name':'2nd St & Harrison St'},
{'line_name':'8X', 'stop_id':'13723', 'stop_name':'Bryan St & 4th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
Update stops for new officeDEBUG = True
STOPS = [
{'line_name':'KT', 'stop_id':'17361', 'stop_name':'KT Inbound'},
{'line_name':'22', 'stop_id':'16657', 'stop_name':'Tennessee St & 18th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
| <commit_before>DEBUG = True
STOPS = [
{'line_name':'12', 'stop_id':'14657', 'stop_name':'Folsom St & 3rd St'},
{'line_name':'10', 'stop_id':'13009', 'stop_name':'2nd St & Harrison St'},
{'line_name':'8X', 'stop_id':'13723', 'stop_name':'Bryan St & 4th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
<commit_msg>Update stops for new office<commit_after>DEBUG = True
STOPS = [
{'line_name':'KT', 'stop_id':'17361', 'stop_name':'KT Inbound'},
{'line_name':'22', 'stop_id':'16657', 'stop_name':'Tennessee St & 18th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.appspot.com/agencies/sf-muni/routes/12/stops.json
# stop_name - human readable name of the stop
try:
from settingslocal import *
except:
pass
|
49d7260f2454693c511a0f5124f412e987454dba | matches/models.py | matches/models.py | from django.contrib.auth.models import User
from django.db import models
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
| from django.contrib.auth.models import User
from django.db import models
from promotions.models import Promotion
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
promotion = models.ForeignKey(Promotion)
name = models.CharField(max_length=127, null=True, blank=True)
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
| Add name and promotion to Card. | Add name and promotion to Card.
| Python | agpl-3.0 | OddBloke/moore | from django.contrib.auth.models import User
from django.db import models
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
Add name and promotion to Card. | from django.contrib.auth.models import User
from django.db import models
from promotions.models import Promotion
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
promotion = models.ForeignKey(Promotion)
name = models.CharField(max_length=127, null=True, blank=True)
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
| <commit_before>from django.contrib.auth.models import User
from django.db import models
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
<commit_msg>Add name and promotion to Card.<commit_after> | from django.contrib.auth.models import User
from django.db import models
from promotions.models import Promotion
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
promotion = models.ForeignKey(Promotion)
name = models.CharField(max_length=127, null=True, blank=True)
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
| from django.contrib.auth.models import User
from django.db import models
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
Add name and promotion to Card.from django.contrib.auth.models import User
from django.db import models
from promotions.models import Promotion
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
promotion = models.ForeignKey(Promotion)
name = models.CharField(max_length=127, null=True, blank=True)
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
| <commit_before>from django.contrib.auth.models import User
from django.db import models
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
<commit_msg>Add name and promotion to Card.<commit_after>from django.contrib.auth.models import User
from django.db import models
from promotions.models import Promotion
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models.DateField()
promotion = models.ForeignKey(Promotion)
name = models.CharField(max_length=127, null=True, blank=True)
def __unicode__(self):
return unicode(self.date)
class Match(Review):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
winner = models.ForeignKey(WrestlingEntity, related_name="won_matches",
null=True, blank=True)
def __unicode__(self):
return " vs. ".join([p.name for p in self.participants.all()])
|
dc1130766d356e1e9a613ba924e4af942631428c | distutils/tests/test_ccompiler.py | distutils/tests/test_ccompiler.py |
from distutils import ccompiler
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile([c_file])
| import os
import sys
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8):
return paths
return list(map(os.fspath, paths))
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile(_make_strs([c_file]))
| Add compatibility for Python 3.7 | Add compatibility for Python 3.7
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
from distutils import ccompiler
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile([c_file])
Add compatibility for Python 3.7 | import os
import sys
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8):
return paths
return list(map(os.fspath, paths))
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile(_make_strs([c_file]))
| <commit_before>
from distutils import ccompiler
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile([c_file])
<commit_msg>Add compatibility for Python 3.7<commit_after> | import os
import sys
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8):
return paths
return list(map(os.fspath, paths))
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile(_make_strs([c_file]))
|
from distutils import ccompiler
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile([c_file])
Add compatibility for Python 3.7import os
import sys
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8):
return paths
return list(map(os.fspath, paths))
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile(_make_strs([c_file]))
| <commit_before>
from distutils import ccompiler
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile([c_file])
<commit_msg>Add compatibility for Python 3.7<commit_after>import os
import sys
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8):
return paths
return list(map(os.fspath, paths))
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler = ccompiler.new_compiler()
compiler.set_include_dirs([])
compiler.compile(_make_strs([c_file]))
|
742ce33b0acc576aab72d625d2accc86a53b4023 | comrade/cronjobs/management/commands/cron.py | comrade/cronjobs/management/commands/cron.py | import sys
from django.conf import settings
from django.core.management.base import BaseCommand
import cronjobs
import commonware.log
log = commonware.log.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
log.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
log.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
log.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
log.info("Ending job: %s %s" % (script, args))
| import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from comrade import cronjobs
import logging
logger = logging.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
logger.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
logger.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
logger.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
logger.info("Ending job: %s %s" % (script, args))
| Fix import now that this is renamed. | Fix import now that this is renamed.
| Python | mit | bueda/django-comrade | import sys
from django.conf import settings
from django.core.management.base import BaseCommand
import cronjobs
import commonware.log
log = commonware.log.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
log.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
log.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
log.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
log.info("Ending job: %s %s" % (script, args))
Fix import now that this is renamed. | import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from comrade import cronjobs
import logging
logger = logging.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
logger.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
logger.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
logger.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
logger.info("Ending job: %s %s" % (script, args))
| <commit_before>import sys
from django.conf import settings
from django.core.management.base import BaseCommand
import cronjobs
import commonware.log
log = commonware.log.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
log.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
log.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
log.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
log.info("Ending job: %s %s" % (script, args))
<commit_msg>Fix import now that this is renamed.<commit_after> | import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from comrade import cronjobs
import logging
logger = logging.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
logger.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
logger.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
logger.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
logger.info("Ending job: %s %s" % (script, args))
| import sys
from django.conf import settings
from django.core.management.base import BaseCommand
import cronjobs
import commonware.log
log = commonware.log.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
log.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
log.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
log.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
log.info("Ending job: %s %s" % (script, args))
Fix import now that this is renamed.import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from comrade import cronjobs
import logging
logger = logging.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
logger.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
logger.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
logger.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
logger.info("Ending job: %s %s" % (script, args))
| <commit_before>import sys
from django.conf import settings
from django.core.management.base import BaseCommand
import cronjobs
import commonware.log
log = commonware.log.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
log.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
log.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
log.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
log.info("Ending job: %s %s" % (script, args))
<commit_msg>Fix import now that this is renamed.<commit_after>import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from comrade import cronjobs
import logging
logger = logging.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):
# Load up all the cron scripts.
for app in settings.INSTALLED_APPS:
try:
__import__('%s.cron' % app)
except ImportError:
pass
registered = cronjobs.registered
if not args:
logger.error("Cron called but doesn't know what to do.")
print 'Try one of these: %s' % ', '.join(registered)
sys.exit(1)
script, args = args[0], args[1:]
if script not in registered:
logger.error("Cron called with unrecognized command: %s %s"
% (script, args))
print 'Unrecognized name: %s' % script
sys.exit(1)
logger.info("Beginning job: %s %s" % (script, args))
registered[script](*args)
logger.info("Ending job: %s %s" % (script, args))
|
1fd73a2c07ce66a8dba0ef08210612a2535538ea | jesusmtnez/python/koans/koans/about_decorating_with_functions.py | jesusmtnez/python/koans/koans/about_decorating_with_functions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), __)
self.assertEqual(__, self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual(__, self.render_tag('llama'))
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), "o/~ We all live in a broken submarine o/~")
self.assertEqual("COWBELL BABY!", self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual("<llama/>", self.render_tag('llama'))
| Complete 'About Decorating with functions' koans | [Python] Complete 'About Decorating with functions' koans
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), __)
self.assertEqual(__, self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual(__, self.render_tag('llama'))
[Python] Complete 'About Decorating with functions' koans | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), "o/~ We all live in a broken submarine o/~")
self.assertEqual("COWBELL BABY!", self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual("<llama/>", self.render_tag('llama'))
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), __)
self.assertEqual(__, self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual(__, self.render_tag('llama'))
<commit_msg>[Python] Complete 'About Decorating with functions' koans<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), "o/~ We all live in a broken submarine o/~")
self.assertEqual("COWBELL BABY!", self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual("<llama/>", self.render_tag('llama'))
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), __)
self.assertEqual(__, self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual(__, self.render_tag('llama'))
[Python] Complete 'About Decorating with functions' koans#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), "o/~ We all live in a broken submarine o/~")
self.assertEqual("COWBELL BABY!", self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual("<llama/>", self.render_tag('llama'))
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), __)
self.assertEqual(__, self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual(__, self.render_tag('llama'))
<commit_msg>[Python] Complete 'About Decorating with functions' koans<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
self.assertRegex(self.mediocre_song(), "o/~ We all live in a broken submarine o/~")
self.assertEqual("COWBELL BABY!", self.mediocre_song.wow_factor)
# ------------------------------------------------------------------
def xmltag(fn):
def func(*args):
return '<' + fn(*args) + '/>'
return func
@xmltag
def render_tag(self, name):
return name
def test_decorators_can_change_a_function_output(self):
self.assertEqual("<llama/>", self.render_tag('llama'))
|
97f59c20ca5bcb2388cada55044e0ab5bdc79669 | src/client/packaging/pypi/delphi_epidata/__init__.py | src/client/packaging/pypi/delphi_epidata/__init__.py | from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.0.12'
| from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.1.0'
| Set self-reported python client version to 0.1.0 | Set self-reported python client version to 0.1.0 | Python | mit | cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata | from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.0.12'
Set self-reported python client version to 0.1.0 | from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.1.0'
| <commit_before>from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.0.12'
<commit_msg>Set self-reported python client version to 0.1.0<commit_after> | from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.1.0'
| from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.0.12'
Set self-reported python client version to 0.1.0from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.1.0'
| <commit_before>from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.0.12'
<commit_msg>Set self-reported python client version to 0.1.0<commit_after>from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.1.0'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.