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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8228a862654dfd0418d1e756042fa8f8746b57b9
|
ideascube/conf/kb_usa_wmapache.py
|
ideascube/conf/kb_usa_wmapache.py
|
# -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wiktionary',
},
{
'id': 'ted',
'sessions': [
('tedbusiness.en', 'Business'),
('teddesign.en', 'Design'),
('tedentertainment.en', 'Entertainment'),
('tedglobalissues.en', 'Global Issues'),
('tedscience.en', 'Science'),
('tedtechnology.en', 'Technology'),
]
},
{
'id': 'khanacademy',
},
]
|
# -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wikipedia',
},
{
'id': 'wiktionary',
},
{
'id': 'khanacademy',
},
]
|
Remove Ted and add Wikiepdia
|
Remove Ted and add Wikiepdia
|
Python
|
agpl-3.0
|
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
|
# -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wiktionary',
},
{
'id': 'ted',
'sessions': [
('tedbusiness.en', 'Business'),
('teddesign.en', 'Design'),
('tedentertainment.en', 'Entertainment'),
('tedglobalissues.en', 'Global Issues'),
('tedscience.en', 'Science'),
('tedtechnology.en', 'Technology'),
]
},
{
'id': 'khanacademy',
},
]
Remove Ted and add Wikiepdia
|
# -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wikipedia',
},
{
'id': 'wiktionary',
},
{
'id': 'khanacademy',
},
]
|
<commit_before># -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wiktionary',
},
{
'id': 'ted',
'sessions': [
('tedbusiness.en', 'Business'),
('teddesign.en', 'Design'),
('tedentertainment.en', 'Entertainment'),
('tedglobalissues.en', 'Global Issues'),
('tedscience.en', 'Science'),
('tedtechnology.en', 'Technology'),
]
},
{
'id': 'khanacademy',
},
]
<commit_msg>Remove Ted and add Wikiepdia<commit_after>
|
# -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wikipedia',
},
{
'id': 'wiktionary',
},
{
'id': 'khanacademy',
},
]
|
# -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wiktionary',
},
{
'id': 'ted',
'sessions': [
('tedbusiness.en', 'Business'),
('teddesign.en', 'Design'),
('tedentertainment.en', 'Entertainment'),
('tedglobalissues.en', 'Global Issues'),
('tedscience.en', 'Science'),
('tedtechnology.en', 'Technology'),
]
},
{
'id': 'khanacademy',
},
]
Remove Ted and add Wikiepdia# -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wikipedia',
},
{
'id': 'wiktionary',
},
{
'id': 'khanacademy',
},
]
|
<commit_before># -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wiktionary',
},
{
'id': 'ted',
'sessions': [
('tedbusiness.en', 'Business'),
('teddesign.en', 'Design'),
('tedentertainment.en', 'Entertainment'),
('tedglobalissues.en', 'Global Issues'),
('tedscience.en', 'Science'),
('tedtechnology.en', 'Technology'),
]
},
{
'id': 'khanacademy',
},
]
<commit_msg>Remove Ted and add Wikiepdia<commit_after># -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wikipedia',
},
{
'id': 'wiktionary',
},
{
'id': 'khanacademy',
},
]
|
4a8540dd374d4f75f4ded6a3e555776489b8d190
|
imagersite/imager_images/tests.py
|
imagersite/imager_images/tests.py
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.Factory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.django.DjangoModelFactory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
class AlbumFactory(factory.django.DjangoModelFactory):
"""Create a fake album."""
class Meta:
model = Album
title = fake.sentence()
description = fake.text()
|
Use DjangoModelFactory subclass for images test
|
Use DjangoModelFactory subclass for images test
|
Python
|
mit
|
jesseklein406/django-imager,jesseklein406/django-imager,jesseklein406/django-imager
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.Factory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
Use DjangoModelFactory subclass for images test
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.django.DjangoModelFactory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
class AlbumFactory(factory.django.DjangoModelFactory):
"""Create a fake album."""
class Meta:
model = Album
title = fake.sentence()
description = fake.text()
|
<commit_before>from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.Factory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
<commit_msg>Use DjangoModelFactory subclass for images test<commit_after>
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.django.DjangoModelFactory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
class AlbumFactory(factory.django.DjangoModelFactory):
"""Create a fake album."""
class Meta:
model = Album
title = fake.sentence()
description = fake.text()
|
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.Factory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
Use DjangoModelFactory subclass for images testfrom __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.django.DjangoModelFactory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
class AlbumFactory(factory.django.DjangoModelFactory):
"""Create a fake album."""
class Meta:
model = Album
title = fake.sentence()
description = fake.text()
|
<commit_before>from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.Factory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
<commit_msg>Use DjangoModelFactory subclass for images test<commit_after>from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.test import TestCase
import factory
from faker import Faker
from imager_profile.models import ImagerProfile
from .models import Album, Photo
# Create your tests here.
fake = Faker()
class UserFactory(factory.django.DjangoModelFactory):
"""Create a fake user."""
class Meta:
model = User
username = factory.Sequence(lambda n: 'user{}'.format(n))
first_name = fake.first_name()
last_name = fake.last_name()
email = fake.email()
class PhotoFactory(factory.django.DjangoModelFactory):
"""Create a fake photo."""
class Meta:
model = Photo
photo = factory.django.ImageField()
title = fake.sentence()
description = fake.text()
class AlbumFactory(factory.django.DjangoModelFactory):
"""Create a fake album."""
class Meta:
model = Album
title = fake.sentence()
description = fake.text()
|
cd26af9f5edb1b39e2ead09102c7dee409263c15
|
sensor_consumers/bathroom_door.py
|
sensor_consumers/bathroom_door.py
|
# coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
|
# coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
bathroom_temperature = round(data["data"]["bathroom_temperature"], 1)
bathroom_humidity = round(data["data"]["bathroom_humidity"], 1)
corridor_temperature = round(data["data"]["corridor_temperature"], 1)
corridor_humidity = round(data["data"]["corridor_humidity"], 1)
if bathroom_temperature < 1 or bathroom_temperature > 60:
bathroom_temperature = None
if corridor_temperature < 1 or corridor_temperature > 60:
corridor_temperature = None
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": bathroom_temperature,
"bathroom_humidity": bathroom_humidity,
"corridor_temperature": corridor_temperature,
"corridor_humidity": corridor_humidity,
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
|
Add sanity checks for temperature readings
|
Add sanity checks for temperature readings
|
Python
|
bsd-3-clause
|
ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display
|
# coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
Add sanity checks for temperature readings
|
# coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
bathroom_temperature = round(data["data"]["bathroom_temperature"], 1)
bathroom_humidity = round(data["data"]["bathroom_humidity"], 1)
corridor_temperature = round(data["data"]["corridor_temperature"], 1)
corridor_humidity = round(data["data"]["corridor_humidity"], 1)
if bathroom_temperature < 1 or bathroom_temperature > 60:
bathroom_temperature = None
if corridor_temperature < 1 or corridor_temperature > 60:
corridor_temperature = None
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": bathroom_temperature,
"bathroom_humidity": bathroom_humidity,
"corridor_temperature": corridor_temperature,
"corridor_humidity": corridor_humidity,
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
|
<commit_before># coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
<commit_msg>Add sanity checks for temperature readings<commit_after>
|
# coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
bathroom_temperature = round(data["data"]["bathroom_temperature"], 1)
bathroom_humidity = round(data["data"]["bathroom_humidity"], 1)
corridor_temperature = round(data["data"]["corridor_temperature"], 1)
corridor_humidity = round(data["data"]["corridor_humidity"], 1)
if bathroom_temperature < 1 or bathroom_temperature > 60:
bathroom_temperature = None
if corridor_temperature < 1 or corridor_temperature > 60:
corridor_temperature = None
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": bathroom_temperature,
"bathroom_humidity": bathroom_humidity,
"corridor_temperature": corridor_temperature,
"corridor_humidity": corridor_humidity,
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
|
# coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
Add sanity checks for temperature readings# coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
bathroom_temperature = round(data["data"]["bathroom_temperature"], 1)
bathroom_humidity = round(data["data"]["bathroom_humidity"], 1)
corridor_temperature = round(data["data"]["corridor_temperature"], 1)
corridor_humidity = round(data["data"]["corridor_humidity"], 1)
if bathroom_temperature < 1 or bathroom_temperature > 60:
bathroom_temperature = None
if corridor_temperature < 1 or corridor_temperature > 60:
corridor_temperature = None
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": bathroom_temperature,
"bathroom_humidity": bathroom_humidity,
"corridor_temperature": corridor_temperature,
"corridor_humidity": corridor_humidity,
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
|
<commit_before># coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
<commit_msg>Add sanity checks for temperature readings<commit_after># coding=utf-8
from utils import SensorConsumerBase
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "home")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
bathroom_temperature = round(data["data"]["bathroom_temperature"], 1)
bathroom_humidity = round(data["data"]["bathroom_humidity"], 1)
corridor_temperature = round(data["data"]["corridor_temperature"], 1)
corridor_humidity = round(data["data"]["corridor_humidity"], 1)
if bathroom_temperature < 1 or bathroom_temperature > 60:
bathroom_temperature = None
if corridor_temperature < 1 or corridor_temperature > 60:
corridor_temperature = None
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"tags": {
"location": "bathroom-door",
},
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": bathroom_temperature,
"bathroom_humidity": bathroom_humidity,
"corridor_temperature": corridor_temperature,
"corridor_humidity": corridor_humidity,
},
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
|
72658874727d877996b413aa7d7d1beb1375a9c3
|
stagecraft/libs/backdrop_client/backdrop_client.py
|
stagecraft/libs/backdrop_client/backdrop_client.py
|
from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
assert isinstance(capped_size, int)
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
|
from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
if not isinstance(capped_size, int) or capped_size < 0:
raise BackdropError(
"capped_size must be 0 or a positive integer number of bytes.")
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
|
Add further constrains to create_dataset
|
Add further constrains to create_dataset
To clarify that it capped_size must be zero or a positive integer.
|
Python
|
mit
|
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
|
from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
assert isinstance(capped_size, int)
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
Add further constrains to create_dataset
To clarify that it capped_size must be zero or a positive integer.
|
from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
if not isinstance(capped_size, int) or capped_size < 0:
raise BackdropError(
"capped_size must be 0 or a positive integer number of bytes.")
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
|
<commit_before>from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
assert isinstance(capped_size, int)
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
<commit_msg>Add further constrains to create_dataset
To clarify that it capped_size must be zero or a positive integer.<commit_after>
|
from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
if not isinstance(capped_size, int) or capped_size < 0:
raise BackdropError(
"capped_size must be 0 or a positive integer number of bytes.")
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
|
from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
assert isinstance(capped_size, int)
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
Add further constrains to create_dataset
To clarify that it capped_size must be zero or a positive integer.from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
if not isinstance(capped_size, int) or capped_size < 0:
raise BackdropError(
"capped_size must be 0 or a positive integer number of bytes.")
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
|
<commit_before>from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
assert isinstance(capped_size, int)
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
<commit_msg>Add further constrains to create_dataset
To clarify that it capped_size must be zero or a positive integer.<commit_after>from __future__ import unicode_literals
import json
import requests
from django.conf import settings
class BackdropError(Exception):
pass
def create_dataset(name, capped_size):
"""
Connect to Backdrop and create a new collection called ``name``.
Specify ``capped_size`` in bytes to create a capped collection, or 0 to
create an uncapped collection.
"""
if not isinstance(capped_size, int) or capped_size < 0:
raise BackdropError(
"capped_size must be 0 or a positive integer number of bytes.")
json_request = json.dumps({'capped_size': capped_size})
backdrop_url = '{url}/data-sets/{name}'.format(
url=settings.BACKDROP_URL, name=name)
auth_header = (
'Authorization',
'Bearer {}'.format(settings.CREATE_COLLECTION_ENDPOINT_TOKEN))
type_header = ('content-type', 'application/json')
try:
response = requests.post(
backdrop_url,
headers=dict([type_header, auth_header]),
data=json_request)
response.raise_for_status()
except Exception as e:
raise BackdropError(repr(e))
|
8f42513d6845b6b1461150b1e92890c78c72280e
|
find_text_type_file.py
|
find_text_type_file.py
|
#!/usr/bin/env python3
import os
import subprocess
import sys
def find_text_files(directory):
''' , '''
file_list = []
abspath = os.path.abspath(directory)
for i in os.listdir(directory):
result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
file_list.append(i)
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
print(results)
|
#!/usr/bin/env python3
from pathlib import Path
import os
import subprocess
import sys
LINE_LIMIT = 100
def find_text_files(directory):
''' find text files and look for file content less than 100 characters. '''
file_list = []
abspath = os.path.abspath(directory)
files = [i[0] for i in os.walk(abspath)]
for i in os.walk(abspath):
for j in i[2]:
file_abspath = '{}/{}'.format(i[0], j)
path_obj = Path(file_abspath)
if path_obj.is_file():
result = subprocess.run(['file', "{}".format(file_abspath)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
with open(file_abspath) as text_file:
for line in text_file.readlines():
if len(line) < LINE_LIMIT:
print('file path = {}'.format(file_abspath))
print(line)
file_list.append("{}".format(file_abspath))
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
|
Update find text, walk through the directories with os.walk and print line length less than 100 characters.
|
Update find text, walk through the directories with os.walk and print line length less than 100 characters.
Signed-off-by: SJ Huang <55a36c562e010d4b156739b1c231e1aa17113c8e@gmail.com>
|
Python
|
apache-2.0
|
sjh/python
|
#!/usr/bin/env python3
import os
import subprocess
import sys
def find_text_files(directory):
''' , '''
file_list = []
abspath = os.path.abspath(directory)
for i in os.listdir(directory):
result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
file_list.append(i)
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
print(results)
Update find text, walk through the directories with os.walk and print line length less than 100 characters.
Signed-off-by: SJ Huang <55a36c562e010d4b156739b1c231e1aa17113c8e@gmail.com>
|
#!/usr/bin/env python3
from pathlib import Path
import os
import subprocess
import sys
LINE_LIMIT = 100
def find_text_files(directory):
''' find text files and look for file content less than 100 characters. '''
file_list = []
abspath = os.path.abspath(directory)
files = [i[0] for i in os.walk(abspath)]
for i in os.walk(abspath):
for j in i[2]:
file_abspath = '{}/{}'.format(i[0], j)
path_obj = Path(file_abspath)
if path_obj.is_file():
result = subprocess.run(['file', "{}".format(file_abspath)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
with open(file_abspath) as text_file:
for line in text_file.readlines():
if len(line) < LINE_LIMIT:
print('file path = {}'.format(file_abspath))
print(line)
file_list.append("{}".format(file_abspath))
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
|
<commit_before>#!/usr/bin/env python3
import os
import subprocess
import sys
def find_text_files(directory):
''' , '''
file_list = []
abspath = os.path.abspath(directory)
for i in os.listdir(directory):
result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
file_list.append(i)
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
print(results)
<commit_msg>Update find text, walk through the directories with os.walk and print line length less than 100 characters.
Signed-off-by: SJ Huang <55a36c562e010d4b156739b1c231e1aa17113c8e@gmail.com><commit_after>
|
#!/usr/bin/env python3
from pathlib import Path
import os
import subprocess
import sys
LINE_LIMIT = 100
def find_text_files(directory):
''' find text files and look for file content less than 100 characters. '''
file_list = []
abspath = os.path.abspath(directory)
files = [i[0] for i in os.walk(abspath)]
for i in os.walk(abspath):
for j in i[2]:
file_abspath = '{}/{}'.format(i[0], j)
path_obj = Path(file_abspath)
if path_obj.is_file():
result = subprocess.run(['file', "{}".format(file_abspath)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
with open(file_abspath) as text_file:
for line in text_file.readlines():
if len(line) < LINE_LIMIT:
print('file path = {}'.format(file_abspath))
print(line)
file_list.append("{}".format(file_abspath))
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
|
#!/usr/bin/env python3
import os
import subprocess
import sys
def find_text_files(directory):
''' , '''
file_list = []
abspath = os.path.abspath(directory)
for i in os.listdir(directory):
result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
file_list.append(i)
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
print(results)
Update find text, walk through the directories with os.walk and print line length less than 100 characters.
Signed-off-by: SJ Huang <55a36c562e010d4b156739b1c231e1aa17113c8e@gmail.com>#!/usr/bin/env python3
from pathlib import Path
import os
import subprocess
import sys
LINE_LIMIT = 100
def find_text_files(directory):
''' find text files and look for file content less than 100 characters. '''
file_list = []
abspath = os.path.abspath(directory)
files = [i[0] for i in os.walk(abspath)]
for i in os.walk(abspath):
for j in i[2]:
file_abspath = '{}/{}'.format(i[0], j)
path_obj = Path(file_abspath)
if path_obj.is_file():
result = subprocess.run(['file', "{}".format(file_abspath)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
with open(file_abspath) as text_file:
for line in text_file.readlines():
if len(line) < LINE_LIMIT:
print('file path = {}'.format(file_abspath))
print(line)
file_list.append("{}".format(file_abspath))
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
|
<commit_before>#!/usr/bin/env python3
import os
import subprocess
import sys
def find_text_files(directory):
''' , '''
file_list = []
abspath = os.path.abspath(directory)
for i in os.listdir(directory):
result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
file_list.append(i)
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
print(results)
<commit_msg>Update find text, walk through the directories with os.walk and print line length less than 100 characters.
Signed-off-by: SJ Huang <55a36c562e010d4b156739b1c231e1aa17113c8e@gmail.com><commit_after>#!/usr/bin/env python3
from pathlib import Path
import os
import subprocess
import sys
LINE_LIMIT = 100
def find_text_files(directory):
''' find text files and look for file content less than 100 characters. '''
file_list = []
abspath = os.path.abspath(directory)
files = [i[0] for i in os.walk(abspath)]
for i in os.walk(abspath):
for j in i[2]:
file_abspath = '{}/{}'.format(i[0], j)
path_obj = Path(file_abspath)
if path_obj.is_file():
result = subprocess.run(['file', "{}".format(file_abspath)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
with open(file_abspath) as text_file:
for line in text_file.readlines():
if len(line) < LINE_LIMIT:
print('file path = {}'.format(file_abspath))
print(line)
file_list.append("{}".format(file_abspath))
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
|
c53e8aaadb35b6ca23d60bf4f4aa84812f186128
|
flake8_respect_noqa.py
|
flake8_respect_noqa.py
|
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
|
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
|
Fix for case when file can't be opened due to IOError or similar
|
Fix for case when file can't be opened due to IOError or similar
|
Python
|
mit
|
spookylukey/flake8-respect-noqa
|
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
Fix for case when file can't be opened due to IOError or similar
|
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
|
<commit_before># -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
<commit_msg>Fix for case when file can't be opened due to IOError or similar<commit_after>
|
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
|
# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
Fix for case when file can't be opened due to IOError or similar# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
|
<commit_before># -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
<commit_msg>Fix for case when file can't be opened due to IOError or similar<commit_after># -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.1
import pep8
class RespectNoqaReport(pep8.StandardReport):
def error(self, line_number, offset, text, check):
if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
return
else:
return super(RespectNoqaReport, self).error(line_number, offset,
text, check)
class RespectNoqa(object):
name = 'flake8-respect-noqa'
version = __version__
def __init__(self, *args, **kwargs):
pass
@classmethod
def parse_options(cls, options):
# The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
# or put "jobs = 1" in your [flake8] config.
# Otherwise, flake8 replaces this reported with it's own.
# See https://gitlab.com/pycqa/flake8/issues/66
options.reporter = RespectNoqaReport
options.report = RespectNoqaReport(options)
|
c54bca55a4b0be4f1b2be7bda5ae5cdb215959ed
|
flask_toybox/compat.py
|
flask_toybox/compat.py
|
"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
|
"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict
|
Exclude fallback from coverage reporting
|
Exclude fallback from coverage reporting
|
Python
|
mit
|
drdaeman/flask-toybox
|
"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
Exclude fallback from coverage reporting
|
"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict
|
<commit_before>"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
<commit_msg>Exclude fallback from coverage reporting<commit_after>
|
"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict
|
"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
Exclude fallback from coverage reporting"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict
|
<commit_before>"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
<commit_msg>Exclude fallback from coverage reporting<commit_after>"""
Cross-version compatibility module.
"""
from __future__ import absolute_import
try:
from collections import OrderedDict
except ImportError: # pragma: no cover
from ordereddict import OrderedDict
|
d3b544f5977a433488d9abde6ff1a078def15647
|
app/crosswalk.py
|
app/crosswalk.py
|
from app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, False
|
from app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping, True
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, False
|
Fix branch in caching logic
|
Fix branch in caching logic
|
Python
|
mpl-2.0
|
liuche/prox-server
|
from app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, FalseFix branch in caching logic
|
from app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping, True
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, False
|
<commit_before>from app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, False<commit_msg>Fix branch in caching logic<commit_after>
|
from app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping, True
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, False
|
from app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, FalseFix branch in caching logicfrom app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping, True
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, False
|
<commit_before>from app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, False<commit_msg>Fix branch in caching logic<commit_after>from app.clients import factualClient
from app.util import log
from factual import APIException
CROSSWALK_CACHE_VERSION = 1
def getVenueIdentifiers(yelpID):
yelpURL = "https://yelp.com/biz/%s" % yelpID
mapping = {
"id": yelpID,
"version": CROSSWALK_CACHE_VERSION,
"yelp": {
"url": yelpURL
}
}
try:
obj = factualClient.crosswalk().filters({"url": yelpURL}).data()
if len(obj) == 0:
return mapping, True
factualID = obj[0]["factual_id"]
mapping["factualID"] = factualID
idList = factualClient.crosswalk().filters({"factual_id": factualID}).data()
for idObj in idList:
namespace = idObj["namespace"]
del idObj["factual_id"]
del idObj["namespace"]
mapping[namespace] = idObj
return mapping, True
except APIException:
log.error("Factual API failed again")
except Exception:
log.exception("Factual problem " + yelpID)
return mapping, False
|
e317812daaae4ff1b50c7d56931425e86a7255b8
|
run_IRIDA_Uploader.py
|
run_IRIDA_Uploader.py
|
#!/usr/bin/env python
import wx
from GUI.iridaUploaderMain import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
|
#!/usr/bin/env python
import wx
from GUI.MainFrame import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
|
Use the right package name for running the uploader.
|
Use the right package name for running the uploader.
|
Python
|
apache-2.0
|
phac-nml/irida-miseq-uploader,phac-nml/irida-miseq-uploader
|
#!/usr/bin/env python
import wx
from GUI.iridaUploaderMain import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
Use the right package name for running the uploader.
|
#!/usr/bin/env python
import wx
from GUI.MainFrame import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
|
<commit_before>#!/usr/bin/env python
import wx
from GUI.iridaUploaderMain import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
<commit_msg>Use the right package name for running the uploader.<commit_after>
|
#!/usr/bin/env python
import wx
from GUI.MainFrame import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
|
#!/usr/bin/env python
import wx
from GUI.iridaUploaderMain import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
Use the right package name for running the uploader.#!/usr/bin/env python
import wx
from GUI.MainFrame import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
|
<commit_before>#!/usr/bin/env python
import wx
from GUI.iridaUploaderMain import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
<commit_msg>Use the right package name for running the uploader.<commit_after>#!/usr/bin/env python
import wx
from GUI.MainFrame import MainFrame
if __name__ == "__main__":
app = wx.App(False)
frame = MainFrame()
frame.Show()
frame.mp.api = frame.settings_frame.attempt_connect_to_api()
app.MainLoop()
|
e3c79b7851aafad2a491c0ceafe2d3f539a4e3df
|
number_to_words.py
|
number_to_words.py
|
class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
|
class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
def convert(self, number):
"""
Take an integer and return it converted to a textual representation.
Args:
number (int): The number to be converted.
Returns:
sentence (string): The textual representation of `number`.
"""
|
Add initial function definition and documentation for function to do conversion
|
Add initial function definition and documentation for function to do conversion
|
Python
|
mit
|
ianfieldhouse/number_to_words
|
class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
Add initial function definition and documentation for function to do conversion
|
class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
def convert(self, number):
"""
Take an integer and return it converted to a textual representation.
Args:
number (int): The number to be converted.
Returns:
sentence (string): The textual representation of `number`.
"""
|
<commit_before>class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
<commit_msg>Add initial function definition and documentation for function to do conversion<commit_after>
|
class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
def convert(self, number):
"""
Take an integer and return it converted to a textual representation.
Args:
number (int): The number to be converted.
Returns:
sentence (string): The textual representation of `number`.
"""
|
class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
Add initial function definition and documentation for function to do conversionclass NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
def convert(self, number):
"""
Take an integer and return it converted to a textual representation.
Args:
number (int): The number to be converted.
Returns:
sentence (string): The textual representation of `number`.
"""
|
<commit_before>class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
<commit_msg>Add initial function definition and documentation for function to do conversion<commit_after>class NumberToWords(object):
"""
Class for converting positive integer values to a textual representation
of the submitted number for value of 0 up to 999999999.
"""
MAX = 999999999
SMALL_NUMBERS = ['', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen']
TENS = ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy',
'eighty', 'ninety']
LARGE_NUMBERS = ['', 'thousand', 'million']
def convert(self, number):
"""
Take an integer and return it converted to a textual representation.
Args:
number (int): The number to be converted.
Returns:
sentence (string): The textual representation of `number`.
"""
|
27c3ebfee3789de817defc18ac4a3dbc37a7d03f
|
tests/munge_js_test.py
|
tests/munge_js_test.py
|
import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
for fixture in get_fixtures():
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
setattr(MungeJsTest, 'test_' + fixture, test)
if __name__ == '__main__':
unittest.main()
|
import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
def generate(fixture):
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
return test
for fixture in get_fixtures():
setattr(MungeJsTest, 'test_' + fixture, generate(fixture))
if __name__ == '__main__':
unittest.main()
|
Use an additional function to scope everything properly
|
Use an additional function to scope everything properly
|
Python
|
mit
|
p/munge-js,p/munge-js
|
import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
for fixture in get_fixtures():
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
setattr(MungeJsTest, 'test_' + fixture, test)
if __name__ == '__main__':
unittest.main()
Use an additional function to scope everything properly
|
import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
def generate(fixture):
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
return test
for fixture in get_fixtures():
setattr(MungeJsTest, 'test_' + fixture, generate(fixture))
if __name__ == '__main__':
unittest.main()
|
<commit_before>import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
for fixture in get_fixtures():
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
setattr(MungeJsTest, 'test_' + fixture, test)
if __name__ == '__main__':
unittest.main()
<commit_msg>Use an additional function to scope everything properly<commit_after>
|
import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
def generate(fixture):
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
return test
for fixture in get_fixtures():
setattr(MungeJsTest, 'test_' + fixture, generate(fixture))
if __name__ == '__main__':
unittest.main()
|
import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
for fixture in get_fixtures():
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
setattr(MungeJsTest, 'test_' + fixture, test)
if __name__ == '__main__':
unittest.main()
Use an additional function to scope everything properlyimport os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
def generate(fixture):
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
return test
for fixture in get_fixtures():
setattr(MungeJsTest, 'test_' + fixture, generate(fixture))
if __name__ == '__main__':
unittest.main()
|
<commit_before>import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
for fixture in get_fixtures():
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
setattr(MungeJsTest, 'test_' + fixture, test)
if __name__ == '__main__':
unittest.main()
<commit_msg>Use an additional function to scope everything properly<commit_after>import os.path
import unittest
import munge_js
class TestCase(unittest.TestCase):
pass
TestCase.assert_false = TestCase.assertFalse
TestCase.assert_equal = TestCase.assertEqual
fixture_root = os.path.join(os.path.dirname(__file__), 'fixtures')
def get_fixtures():
dir = os.path.join(fixture_root, 'input')
files = os.listdir(dir)
files.sort()
names = [file[0:len(file)-3] for file in files if file.endswith('.js')]
return names
class MungeJsTest(TestCase):
pass
def generate(fixture):
def test(self):
with open(os.path.join(fixture_root, 'input', fixture + '.js')) as f:
input = f.read()
with open(os.path.join(fixture_root, 'output', fixture + '.js')) as f:
expected = f.read()
actual = munge_js.convert(input)
self.assert_equal(expected, actual)
return test
for fixture in get_fixtures():
setattr(MungeJsTest, 'test_' + fixture, generate(fixture))
if __name__ == '__main__':
unittest.main()
|
7be4d15bfba24e090647d40c4f4a7f5f14e54204
|
scheduler/schedule.py
|
scheduler/schedule.py
|
import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
|
import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph)
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
|
Remove timeout argument on update job
|
Remove timeout argument on update job
|
Python
|
apache-2.0
|
ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod
|
import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
Remove timeout argument on update job
|
import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph)
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
|
<commit_before>import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
<commit_msg>Remove timeout argument on update job<commit_after>
|
import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph)
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
|
import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
Remove timeout argument on update jobimport sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph)
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
|
<commit_before>import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
<commit_msg>Remove timeout argument on update job<commit_after>import sys
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from redis import StrictRedis
from rq import Queue
from apscheduler.schedulers.blocking import BlockingScheduler
from d1lod import jobs
conn = StrictRedis(host='redis', port='6379')
q = Queue(connection=conn)
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=1)
def queue_update_job():
q.enqueue(jobs.update_graph)
@sched.scheduled_job('interval', minutes=1)
def queue_stats_job():
q.enqueue(jobs.calculate_stats)
@sched.scheduled_job('interval', minutes=1)
def queue_export_job():
q.enqueue(jobs.export_graph)
@sched.scheduled_job('interval', minutes=1)
def print_jobs_job():
sched.print_jobs()
# Wait a bit for Sesame to start
time.sleep(10)
# Queue the stats job first. This creates the repository before any other
# jobs are run.
q.enqueue(jobs.calculate_stats)
# Start the scheduler
sched.start()
|
29b26aa8b44ea5820cfcd20e324d2c3631338228
|
portal/models/research_protocol.py
|
portal/models/research_protocol.py
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
rp = ResearchProtocol.query.filter_by(name=data['name']).first()
if not rp:
rp = cls(data['name'])
return rp
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
Implement common pattern from_json calls update_from_json
|
Implement common pattern from_json calls update_from_json
|
Python
|
bsd-3-clause
|
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
rp = ResearchProtocol.query.filter_by(name=data['name']).first()
if not rp:
rp = cls(data['name'])
return rp
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
Implement common pattern from_json calls update_from_json
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
<commit_before>"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
rp = ResearchProtocol.query.filter_by(name=data['name']).first()
if not rp:
rp = cls(data['name'])
return rp
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
<commit_msg>Implement common pattern from_json calls update_from_json<commit_after>
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
rp = ResearchProtocol.query.filter_by(name=data['name']).first()
if not rp:
rp = cls(data['name'])
return rp
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
Implement common pattern from_json calls update_from_json"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
<commit_before>"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
rp = ResearchProtocol.query.filter_by(name=data['name']).first()
if not rp:
rp = cls(data['name'])
return rp
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
<commit_msg>Implement common pattern from_json calls update_from_json<commit_after>"""Research Protocol module"""
from datetime import datetime
from ..database import db
from ..date_tools import FHIR_datetime
class ResearchProtocol(db.Model):
"""ResearchProtocol model for tracking QB versions"""
__tablename__ = 'research_protocols'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
created_at = db.Column(db.DateTime, nullable=False)
def __init__(self, name):
self.name = name
self.created_at = datetime.utcnow()
@classmethod
def from_json(cls, data):
if 'name' not in data:
raise ValueError("missing required name field")
instance = cls(data['name'])
return instance.update_from_json(data)
def update_from_json(self, data):
self.name = data['name']
if 'created_at' in data:
self.created_at = data['created_at']
return self
def as_json(self):
d = {}
d['id'] = self.id
d['resourceType'] = 'ResearchProtocol'
d['name'] = self.name
d['created_at'] = FHIR_datetime.as_fhir(self.created_at)
return d
|
e68b8146c6ae509489fde97faf10d5748904a20c
|
sentrylogs/helpers.py
|
sentrylogs/helpers.py
|
"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_extra(key, value)
capture_message(message, level)
|
"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_context(key, value)
capture_message(message, level)
|
Use structured context instead of additional data
|
Use structured context instead of additional data
Additional Data is deprecated https://docs.sentry.io/platforms/python/enriching-events/context/#additional-data
|
Python
|
bsd-3-clause
|
mdgart/sentrylogs
|
"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_extra(key, value)
capture_message(message, level)
Use structured context instead of additional data
Additional Data is deprecated https://docs.sentry.io/platforms/python/enriching-events/context/#additional-data
|
"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_context(key, value)
capture_message(message, level)
|
<commit_before>"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_extra(key, value)
capture_message(message, level)
<commit_msg>Use structured context instead of additional data
Additional Data is deprecated https://docs.sentry.io/platforms/python/enriching-events/context/#additional-data<commit_after>
|
"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_context(key, value)
capture_message(message, level)
|
"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_extra(key, value)
capture_message(message, level)
Use structured context instead of additional data
Additional Data is deprecated https://docs.sentry.io/platforms/python/enriching-events/context/#additional-data"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_context(key, value)
capture_message(message, level)
|
<commit_before>"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_extra(key, value)
capture_message(message, level)
<commit_msg>Use structured context instead of additional data
Additional Data is deprecated https://docs.sentry.io/platforms/python/enriching-events/context/#additional-data<commit_after>"""
Helper functions for Sentry Logs
"""
from sentry_sdk import capture_message, configure_scope
from .conf.settings import SENTRY_LOG_LEVEL, SENTRY_LOG_LEVELS
def send_message(message, level, data):
"""Send a message to the Sentry server"""
# Only send messages for desired log level
if (SENTRY_LOG_LEVELS.index(level)
< SENTRY_LOG_LEVELS.index(SENTRY_LOG_LEVEL)):
return
with configure_scope() as scope:
for key, value in data.items():
scope.set_context(key, value)
capture_message(message, level)
|
f0d19857914f196db624abcd9de718d1d4b73e84
|
organizer/views.py
|
organizer/views.py
|
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
|
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
return HttpResponse()
|
Tag Detail: create view skeleton.
|
Ch05: Tag Detail: create view skeleton.
|
Python
|
bsd-2-clause
|
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
|
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
Ch05: Tag Detail: create view skeleton.
|
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
return HttpResponse()
|
<commit_before>from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
<commit_msg>Ch05: Tag Detail: create view skeleton.<commit_after>
|
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
return HttpResponse()
|
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
Ch05: Tag Detail: create view skeleton.from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
return HttpResponse()
|
<commit_before>from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
<commit_msg>Ch05: Tag Detail: create view skeleton.<commit_after>from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
return HttpResponse()
|
12c57c385ad60cf48f99082bb486b429250e5921
|
gittip/orm/__init__.py
|
gittip/orm/__init__.py
|
from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()
|
from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
def drop_all(self):
self.Model.metadata.drop_all(bind=self.engine)
def create_all(self):
self.Model.metadata.create_all(bind=self.engine)
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()
|
Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
|
Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
Signed-off-by: Joonas Bergius <9be13466ab086d7a8db93edb14ffb6760790b15e@gmail.com>
|
Python
|
cc0-1.0
|
bountysource/www.gittip.com,gratipay/gratipay.com,bountysource/www.gittip.com,gratipay/gratipay.com,studio666/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,bountysource/www.gittip.com,bountysource/www.gittip.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,MikeFair/www.gittip.com,MikeFair/www.gittip.com,gratipay/gratipay.com,MikeFair/www.gittip.com,studio666/gratipay.com,mccolgst/www.gittip.com
|
from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
Signed-off-by: Joonas Bergius <9be13466ab086d7a8db93edb14ffb6760790b15e@gmail.com>
|
from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
def drop_all(self):
self.Model.metadata.drop_all(bind=self.engine)
def create_all(self):
self.Model.metadata.create_all(bind=self.engine)
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()
|
<commit_before>from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()<commit_msg>Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
Signed-off-by: Joonas Bergius <9be13466ab086d7a8db93edb14ffb6760790b15e@gmail.com><commit_after>
|
from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
def drop_all(self):
self.Model.metadata.drop_all(bind=self.engine)
def create_all(self):
self.Model.metadata.create_all(bind=self.engine)
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()
|
from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
Signed-off-by: Joonas Bergius <9be13466ab086d7a8db93edb14ffb6760790b15e@gmail.com>from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
def drop_all(self):
self.Model.metadata.drop_all(bind=self.engine)
def create_all(self):
self.Model.metadata.create_all(bind=self.engine)
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()
|
<commit_before>from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()<commit_msg>Add convenience methods for creating/deleting all tables, for bootstrapping/testing use
Signed-off-by: Joonas Bergius <9be13466ab086d7a8db93edb14ffb6760790b15e@gmail.com><commit_after>from __future__ import unicode_literals
import os
import pdb
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
class Model(object):
def __repr__(self):
cols = self.__mapper__.c.keys()
class_name = self.__class__.__name__
items = ', '.join(['%s=%s' % (col, repr(getattr(self, col))) for col
in cols])
return '%s(%s)' % (class_name, items)
def attrs_dict(self):
keys = self.__mapper__.c.keys()
attrs = {}
for key in keys:
attrs[key] = getattr(self, key)
return attrs
class SQLAlchemy(object):
def __init__(self):
self.session = self.create_session()
self.Model = self.make_declarative_base()
@property
def engine(self):
dburl = os.environ['DATABASE_URL']
return create_engine(dburl)
def create_session(self):
session = scoped_session(sessionmaker())
session.configure(bind=self.engine)
return session
def make_declarative_base(self):
base = declarative_base(cls=Model)
base.query = self.session.query_property()
return base
def drop_all(self):
self.Model.metadata.drop_all(bind=self.engine)
def create_all(self):
self.Model.metadata.create_all(bind=self.engine)
db = SQLAlchemy()
all = [db]
def rollback(*_):
db.session.rollback()
|
393abd296c65a5fd8fd094ca2c6925f132b77ad4
|
utc-time/utc-time.py
|
utc-time/utc-time.py
|
#!/usr/bin/env python
import time
print 'Content-Type: text/javascript'
print ''
print 'var timeskew = new Date().getTime() - ' + str(time.time()*1000) + ';'
|
#!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
|
Disable caching of stale time stamp information.
|
Disable caching of stale time stamp information.
|
Python
|
apache-2.0
|
google/google-authenticator-libpam,google/google-authenticator-libpam,google/google-authenticator-libpam,google/google-authenticator-libpam
|
#!/usr/bin/env python
import time
print 'Content-Type: text/javascript'
print ''
print 'var timeskew = new Date().getTime() - ' + str(time.time()*1000) + ';'
Disable caching of stale time stamp information.
|
#!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
|
<commit_before>#!/usr/bin/env python
import time
print 'Content-Type: text/javascript'
print ''
print 'var timeskew = new Date().getTime() - ' + str(time.time()*1000) + ';'
<commit_msg>Disable caching of stale time stamp information.<commit_after>
|
#!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
|
#!/usr/bin/env python
import time
print 'Content-Type: text/javascript'
print ''
print 'var timeskew = new Date().getTime() - ' + str(time.time()*1000) + ';'
Disable caching of stale time stamp information.#!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
|
<commit_before>#!/usr/bin/env python
import time
print 'Content-Type: text/javascript'
print ''
print 'var timeskew = new Date().getTime() - ' + str(time.time()*1000) + ';'
<commit_msg>Disable caching of stale time stamp information.<commit_after>#!/usr/bin/env python
import time
t = time.time()
u = time.gmtime(t)
s = time.strftime('%a, %e %b %Y %T GMT', u)
print 'Content-Type: text/javascript'
print 'Cache-Control: no-cache'
print 'Date: ' + s
print 'Expires: ' + s
print ''
print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
|
745568d54b705cf767142911556c7d87a0397919
|
lfs/shipping/migrations/0002_auto_20170216_0739.py
|
lfs/shipping/migrations/0002_auto_20170216_0739.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetShippingMethodPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossShippingMethodPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
|
Fix price calculator class names
|
Fix price calculator class names
|
Python
|
bsd-3-clause
|
diefenbach/django-lfs,diefenbach/django-lfs,diefenbach/django-lfs
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
Fix price calculator class names
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetShippingMethodPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossShippingMethodPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
<commit_msg>Fix price calculator class names<commit_after>
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetShippingMethodPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossShippingMethodPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
Fix price calculator class names# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetShippingMethodPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossShippingMethodPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
|
<commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
<commit_msg>Fix price calculator class names<commit_after># -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-02-16 07:39
from __future__ import unicode_literals
from django.db import migrations
def update_price_calculator(apps, schema_editor):
ShippingMethod = apps.get_model("shipping", "ShippingMethod")
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.NetShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.NetShippingMethodPriceCalculator"
shipping_method.save()
for shipping_method in ShippingMethod.objects.filter(price_calculator="lfs.shipping.GrossShippingMethodPriceCalculator"):
shipping_method.price_calculator = "lfs.shipping.calculator.GrossShippingMethodPriceCalculator"
shipping_method.save()
class Migration(migrations.Migration):
dependencies = [
('shipping', '0001_initial'),
]
operations = [
migrations.RunPython(update_price_calculator),
]
|
46c535faf5dec41c34740104d4f6ee6770309ccf
|
spicedham/__init__.py
|
spicedham/__init__.py
|
from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
plugins.append(plugin.load())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data, is_spam):
average_score = 0
for plugin_method in plugins:
average_score += plugin_method(classification_data, is_spam)
return average_score / len(plugins)
def setup():
for pluginMethod in plugins:
print pluginMethod
print type(pluginMethod)
pluginMethod()
|
from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data):
average_score = 0
for plugin in plugins:
average_score += plugin.classify(classification_data)
return average_score / len(plugins)
plugin.setup()
|
Fix plugin system loader and remove setup
|
Fix plugin system loader and remove setup
* We don't need a setup function, that's waht __init__ is for
* There were copy pasta problems with classify. They're fixed.
|
Python
|
mpl-2.0
|
mozilla/spicedham,mozilla/spicedham
|
from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
plugins.append(plugin.load())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data, is_spam):
average_score = 0
for plugin_method in plugins:
average_score += plugin_method(classification_data, is_spam)
return average_score / len(plugins)
def setup():
for pluginMethod in plugins:
print pluginMethod
print type(pluginMethod)
pluginMethod()
Fix plugin system loader and remove setup
* We don't need a setup function, that's waht __init__ is for
* There were copy pasta problems with classify. They're fixed.
|
from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data):
average_score = 0
for plugin in plugins:
average_score += plugin.classify(classification_data)
return average_score / len(plugins)
plugin.setup()
|
<commit_before>from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
plugins.append(plugin.load())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data, is_spam):
average_score = 0
for plugin_method in plugins:
average_score += plugin_method(classification_data, is_spam)
return average_score / len(plugins)
def setup():
for pluginMethod in plugins:
print pluginMethod
print type(pluginMethod)
pluginMethod()
<commit_msg>Fix plugin system loader and remove setup
* We don't need a setup function, that's waht __init__ is for
* There were copy pasta problems with classify. They're fixed.<commit_after>
|
from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data):
average_score = 0
for plugin in plugins:
average_score += plugin.classify(classification_data)
return average_score / len(plugins)
plugin.setup()
|
from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
plugins.append(plugin.load())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data, is_spam):
average_score = 0
for plugin_method in plugins:
average_score += plugin_method(classification_data, is_spam)
return average_score / len(plugins)
def setup():
for pluginMethod in plugins:
print pluginMethod
print type(pluginMethod)
pluginMethod()
Fix plugin system loader and remove setup
* We don't need a setup function, that's waht __init__ is for
* There were copy pasta problems with classify. They're fixed.from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data):
average_score = 0
for plugin in plugins:
average_score += plugin.classify(classification_data)
return average_score / len(plugins)
plugin.setup()
|
<commit_before>from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
plugins.append(plugin.load())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data, is_spam):
average_score = 0
for plugin_method in plugins:
average_score += plugin_method(classification_data, is_spam)
return average_score / len(plugins)
def setup():
for pluginMethod in plugins:
print pluginMethod
print type(pluginMethod)
pluginMethod()
<commit_msg>Fix plugin system loader and remove setup
* We don't need a setup function, that's waht __init__ is for
* There were copy pasta problems with classify. They're fixed.<commit_after>from pkg_resources import iter_entry_points
from config import config
plugins = []
for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
pluginClass = plugin.load()
plugins.append(pluginClass())
def train(training_data, is_spam):
for plugin in plugins:
plugin.train(training_data, is_spam)
def classify(classification_data):
average_score = 0
for plugin in plugins:
average_score += plugin.classify(classification_data)
return average_score / len(plugins)
plugin.setup()
|
fbae85917839aabaf83ff3dd003a6f3b239360d3
|
python/convert_line_endings.py
|
python/convert_line_endings.py
|
#!/usr/bin/python
import os
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
|
Add option to Python line ending conversion to specify a single filename on the command line
|
[trunk] Add option to Python line ending conversion to specify a single filename on the command line
|
Python
|
bsd-3-clause
|
markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation
|
#!/usr/bin/python
import os
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
[trunk] Add option to Python line ending conversion to specify a single filename on the command line
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/python
import os
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
<commit_msg>[trunk] Add option to Python line ending conversion to specify a single filename on the command line<commit_after>
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
|
#!/usr/bin/python
import os
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
[trunk] Add option to Python line ending conversion to specify a single filename on the command line#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/python
import os
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
<commit_msg>[trunk] Add option to Python line ending conversion to specify a single filename on the command line<commit_after>#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
|
c0d0ea6b01ed7ddd9f5817b2debe7c58f64a8ba5
|
tests/test_service.py
|
tests/test_service.py
|
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import base64
import unittest
import sys
import os
sys.path.append(os.path.abspath('../server.py'))
import server
class TestPosieService(unittest.TestCase):
def test_key_generation(self):
# Load public der key from http endpoint
key_string = base64.b64decode(server.key())
public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
self.assertIsNotNone(public_key)
|
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from server import app
import base64
import unittest
class TestPosieService(unittest.TestCase):
key_endpoint = "/key"
decrypt_endpoint = "/decrypt"
def setUp(self):
# creates a test client
self.app = app.test_client()
# propagate the exceptions to the test client
self.app.testing = True
r = self.app.get(self.key_endpoint)
key_string = base64.b64decode(r.data)
self.public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
def send_message(self, message):
ciphertext = self.public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data=base64.b64encode(ciphertext))
return r
def test_key_generation(self):
self.assertIsNotNone(self.public_key)
def test_decrypt_fail_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='rubbish')
self.assertEqual(r.status_code, 400)
def test_no_content_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='')
self.assertEqual(r.status_code, 400)
def test_decrypts_message(self):
# Encrypt a message with the key
message = b"Some encrypted message"
# Ask posie to decode message
r = self.send_message(message)
# Compare to bytestring version of decrypted data
self.assertEqual(r.data, message)
|
Update tests to init flask and use test client
|
Update tests to init flask and use test client
|
Python
|
mit
|
ONSdigital/edcdi
|
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import base64
import unittest
import sys
import os
sys.path.append(os.path.abspath('../server.py'))
import server
class TestPosieService(unittest.TestCase):
def test_key_generation(self):
# Load public der key from http endpoint
key_string = base64.b64decode(server.key())
public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
self.assertIsNotNone(public_key)
Update tests to init flask and use test client
|
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from server import app
import base64
import unittest
class TestPosieService(unittest.TestCase):
key_endpoint = "/key"
decrypt_endpoint = "/decrypt"
def setUp(self):
# creates a test client
self.app = app.test_client()
# propagate the exceptions to the test client
self.app.testing = True
r = self.app.get(self.key_endpoint)
key_string = base64.b64decode(r.data)
self.public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
def send_message(self, message):
ciphertext = self.public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data=base64.b64encode(ciphertext))
return r
def test_key_generation(self):
self.assertIsNotNone(self.public_key)
def test_decrypt_fail_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='rubbish')
self.assertEqual(r.status_code, 400)
def test_no_content_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='')
self.assertEqual(r.status_code, 400)
def test_decrypts_message(self):
# Encrypt a message with the key
message = b"Some encrypted message"
# Ask posie to decode message
r = self.send_message(message)
# Compare to bytestring version of decrypted data
self.assertEqual(r.data, message)
|
<commit_before>from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import base64
import unittest
import sys
import os
sys.path.append(os.path.abspath('../server.py'))
import server
class TestPosieService(unittest.TestCase):
def test_key_generation(self):
# Load public der key from http endpoint
key_string = base64.b64decode(server.key())
public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
self.assertIsNotNone(public_key)
<commit_msg>Update tests to init flask and use test client<commit_after>
|
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from server import app
import base64
import unittest
class TestPosieService(unittest.TestCase):
key_endpoint = "/key"
decrypt_endpoint = "/decrypt"
def setUp(self):
# creates a test client
self.app = app.test_client()
# propagate the exceptions to the test client
self.app.testing = True
r = self.app.get(self.key_endpoint)
key_string = base64.b64decode(r.data)
self.public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
def send_message(self, message):
ciphertext = self.public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data=base64.b64encode(ciphertext))
return r
def test_key_generation(self):
self.assertIsNotNone(self.public_key)
def test_decrypt_fail_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='rubbish')
self.assertEqual(r.status_code, 400)
def test_no_content_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='')
self.assertEqual(r.status_code, 400)
def test_decrypts_message(self):
# Encrypt a message with the key
message = b"Some encrypted message"
# Ask posie to decode message
r = self.send_message(message)
# Compare to bytestring version of decrypted data
self.assertEqual(r.data, message)
|
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import base64
import unittest
import sys
import os
sys.path.append(os.path.abspath('../server.py'))
import server
class TestPosieService(unittest.TestCase):
def test_key_generation(self):
# Load public der key from http endpoint
key_string = base64.b64decode(server.key())
public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
self.assertIsNotNone(public_key)
Update tests to init flask and use test clientfrom cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from server import app
import base64
import unittest
class TestPosieService(unittest.TestCase):
key_endpoint = "/key"
decrypt_endpoint = "/decrypt"
def setUp(self):
# creates a test client
self.app = app.test_client()
# propagate the exceptions to the test client
self.app.testing = True
r = self.app.get(self.key_endpoint)
key_string = base64.b64decode(r.data)
self.public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
def send_message(self, message):
ciphertext = self.public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data=base64.b64encode(ciphertext))
return r
def test_key_generation(self):
self.assertIsNotNone(self.public_key)
def test_decrypt_fail_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='rubbish')
self.assertEqual(r.status_code, 400)
def test_no_content_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='')
self.assertEqual(r.status_code, 400)
def test_decrypts_message(self):
# Encrypt a message with the key
message = b"Some encrypted message"
# Ask posie to decode message
r = self.send_message(message)
# Compare to bytestring version of decrypted data
self.assertEqual(r.data, message)
|
<commit_before>from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
import base64
import unittest
import sys
import os
sys.path.append(os.path.abspath('../server.py'))
import server
class TestPosieService(unittest.TestCase):
def test_key_generation(self):
# Load public der key from http endpoint
key_string = base64.b64decode(server.key())
public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
self.assertIsNotNone(public_key)
<commit_msg>Update tests to init flask and use test client<commit_after>from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from server import app
import base64
import unittest
class TestPosieService(unittest.TestCase):
key_endpoint = "/key"
decrypt_endpoint = "/decrypt"
def setUp(self):
# creates a test client
self.app = app.test_client()
# propagate the exceptions to the test client
self.app.testing = True
r = self.app.get(self.key_endpoint)
key_string = base64.b64decode(r.data)
self.public_key = serialization.load_der_public_key(
key_string,
backend=default_backend()
)
def send_message(self, message):
ciphertext = self.public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
algorithm=hashes.SHA1(),
label=None
)
)
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data=base64.b64encode(ciphertext))
return r
def test_key_generation(self):
self.assertIsNotNone(self.public_key)
def test_decrypt_fail_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='rubbish')
self.assertEqual(r.status_code, 400)
def test_no_content_sends_400(self):
# Ask posie to decode message
r = self.app.post(self.decrypt_endpoint, data='')
self.assertEqual(r.status_code, 400)
def test_decrypts_message(self):
# Encrypt a message with the key
message = b"Some encrypted message"
# Ask posie to decode message
r = self.send_message(message)
# Compare to bytestring version of decrypted data
self.assertEqual(r.data, message)
|
5ac6cc208bf1a3fbe4e860a2356102a2457a1e43
|
server/mod_auth/auth.py
|
server/mod_auth/auth.py
|
from app_factory.create_app import db
from models import User
from forms import RegistrationForm, LoginForm
def load_user(user_id):
return User.query.filter_by(id=user_id).first()
def login(request):
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
|
from models import User
from forms import LoginForm
def load_user(user_id):
"""Returns a user from the database based on their id"""
return User.query.filter_by(id=user_id).first()
def login(request):
"""Handle a login request from a user."""
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
|
Clean up unused imports and add docstrings
|
Clean up unused imports and add docstrings
|
Python
|
mit
|
ganemone/ontheside,ganemone/ontheside,ganemone/ontheside
|
from app_factory.create_app import db
from models import User
from forms import RegistrationForm, LoginForm
def load_user(user_id):
return User.query.filter_by(id=user_id).first()
def login(request):
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
Clean up unused imports and add docstrings
|
from models import User
from forms import LoginForm
def load_user(user_id):
"""Returns a user from the database based on their id"""
return User.query.filter_by(id=user_id).first()
def login(request):
"""Handle a login request from a user."""
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
|
<commit_before>from app_factory.create_app import db
from models import User
from forms import RegistrationForm, LoginForm
def load_user(user_id):
return User.query.filter_by(id=user_id).first()
def login(request):
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
<commit_msg>Clean up unused imports and add docstrings<commit_after>
|
from models import User
from forms import LoginForm
def load_user(user_id):
"""Returns a user from the database based on their id"""
return User.query.filter_by(id=user_id).first()
def login(request):
"""Handle a login request from a user."""
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
|
from app_factory.create_app import db
from models import User
from forms import RegistrationForm, LoginForm
def load_user(user_id):
return User.query.filter_by(id=user_id).first()
def login(request):
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
Clean up unused imports and add docstringsfrom models import User
from forms import LoginForm
def load_user(user_id):
"""Returns a user from the database based on their id"""
return User.query.filter_by(id=user_id).first()
def login(request):
"""Handle a login request from a user."""
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
|
<commit_before>from app_factory.create_app import db
from models import User
from forms import RegistrationForm, LoginForm
def load_user(user_id):
return User.query.filter_by(id=user_id).first()
def login(request):
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
<commit_msg>Clean up unused imports and add docstrings<commit_after>from models import User
from forms import LoginForm
def load_user(user_id):
"""Returns a user from the database based on their id"""
return User.query.filter_by(id=user_id).first()
def login(request):
"""Handle a login request from a user."""
form = LoginForm.from_json(request.form)
if request.method == 'POST' and form.validate():
return True
|
276cb99f893443e4f1d242f861cd74d77770def4
|
inselect/tests/lib/test_segment.py
|
inselect/tests/lib/test_segment.py
|
import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# from pprint import pprint
# pprint([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# pprint([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
|
import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
|
Remove commented-out debug code :-(
|
Remove commented-out debug code :-(
|
Python
|
bsd-3-clause
|
NaturalHistoryMuseum/inselect,NaturalHistoryMuseum/inselect
|
import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# from pprint import pprint
# pprint([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# pprint([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
Remove commented-out debug code :-(
|
import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
|
<commit_before>import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# from pprint import pprint
# pprint([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# pprint([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
<commit_msg>Remove commented-out debug code :-(<commit_after>
|
import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
|
import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# from pprint import pprint
# pprint([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# pprint([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
Remove commented-out debug code :-(import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
|
<commit_before>import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# from pprint import pprint
# pprint([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
# pprint([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
<commit_msg>Remove commented-out debug code :-(<commit_after>import json
import unittest
from pathlib import Path
from inselect.lib.document import InselectDocument
from inselect.lib.segment import segment_document
TESTDATA = Path(__file__).parent.parent / 'test_data'
class TestSegment(unittest.TestCase):
def test_segment_document(self):
doc = InselectDocument.load(TESTDATA / 'test_segment.inselect')
self.assertEqual(5, len(doc.items))
# Compare the rects in pixels
expected = doc.scanned.from_normalised([i['rect'] for i in doc.items])
doc.set_items([])
self.assertEqual(0, len(doc.items))
doc, display_image = segment_document(doc)
actual = doc.scanned.from_normalised([i['rect'] for i in doc.items])
self.assertEqual(list(expected), list(actual))
if __name__ == '__main__':
unittest.main()
|
eed7727afd1622cbefb8ef1e113f15706170dfdf
|
parens.py
|
parens.py
|
def balanceness(paren_series):
indicator = 0
for paren in paren_series:
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken.
if indicator < 0
reutrn -1
|
def balanceness(paren_series):
indicator = 0
for paren in paren_series:
print paren
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken, and the rest of the string does not need
# to be traversed.
if indicator < 0:
return -1
# If the indicator has remained greater than or equal to 0 the whole
# traversal of the string, then no ')'s have preceded unclosed '('s.
if indicator is 0:
# An indicator = 0 means an equal number of '('s and ')'s.
return 0
else:
# An indicator > 1 means a greater number of '('s than ')'s.
return 1
|
Complete quick attempt at function.
|
Complete quick attempt at function.
|
Python
|
mit
|
jefimenko/data-structures
|
def balanceness(paren_series):
indicator = 0
for paren in paren_series:
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken.
if indicator < 0
reutrn -1
Complete quick attempt at function.
|
def balanceness(paren_series):
indicator = 0
for paren in paren_series:
print paren
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken, and the rest of the string does not need
# to be traversed.
if indicator < 0:
return -1
# If the indicator has remained greater than or equal to 0 the whole
# traversal of the string, then no ')'s have preceded unclosed '('s.
if indicator is 0:
# An indicator = 0 means an equal number of '('s and ')'s.
return 0
else:
# An indicator > 1 means a greater number of '('s than ')'s.
return 1
|
<commit_before>def balanceness(paren_series):
indicator = 0
for paren in paren_series:
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken.
if indicator < 0
reutrn -1
<commit_msg>Complete quick attempt at function.<commit_after>
|
def balanceness(paren_series):
indicator = 0
for paren in paren_series:
print paren
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken, and the rest of the string does not need
# to be traversed.
if indicator < 0:
return -1
# If the indicator has remained greater than or equal to 0 the whole
# traversal of the string, then no ')'s have preceded unclosed '('s.
if indicator is 0:
# An indicator = 0 means an equal number of '('s and ')'s.
return 0
else:
# An indicator > 1 means a greater number of '('s than ')'s.
return 1
|
def balanceness(paren_series):
indicator = 0
for paren in paren_series:
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken.
if indicator < 0
reutrn -1
Complete quick attempt at function.def balanceness(paren_series):
indicator = 0
for paren in paren_series:
print paren
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken, and the rest of the string does not need
# to be traversed.
if indicator < 0:
return -1
# If the indicator has remained greater than or equal to 0 the whole
# traversal of the string, then no ')'s have preceded unclosed '('s.
if indicator is 0:
# An indicator = 0 means an equal number of '('s and ')'s.
return 0
else:
# An indicator > 1 means a greater number of '('s than ')'s.
return 1
|
<commit_before>def balanceness(paren_series):
indicator = 0
for paren in paren_series:
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken.
if indicator < 0
reutrn -1
<commit_msg>Complete quick attempt at function.<commit_after>def balanceness(paren_series):
indicator = 0
for paren in paren_series:
print paren
if paren == u'(':
indicator += 1
elif paren == u')':
indicator -= 1
# At any point in time, if a ')' precedes a '(', then the series
# of parenthesis is broken, and the rest of the string does not need
# to be traversed.
if indicator < 0:
return -1
# If the indicator has remained greater than or equal to 0 the whole
# traversal of the string, then no ')'s have preceded unclosed '('s.
if indicator is 0:
# An indicator = 0 means an equal number of '('s and ')'s.
return 0
else:
# An indicator > 1 means a greater number of '('s than ')'s.
return 1
|
0d2667684f0b65cb832528a80ef7bf008bf9c706
|
pentai/ai/standardise.py
|
pentai/ai/standardise.py
|
import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state): # Test code only
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = min(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
|
import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state):
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = max(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
|
Use max representation for smaller space usage.
|
Use max representation for smaller space usage.
|
Python
|
mit
|
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
|
import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state): # Test code only
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = min(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
Use max representation for smaller space usage.
|
import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state):
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = max(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
|
<commit_before>import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state): # Test code only
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = min(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
<commit_msg>Use max representation for smaller space usage.<commit_after>
|
import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state):
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = max(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
|
import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state): # Test code only
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = min(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
Use max representation for smaller space usage.import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state):
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = max(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
|
<commit_before>import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state): # Test code only
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = min(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
<commit_msg>Use max representation for smaller space usage.<commit_after>import rot_standardise as rs_m
import trans_standardise as t_m
def standardise(orig_state):
possibilities = rs_m.rot_possibilities(orig_state)
all_combined = []
for p in possibilities:
c = combine_and_trim(p)
all_combined.append((c[0], c))
try:
s = max(all_combined)[1]
except IndexError:
import pdb
pdb.set_trace()
return s
def combine_and_trim(poss):
rot_std, fwd, rev = poss
both_std, lshift, dshift = t_m.shift(rot_std)
trimmed = both_std.get_board().d_strips[0].strips
while len(trimmed) and trimmed[-1] == 0:
trimmed.pop()
trimmed_tuple = tuple(trimmed)
# Now combine lshift and dshift into fwd and rev
def both_fwd(*pos):
x, y = fwd(*pos)
x -= lshift
y -= dshift
return x, y
def both_rev(*pos):
x, y = pos
x += lshift
y += dshift
new_p = rev(x, y)
return new_p
return trimmed_tuple, both_fwd, both_rev
|
a5c2e4d8eeaaaa03195344fdd2cb9654e63f8a55
|
NagiosWrapper/NagiosWrapper.py
|
NagiosWrapper/NagiosWrapper.py
|
import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(pluginCommandLineList, stdout=subprocess.PIPE)
out, err = p.communicate()
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
|
import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(
pluginCommandLineList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = p.communicate()
checksLogger.debug('Output of {}: {}'.format(pluginCommand, out))
if err:
checksLogger.error('Error executing {}: {}'.format(
pluginCommand, err))
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
|
Add error logging to nagios wrapper
|
Add error logging to nagios wrapper
|
Python
|
bsd-3-clause
|
shanethehat/sd-agent-plugins,bastiendonjon/sd-agent-plugins,bencer/sd-agent-plugins,bencer/sd-agent-plugins,shanethehat/sd-agent-plugins,bastiendonjon/sd-agent-plugins
|
import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(pluginCommandLineList, stdout=subprocess.PIPE)
out, err = p.communicate()
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
Add error logging to nagios wrapper
|
import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(
pluginCommandLineList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = p.communicate()
checksLogger.debug('Output of {}: {}'.format(pluginCommand, out))
if err:
checksLogger.error('Error executing {}: {}'.format(
pluginCommand, err))
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
|
<commit_before>import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(pluginCommandLineList, stdout=subprocess.PIPE)
out, err = p.communicate()
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
<commit_msg>Add error logging to nagios wrapper<commit_after>
|
import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(
pluginCommandLineList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = p.communicate()
checksLogger.debug('Output of {}: {}'.format(pluginCommand, out))
if err:
checksLogger.error('Error executing {}: {}'.format(
pluginCommand, err))
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
|
import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(pluginCommandLineList, stdout=subprocess.PIPE)
out, err = p.communicate()
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
Add error logging to nagios wrapperimport subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(
pluginCommandLineList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = p.communicate()
checksLogger.debug('Output of {}: {}'.format(pluginCommand, out))
if err:
checksLogger.error('Error executing {}: {}'.format(
pluginCommand, err))
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
|
<commit_before>import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(pluginCommandLineList, stdout=subprocess.PIPE)
out, err = p.communicate()
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
<commit_msg>Add error logging to nagios wrapper<commit_after>import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(
pluginCommandLineList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = p.communicate()
checksLogger.debug('Output of {}: {}'.format(pluginCommand, out))
if err:
checksLogger.error('Error executing {}: {}'.format(
pluginCommand, err))
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
|
7560c3efc638940cca8f25a6e58e4ea1f85dc9dc
|
src/sentry/filters/builtins.py
|
src/sentry/filters/builtins.py
|
"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
def get_choices(self):
return SortedDict([
(0, _('Unresolved')),
(1, _('Resolved')),
])
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
|
"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from sentry.constants import STATUS_LEVELS
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
choices = SortedDict(STATUS_LEVELS)
def get_choices(self):
return self.choices
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
|
Change Status filters to build from constant
|
Change Status filters to build from constant
|
Python
|
bsd-3-clause
|
jean/sentry,zenefits/sentry,camilonova/sentry,mitsuhiko/sentry,nicholasserra/sentry,wujuguang/sentry,zenefits/sentry,rdio/sentry,BuildingLink/sentry,JamesMura/sentry,drcapulet/sentry,imankulov/sentry,fotinakis/sentry,llonchj/sentry,BayanGroup/sentry,looker/sentry,felixbuenemann/sentry,fotinakis/sentry,Kryz/sentry,NickPresta/sentry,vperron/sentry,argonemyth/sentry,jean/sentry,JamesMura/sentry,jokey2k/sentry,1tush/sentry,Natim/sentry,ifduyue/sentry,gencer/sentry,ewdurbin/sentry,imankulov/sentry,beeftornado/sentry,jean/sentry,beeftornado/sentry,rdio/sentry,argonemyth/sentry,BayanGroup/sentry,hongliang5623/sentry,argonemyth/sentry,daevaorn/sentry,daevaorn/sentry,NickPresta/sentry,llonchj/sentry,gencer/sentry,BuildingLink/sentry,beeftornado/sentry,ifduyue/sentry,kevinastone/sentry,JTCunning/sentry,rdio/sentry,wong2/sentry,TedaLIEz/sentry,BuildingLink/sentry,mvaled/sentry,boneyao/sentry,fotinakis/sentry,looker/sentry,boneyao/sentry,mvaled/sentry,hongliang5623/sentry,drcapulet/sentry,ngonzalvez/sentry,ngonzalvez/sentry,SilentCircle/sentry,imankulov/sentry,JamesMura/sentry,nicholasserra/sentry,jean/sentry,jokey2k/sentry,korealerts1/sentry,korealerts1/sentry,BuildingLink/sentry,songyi199111/sentry,1tush/sentry,vperron/sentry,Kryz/sentry,JTCunning/sentry,mvaled/sentry,alexm92/sentry,vperron/sentry,ewdurbin/sentry,rdio/sentry,beni55/sentry,wong2/sentry,JamesMura/sentry,gencer/sentry,zenefits/sentry,kevinlondon/sentry,korealerts1/sentry,alexm92/sentry,jokey2k/sentry,pauloschilling/sentry,looker/sentry,ifduyue/sentry,boneyao/sentry,fotinakis/sentry,ifduyue/sentry,kevinlondon/sentry,fuziontech/sentry,alexm92/sentry,gencer/sentry,SilentCircle/sentry,felixbuenemann/sentry,jean/sentry,NickPresta/sentry,BayanGroup/sentry,mitsuhiko/sentry,fuziontech/sentry,looker/sentry,gg7/sentry,JackDanger/sentry,beni55/sentry,ngonzalvez/sentry,hongliang5623/sentry,SilentCircle/sentry,wujuguang/sentry,mvaled/sentry,JTCunning/sentry,Kryz/sentry,looker/sentry,JackDanger/sentry,pauloschilling/sentry,1tush/sentry,zenefits/sentry,songyi199111/sentry,JamesMura/sentry,songyi199111/sentry,llonchj/sentry,camilonova/sentry,drcapulet/sentry,Natim/sentry,zenefits/sentry,kevinastone/sentry,kevinlondon/sentry,wong2/sentry,mvaled/sentry,camilonova/sentry,daevaorn/sentry,beni55/sentry,ewdurbin/sentry,TedaLIEz/sentry,gg7/sentry,daevaorn/sentry,ifduyue/sentry,SilentCircle/sentry,pauloschilling/sentry,JackDanger/sentry,fuziontech/sentry,Natim/sentry,kevinastone/sentry,NickPresta/sentry,TedaLIEz/sentry,gg7/sentry,felixbuenemann/sentry,nicholasserra/sentry,wujuguang/sentry,BuildingLink/sentry,mvaled/sentry,gencer/sentry
|
"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
def get_choices(self):
return SortedDict([
(0, _('Unresolved')),
(1, _('Resolved')),
])
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
Change Status filters to build from constant
|
"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from sentry.constants import STATUS_LEVELS
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
choices = SortedDict(STATUS_LEVELS)
def get_choices(self):
return self.choices
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
|
<commit_before>"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
def get_choices(self):
return SortedDict([
(0, _('Unresolved')),
(1, _('Resolved')),
])
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
<commit_msg>Change Status filters to build from constant<commit_after>
|
"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from sentry.constants import STATUS_LEVELS
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
choices = SortedDict(STATUS_LEVELS)
def get_choices(self):
return self.choices
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
|
"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
def get_choices(self):
return SortedDict([
(0, _('Unresolved')),
(1, _('Resolved')),
])
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
Change Status filters to build from constant"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from sentry.constants import STATUS_LEVELS
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
choices = SortedDict(STATUS_LEVELS)
def get_choices(self):
return self.choices
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
|
<commit_before>"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
def get_choices(self):
return SortedDict([
(0, _('Unresolved')),
(1, _('Resolved')),
])
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
<commit_msg>Change Status filters to build from constant<commit_after>"""
sentry.filters.base
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext_lazy as _
from sentry.conf import settings
from sentry.constants import STATUS_LEVELS
from .base import Filter, GroupFilter
__all__ = ('StatusFilter', 'LoggerFilter', 'LevelFilter')
class StatusFilter(GroupFilter):
label = _('Status')
column = 'status'
default = '0'
choices = SortedDict(STATUS_LEVELS)
def get_choices(self):
return self.choices
class LoggerFilter(Filter):
label = _('Logger')
column = 'logger'
class LevelFilter(Filter):
label = _('Level')
column = 'level'
def get_choices(self):
return SortedDict((str(k), v) for k, v in settings.LOG_LEVELS)
def get_query_set(self, queryset):
return queryset.filter(level=self.get_value())
|
ada858de787991c885030bb122e50df36b6fdc11
|
github3/__init__.py
|
github3/__init__.py
|
"""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
from .legacy import LegacyUser, LegacyRepo, LegacyIssue
from .org import Organization, Team
from .pulls import PullRequest
from .repo import Repository, Branch
from .user import User
|
"""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
|
Clean up namespace as mentioned.
|
Clean up namespace as mentioned.
|
Python
|
bsd-3-clause
|
balloob/github3.py,krxsky/github3.py,icio/github3.py,sigmavirus24/github3.py,wbrefvem/github3.py,christophelec/github3.py,ueg1990/github3.py,itsmemattchung/github3.py,agamdua/github3.py,h4ck3rm1k3/github3.py,degustaf/github3.py,jim-minter/github3.py
|
"""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
from .legacy import LegacyUser, LegacyRepo, LegacyIssue
from .org import Organization, Team
from .pulls import PullRequest
from .repo import Repository, Branch
from .user import User
Clean up namespace as mentioned.
|
"""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
|
<commit_before>"""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
from .legacy import LegacyUser, LegacyRepo, LegacyIssue
from .org import Organization, Team
from .pulls import PullRequest
from .repo import Repository, Branch
from .user import User
<commit_msg>Clean up namespace as mentioned.<commit_after>
|
"""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
|
"""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
from .legacy import LegacyUser, LegacyRepo, LegacyIssue
from .org import Organization, Team
from .pulls import PullRequest
from .repo import Repository, Branch
from .user import User
Clean up namespace as mentioned."""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
|
<commit_before>"""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
from .event import Event
from .gist import Gist, GistComment, GistFile
from .git import Blob, GitData, Commit, Reference, GitObject, Tag, Tree, Hash
from .issue import Issue, IssueComment, IssueEvent, Label, Milestone
from .legacy import LegacyUser, LegacyRepo, LegacyIssue
from .org import Organization, Team
from .pulls import PullRequest
from .repo import Repository, Branch
from .user import User
<commit_msg>Clean up namespace as mentioned.<commit_after>"""
github3
=======
See http://github3py.rtfd.org/ for documentation.
:copyright: (c) 2012 by Ian Cordasco
:license: Modified BSD, see LICENSE for more details
"""
__title__ = 'github3'
__author__ = 'Ian Cordasco'
__license__ = 'Modified BSD'
__copyright__ = 'Copyright 2012 Ian Cordasco'
__version__ = '0.1a5'
from .api import *
from .github import GitHub
from .models import GitHubError
|
f56f98d5ec2b9cd689349cc239ca550f1182563e
|
src/olympia/core/tests/test_db.py
|
src/olympia/core/tests/test_db.py
|
# -*- coding: utf-8 -*-
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
|
# -*- coding: utf-8 -*-
import os
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
def test_no_duplicate_migration_ids():
seen = set()
migration_ids = [
fname.split('-')[0] for fname in os.listdir('src/olympia/migrations/')
if fname.endswith('.sql')]
duplicates = {x for x in migration_ids if x in seen or seen.add(x)}
assert not duplicates
|
Add simple test to fail in case of duplicate migration ids.
|
Add simple test to fail in case of duplicate migration ids.
The test fails by showing which migrations are duplicated.
```python
src/olympia/core/tests/test_db.py:29: in test_no_duplicate_migration_ids
assert not duplicates
E AssertionError: assert not {'99'}
```
Fixes #11852
|
Python
|
bsd-3-clause
|
eviljeff/olympia,eviljeff/olympia,psiinon/addons-server,eviljeff/olympia,psiinon/addons-server,psiinon/addons-server,bqbn/addons-server,diox/olympia,mozilla/addons-server,mozilla/olympia,bqbn/addons-server,wagnerand/addons-server,eviljeff/olympia,mozilla/olympia,wagnerand/addons-server,mozilla/olympia,wagnerand/addons-server,wagnerand/addons-server,psiinon/addons-server,mozilla/addons-server,bqbn/addons-server,mozilla/addons-server,diox/olympia,mozilla/olympia,mozilla/addons-server,diox/olympia,diox/olympia,bqbn/addons-server
|
# -*- coding: utf-8 -*-
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
Add simple test to fail in case of duplicate migration ids.
The test fails by showing which migrations are duplicated.
```python
src/olympia/core/tests/test_db.py:29: in test_no_duplicate_migration_ids
assert not duplicates
E AssertionError: assert not {'99'}
```
Fixes #11852
|
# -*- coding: utf-8 -*-
import os
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
def test_no_duplicate_migration_ids():
seen = set()
migration_ids = [
fname.split('-')[0] for fname in os.listdir('src/olympia/migrations/')
if fname.endswith('.sql')]
duplicates = {x for x in migration_ids if x in seen or seen.add(x)}
assert not duplicates
|
<commit_before># -*- coding: utf-8 -*-
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
<commit_msg>Add simple test to fail in case of duplicate migration ids.
The test fails by showing which migrations are duplicated.
```python
src/olympia/core/tests/test_db.py:29: in test_no_duplicate_migration_ids
assert not duplicates
E AssertionError: assert not {'99'}
```
Fixes #11852<commit_after>
|
# -*- coding: utf-8 -*-
import os
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
def test_no_duplicate_migration_ids():
seen = set()
migration_ids = [
fname.split('-')[0] for fname in os.listdir('src/olympia/migrations/')
if fname.endswith('.sql')]
duplicates = {x for x in migration_ids if x in seen or seen.add(x)}
assert not duplicates
|
# -*- coding: utf-8 -*-
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
Add simple test to fail in case of duplicate migration ids.
The test fails by showing which migrations are duplicated.
```python
src/olympia/core/tests/test_db.py:29: in test_no_duplicate_migration_ids
assert not duplicates
E AssertionError: assert not {'99'}
```
Fixes #11852# -*- coding: utf-8 -*-
import os
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
def test_no_duplicate_migration_ids():
seen = set()
migration_ids = [
fname.split('-')[0] for fname in os.listdir('src/olympia/migrations/')
if fname.endswith('.sql')]
duplicates = {x for x in migration_ids if x in seen or seen.add(x)}
assert not duplicates
|
<commit_before># -*- coding: utf-8 -*-
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
<commit_msg>Add simple test to fail in case of duplicate migration ids.
The test fails by showing which migrations are duplicated.
```python
src/olympia/core/tests/test_db.py:29: in test_no_duplicate_migration_ids
assert not duplicates
E AssertionError: assert not {'99'}
```
Fixes #11852<commit_after># -*- coding: utf-8 -*-
import os
import pytest
from olympia.core.tests.db_tests_testapp.models import TestRegularCharField
@pytest.mark.django_db
@pytest.mark.parametrize('value', [
u'a',
u'🔍', # Magnifying Glass Tilted Left (U+1F50D)
u'❤', # Heavy Black Heart (U+2764, U+FE0F)
])
def test_max_length_utf8mb4(value):
TestRegularCharField.objects.create(name=value * 255)
assert TestRegularCharField.objects.get().name == value * 255
def test_no_duplicate_migration_ids():
seen = set()
migration_ids = [
fname.split('-')[0] for fname in os.listdir('src/olympia/migrations/')
if fname.endswith('.sql')]
duplicates = {x for x in migration_ids if x in seen or seen.add(x)}
assert not duplicates
|
d483e49d826607c0f59ee4b531a2b8e98beffa40
|
guizero/__init__.py
|
guizero/__init__.py
|
try:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
|
try:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
__all__ = ['utilities', 'alerts', 'App', 'Box', 'ButtonGroup', 'CheckBox', 'Combo', 'MenuBar', 'Picture', 'PushButton',
'RadioButton', 'Slider', 'Text', 'TextBox', 'PushButton']
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
|
Add an all to init
|
Add an all to init
|
Python
|
bsd-3-clause
|
lawsie/guizero,lawsie/guizero,lawsie/guizero
|
try:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
Add an all to init
|
try:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
__all__ = ['utilities', 'alerts', 'App', 'Box', 'ButtonGroup', 'CheckBox', 'Combo', 'MenuBar', 'Picture', 'PushButton',
'RadioButton', 'Slider', 'Text', 'TextBox', 'PushButton']
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
|
<commit_before>try:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
<commit_msg>Add an all to init<commit_after>
|
try:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
__all__ = ['utilities', 'alerts', 'App', 'Box', 'ButtonGroup', 'CheckBox', 'Combo', 'MenuBar', 'Picture', 'PushButton',
'RadioButton', 'Slider', 'Text', 'TextBox', 'PushButton']
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
|
try:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
Add an all to inittry:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
__all__ = ['utilities', 'alerts', 'App', 'Box', 'ButtonGroup', 'CheckBox', 'Combo', 'MenuBar', 'Picture', 'PushButton',
'RadioButton', 'Slider', 'Text', 'TextBox', 'PushButton']
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
|
<commit_before>try:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
<commit_msg>Add an all to init<commit_after>try:
from tkinter import *
except:
from Tkinter import *
# -----------------------------
__all__ = ['utilities', 'alerts', 'App', 'Box', 'ButtonGroup', 'CheckBox', 'Combo', 'MenuBar', 'Picture', 'PushButton',
'RadioButton', 'Slider', 'Text', 'TextBox', 'PushButton']
import utilities as utils
from alerts import *
from App import App
from Box import Box
from ButtonGroup import ButtonGroup
from CheckBox import CheckBox
from Combo import Combo
from MenuBar import MenuBar
from Picture import Picture
from PushButton import PushButton
from RadioButton import RadioButton
from Slider import Slider
from Text import Text
from TextBox import TextBox
from PushButton import PushButton
|
9a1272082f8750565f727f2c97a71768a9ceb7ca
|
books/search_indexes.py
|
books/search_indexes.py
|
from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
|
from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
|
Add fields to index so 'update_index' works
|
Add fields to index so 'update_index' works
|
Python
|
mit
|
phildini/bockus,phildini/bockus,phildini/bockus
|
from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()Add fields to index so 'update_index' works
|
from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
|
<commit_before>from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()<commit_msg>Add fields to index so 'update_index' works<commit_after>
|
from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
|
from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()Add fields to index so 'update_index' worksfrom haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
|
<commit_before>from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()<commit_msg>Add fields to index so 'update_index' works<commit_after>from haystack import indexes
from books.models import Book, Series
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
class SeriesIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
library = indexes.IntegerField(model_attr="library_id")
def get_model(self):
return Series
def index_queryset(self, using=None):
return self.get_model().objects.all()
def get_updated_field(self):
return 'modified'
|
3fd3795eb1f055e93c74362dfa5bdf46a5141551
|
py-bindings/ompl/util/__init__.py
|
py-bindings/ompl/util/__init__.py
|
from os.path import abspath, dirname
from sys import platform
if platform != 'nt' and platform != 'win32':
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
|
from os.path import abspath, dirname
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
|
Revert changes to py-bindings script
|
Revert changes to py-bindings script
--HG--
branch : windows
|
Python
|
bsd-3-clause
|
jvgomez/ompl,davetcoleman/ompl,davetcoleman/ompl,florianhauer/ompl,florianhauer/ompl,florianhauer/ompl,sonny-tarbouriech/ompl,utiasASRL/batch-informed-trees,sonny-tarbouriech/ompl,davetcoleman/ompl,jvgomez/ompl,utiasASRL/batch-informed-trees,sonny-tarbouriech/ompl,davetcoleman/ompl,sonny-tarbouriech/ompl,florianhauer/ompl,florianhauer/ompl,utiasASRL/batch-informed-trees,utiasASRL/batch-informed-trees,jvgomez/ompl,davetcoleman/ompl,jvgomez/ompl,florianhauer/ompl,davetcoleman/ompl,sonny-tarbouriech/ompl,sonny-tarbouriech/ompl,jvgomez/ompl,utiasASRL/batch-informed-trees,jvgomez/ompl,utiasASRL/batch-informed-trees
|
from os.path import abspath, dirname
from sys import platform
if platform != 'nt' and platform != 'win32':
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
Revert changes to py-bindings script
--HG--
branch : windows
|
from os.path import abspath, dirname
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
|
<commit_before>from os.path import abspath, dirname
from sys import platform
if platform != 'nt' and platform != 'win32':
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
<commit_msg>Revert changes to py-bindings script
--HG--
branch : windows<commit_after>
|
from os.path import abspath, dirname
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
|
from os.path import abspath, dirname
from sys import platform
if platform != 'nt' and platform != 'win32':
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
Revert changes to py-bindings script
--HG--
branch : windowsfrom os.path import abspath, dirname
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
|
<commit_before>from os.path import abspath, dirname
from sys import platform
if platform != 'nt' and platform != 'win32':
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
<commit_msg>Revert changes to py-bindings script
--HG--
branch : windows<commit_after>from os.path import abspath, dirname
from ompl import dll_loader
dll_loader('ompl', dirname(abspath(__file__)))
from _util import *
|
6e1892daec726b44b1bbb4d085e27fa03c0a419b
|
server/kcaa/kcsapi/client_test.py
|
server/kcaa/kcsapi/client_test.py
|
#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.PORT
screen.update('/api_req_mission/result', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def update(self, screen, api_name):
screen.update(api_name, None, None, None, False)
def update_sequence(self, screen, api_names):
for api_name in api_names:
screen.update(api_name, None, None, None, False)
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.PORT
self.update(screen, '/api_req_mission/result')
assert screen.screen == screens.MISSION_RESULT
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.MISSION_RESULT
def test_mission_result_real_sequence(self):
screen = client.Screen()
screen.screen = screens.PORT
self.update_sequence(screen, [
'/api_auth_member/logincheck',
'/api_get_member/material',
'/api_get_member/deck_port',
'/api_get_member/ndock',
'/api_get_member/ship3',
'/api_get_member/basic',
'/api_req_mission/result',
'/api_get_member/deck_port',
'/api_get_member/basic',
'/api_get_member/ship2',
'/api_get_member/material',
'/api_get_member/useitem',
])
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
|
Add a Screen test for sequence of KCSAPI responses.
|
Add a Screen test for sequence of KCSAPI responses.
|
Python
|
apache-2.0
|
kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa
|
#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.PORT
screen.update('/api_req_mission/result', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
Add a Screen test for sequence of KCSAPI responses.
|
#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def update(self, screen, api_name):
screen.update(api_name, None, None, None, False)
def update_sequence(self, screen, api_names):
for api_name in api_names:
screen.update(api_name, None, None, None, False)
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.PORT
self.update(screen, '/api_req_mission/result')
assert screen.screen == screens.MISSION_RESULT
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.MISSION_RESULT
def test_mission_result_real_sequence(self):
screen = client.Screen()
screen.screen = screens.PORT
self.update_sequence(screen, [
'/api_auth_member/logincheck',
'/api_get_member/material',
'/api_get_member/deck_port',
'/api_get_member/ndock',
'/api_get_member/ship3',
'/api_get_member/basic',
'/api_req_mission/result',
'/api_get_member/deck_port',
'/api_get_member/basic',
'/api_get_member/ship2',
'/api_get_member/material',
'/api_get_member/useitem',
])
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.PORT
screen.update('/api_req_mission/result', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
<commit_msg>Add a Screen test for sequence of KCSAPI responses.<commit_after>
|
#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def update(self, screen, api_name):
screen.update(api_name, None, None, None, False)
def update_sequence(self, screen, api_names):
for api_name in api_names:
screen.update(api_name, None, None, None, False)
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.PORT
self.update(screen, '/api_req_mission/result')
assert screen.screen == screens.MISSION_RESULT
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.MISSION_RESULT
def test_mission_result_real_sequence(self):
screen = client.Screen()
screen.screen = screens.PORT
self.update_sequence(screen, [
'/api_auth_member/logincheck',
'/api_get_member/material',
'/api_get_member/deck_port',
'/api_get_member/ndock',
'/api_get_member/ship3',
'/api_get_member/basic',
'/api_req_mission/result',
'/api_get_member/deck_port',
'/api_get_member/basic',
'/api_get_member/ship2',
'/api_get_member/material',
'/api_get_member/useitem',
])
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.PORT
screen.update('/api_req_mission/result', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
Add a Screen test for sequence of KCSAPI responses.#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def update(self, screen, api_name):
screen.update(api_name, None, None, None, False)
def update_sequence(self, screen, api_names):
for api_name in api_names:
screen.update(api_name, None, None, None, False)
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.PORT
self.update(screen, '/api_req_mission/result')
assert screen.screen == screens.MISSION_RESULT
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.MISSION_RESULT
def test_mission_result_real_sequence(self):
screen = client.Screen()
screen.screen = screens.PORT
self.update_sequence(screen, [
'/api_auth_member/logincheck',
'/api_get_member/material',
'/api_get_member/deck_port',
'/api_get_member/ndock',
'/api_get_member/ship3',
'/api_get_member/basic',
'/api_req_mission/result',
'/api_get_member/deck_port',
'/api_get_member/basic',
'/api_get_member/ship2',
'/api_get_member/material',
'/api_get_member/useitem',
])
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.PORT
screen.update('/api_req_mission/result', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
screen.update('/api_get_member/deck_port', None, None, None, False)
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
<commit_msg>Add a Screen test for sequence of KCSAPI responses.<commit_after>#!/usr/bin/env python
import pytest
import client
from kcaa import screens
class TestScreen(object):
def update(self, screen, api_name):
screen.update(api_name, None, None, None, False)
def update_sequence(self, screen, api_names):
for api_name in api_names:
screen.update(api_name, None, None, None, False)
def test_mission_result(self):
screen = client.Screen()
assert screen.screen == screens.UNKNOWN
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.PORT
self.update(screen, '/api_req_mission/result')
assert screen.screen == screens.MISSION_RESULT
self.update(screen, '/api_get_member/deck_port')
assert screen.screen == screens.MISSION_RESULT
def test_mission_result_real_sequence(self):
screen = client.Screen()
screen.screen = screens.PORT
self.update_sequence(screen, [
'/api_auth_member/logincheck',
'/api_get_member/material',
'/api_get_member/deck_port',
'/api_get_member/ndock',
'/api_get_member/ship3',
'/api_get_member/basic',
'/api_req_mission/result',
'/api_get_member/deck_port',
'/api_get_member/basic',
'/api_get_member/ship2',
'/api_get_member/material',
'/api_get_member/useitem',
])
assert screen.screen == screens.MISSION_RESULT
def main():
import doctest
doctest.testmod(client)
pytest.main(args=[__file__.replace('.pyc', '.py')])
if __name__ == '__main__':
main()
|
8bed90b9d98cc148a03c5b422c90974ddd85e18f
|
Scripts/multi_process_files.py
|
Scripts/multi_process_files.py
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageAnalyzer'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
Set the new ImageAnalyzer executable for multi-processing.
|
Set the new ImageAnalyzer executable for multi-processing.
|
Python
|
apache-2.0
|
HackTheStacks/darwin-notes-image-processing,HackTheStacks/darwin-notes-image-processing
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
Set the new ImageAnalyzer executable for multi-processing.
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageAnalyzer'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
<commit_before>#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
<commit_msg>Set the new ImageAnalyzer executable for multi-processing.<commit_after>
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageAnalyzer'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
Set the new ImageAnalyzer executable for multi-processing.#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageAnalyzer'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
<commit_before>#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
<commit_msg>Set the new ImageAnalyzer executable for multi-processing.<commit_after>#!/usr/bin/python
from joblib import Parallel, delayed
import multiprocessing
import os
from subprocess import call
# inputpath = '/data/amnh/darwin/images'
# segment_exe = '/home/luis_ibanez/bin/darwin-notes-image-processing/Release/Segmentation/ImageToEdges'
inputpath = '/home/ibanez/data/amnh/darwin_notes/images'
segment_exe = '/home/ibanez/bin/amnh/darwin/darwin-notes-image-processing/Release/Segmentation/ImageAnalyzer'
def handle_file(filename):
call([segment_exe, filename])
inputs = os.listdir(inputpath)
num_cores = multiprocessing.cpu_count()
results = Parallel(n_jobs=num_cores)(delayed(handle_file)(i) for i in inputs)
|
5a9ff0cbfade513b592bf309953bd2f927eb705c
|
mozillians/graphql/views.py
|
mozillians/graphql/views.py
|
from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
|
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
import waffle
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
if not waffle.flag_is_active(self.request, 'enable_graphql'):
raise Http404()
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
|
Add a waffle flag for GraphQL.
|
Add a waffle flag for GraphQL.
|
Python
|
bsd-3-clause
|
akatsoulas/mozillians,akatsoulas/mozillians,johngian/mozillians,akatsoulas/mozillians,mozilla/mozillians,johngian/mozillians,mozilla/mozillians,akatsoulas/mozillians,mozilla/mozillians,johngian/mozillians,mozilla/mozillians,johngian/mozillians
|
from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
Add a waffle flag for GraphQL.
|
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
import waffle
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
if not waffle.flag_is_active(self.request, 'enable_graphql'):
raise Http404()
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
|
<commit_before>from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
<commit_msg>Add a waffle flag for GraphQL.<commit_after>
|
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
import waffle
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
if not waffle.flag_is_active(self.request, 'enable_graphql'):
raise Http404()
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
|
from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
Add a waffle flag for GraphQL.from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
import waffle
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
if not waffle.flag_is_active(self.request, 'enable_graphql'):
raise Http404()
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
|
<commit_before>from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
<commit_msg>Add a waffle flag for GraphQL.<commit_after>from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
import waffle
from graphene_django.views import GraphQLView
class MozilliansGraphQLView(GraphQLView):
"""Class Based View to handle GraphQL requests."""
@csrf_exempt
def dispatch(self, *args, **kwargs):
"""Override dispatch method to allow the use of multiple decorators."""
if not waffle.flag_is_active(self.request, 'enable_graphql'):
raise Http404()
return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)
|
0731a34fd55477b20ffcd19c9b41cda0dd084d75
|
ggplot/utils/date_breaks.py
|
ggplot/utils/date_breaks.py
|
from matplotlib.dates import DayLocator, WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
|
from matplotlib.dates import MinuteLocator, HourLocator, DayLocator
from matplotlib.dates import WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'minute': MinuteLocator,
'hour': HourLocator,
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [minute, hour, day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
|
Add more granular date locators
|
Add more granular date locators
|
Python
|
bsd-2-clause
|
xguse/ggplot,andnovar/ggplot,benslice/ggplot,bitemyapp/ggplot,kmather73/ggplot,benslice/ggplot,udacity/ggplot,ricket1978/ggplot,mizzao/ggplot,wllmtrng/ggplot,smblance/ggplot,assad2012/ggplot,Cophy08/ggplot,xguse/ggplot,ricket1978/ggplot,mizzao/ggplot
|
from matplotlib.dates import DayLocator, WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
Add more granular date locators
|
from matplotlib.dates import MinuteLocator, HourLocator, DayLocator
from matplotlib.dates import WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'minute': MinuteLocator,
'hour': HourLocator,
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [minute, hour, day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
|
<commit_before>from matplotlib.dates import DayLocator, WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
<commit_msg>Add more granular date locators<commit_after>
|
from matplotlib.dates import MinuteLocator, HourLocator, DayLocator
from matplotlib.dates import WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'minute': MinuteLocator,
'hour': HourLocator,
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [minute, hour, day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
|
from matplotlib.dates import DayLocator, WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
Add more granular date locatorsfrom matplotlib.dates import MinuteLocator, HourLocator, DayLocator
from matplotlib.dates import WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'minute': MinuteLocator,
'hour': HourLocator,
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [minute, hour, day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
|
<commit_before>from matplotlib.dates import DayLocator, WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
<commit_msg>Add more granular date locators<commit_after>from matplotlib.dates import MinuteLocator, HourLocator, DayLocator
from matplotlib.dates import WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,units = 1, txt
units = units.rstrip('s') # e.g. weeks => week
n = int(n)
return n, units
# matplotlib's YearLocator uses different named
# arguments than the others
LOCATORS = {
'minute': MinuteLocator,
'hour': HourLocator,
'day': DayLocator,
'week': WeekdayLocator,
'month': MonthLocator,
'year': lambda interval: YearLocator(base=interval)
}
def date_breaks(width):
"""
"Regularly spaced dates."
width:
an interval specification. must be one of [minute, hour, day, week, month, year]
usage:
date_breaks(width = '1 year')
date_breaks(width = '6 weeks')
date_breaks('months')
"""
period, units = parse_break_str(width)
Locator = LOCATORS.get(units)
locator = Locator(interval=period)
return locator
|
97daa3e89cbe98602cedddc383876c45ad3f3813
|
purchase_stock_picking_invoice_link/__manifest__.py
|
purchase_stock_picking_invoice_link/__manifest__.py
|
# Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "http://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
|
# Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
|
Update dotfiles + switch to GH actions
|
[IMP] Update dotfiles + switch to GH actions
|
Python
|
agpl-3.0
|
OCA/stock-logistics-workflow,OCA/stock-logistics-workflow,BT-ojossen/stock-logistics-workflow,BT-ojossen/stock-logistics-workflow
|
# Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "http://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
[IMP] Update dotfiles + switch to GH actions
|
# Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
|
<commit_before># Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "http://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
<commit_msg>[IMP] Update dotfiles + switch to GH actions<commit_after>
|
# Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
|
# Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "http://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
[IMP] Update dotfiles + switch to GH actions# Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
|
<commit_before># Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "http://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
<commit_msg>[IMP] Update dotfiles + switch to GH actions<commit_after># Copyright 2019 Vicent Cubells <vicent.cubells@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Purchase Stock Picking Invoice Link",
"version": "13.0.1.0.0",
"category": "Warehouse Management",
"summary": "Adds link between purchases, pickings and invoices",
"author": "Tecnativa, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/stock-logistics-workflow",
"license": "AGPL-3",
"depends": ["stock_picking_invoice_link", "purchase"],
"installable": True,
}
|
6514e75b9a9b3bfeba1c43f95e386afcf67354bd
|
tests/test_django1_8_fixers.py
|
tests/test_django1_8_fixers.py
|
from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as exc:
from django.contrib import comments
expected_error = str(exc)
expected_error = expected_error.replace(r"\'", "'") # Sometimes quotes are escaped...
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
|
from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as excinfo:
from django.contrib import comments
exc = excinfo.value
expected_error = str(exc)
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
|
Fix buggy use of pytest.raises() in tests.
|
Fix buggy use of pytest.raises() in tests.
|
Python
|
mit
|
pakal/django-compat-patcher,pakal/django-compat-patcher
|
from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as exc:
from django.contrib import comments
expected_error = str(exc)
expected_error = expected_error.replace(r"\'", "'") # Sometimes quotes are escaped...
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
Fix buggy use of pytest.raises() in tests.
|
from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as excinfo:
from django.contrib import comments
exc = excinfo.value
expected_error = str(exc)
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
|
<commit_before>from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as exc:
from django.contrib import comments
expected_error = str(exc)
expected_error = expected_error.replace(r"\'", "'") # Sometimes quotes are escaped...
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
<commit_msg>Fix buggy use of pytest.raises() in tests.<commit_after>
|
from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as excinfo:
from django.contrib import comments
exc = excinfo.value
expected_error = str(exc)
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
|
from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as exc:
from django.contrib import comments
expected_error = str(exc)
expected_error = expected_error.replace(r"\'", "'") # Sometimes quotes are escaped...
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
Fix buggy use of pytest.raises() in tests.from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as excinfo:
from django.contrib import comments
exc = excinfo.value
expected_error = str(exc)
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
|
<commit_before>from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as exc:
from django.contrib import comments
expected_error = str(exc)
expected_error = expected_error.replace(r"\'", "'") # Sometimes quotes are escaped...
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
<commit_msg>Fix buggy use of pytest.raises() in tests.<commit_after>from __future__ import absolute_import, print_function, unicode_literals
import os
import pytest
import _test_utilities
def test_fix_outsourcing_contrib_comments():
if os.environ.get(
"IGNORE_CONTRIB_COMMENTS"
): # case where external dependency "django_comments" isn't loaded
with pytest.raises(ImportError) as excinfo:
from django.contrib import comments
exc = excinfo.value
expected_error = str(exc)
assert (
"No module named 'django_comments' (when loading alias name 'django.contrib.comments')"
in expected_error
)
else:
from django.contrib import comments
import django.contrib.comments
import django.contrib.comments.urls
assert isinstance(django.contrib.comments.urls.urlpatterns, list)
from django.contrib.comments.views import comments as comments_views
assert callable(comments_views.post_comment)
|
61e4b4fe80a2d89de5bb30310d65e08e45548208
|
tests/test_read_user_choice.py
|
tests/test_read_user_choice.py
|
# -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
|
# -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
def test_raise_if_options_is_not_a_non_empty_list():
with pytest.raises(TypeError):
read_user_choice('foo', 'NOT A LIST')
with pytest.raises(ValueError):
read_user_choice('foo', [])
|
Implement a test checking that options needs to be a non empty list
|
Implement a test checking that options needs to be a non empty list
|
Python
|
bsd-3-clause
|
pjbull/cookiecutter,benthomasson/cookiecutter,dajose/cookiecutter,atlassian/cookiecutter,dajose/cookiecutter,nhomar/cookiecutter,ionelmc/cookiecutter,christabor/cookiecutter,sp1rs/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,lgp171188/cookiecutter,Springerle/cookiecutter,agconti/cookiecutter,lucius-feng/cookiecutter,lgp171188/cookiecutter,stevepiercy/cookiecutter,venumech/cookiecutter,tylerdave/cookiecutter,lucius-feng/cookiecutter,ionelmc/cookiecutter,tylerdave/cookiecutter,atlassian/cookiecutter,audreyr/cookiecutter,kkujawinski/cookiecutter,audreyr/cookiecutter,foodszhang/cookiecutter,ramiroluz/cookiecutter,cguardia/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,cguardia/cookiecutter,janusnic/cookiecutter,Springerle/cookiecutter,terryjbates/cookiecutter,drgarcia1986/cookiecutter,foodszhang/cookiecutter,Vauxoo/cookiecutter,nhomar/cookiecutter,moi65/cookiecutter,pjbull/cookiecutter,willingc/cookiecutter,willingc/cookiecutter,moi65/cookiecutter,benthomasson/cookiecutter,takeflight/cookiecutter,kkujawinski/cookiecutter,drgarcia1986/cookiecutter,takeflight/cookiecutter,venumech/cookiecutter,michaeljoseph/cookiecutter,ramiroluz/cookiecutter,sp1rs/cookiecutter,agconti/cookiecutter,christabor/cookiecutter,michaeljoseph/cookiecutter,Vauxoo/cookiecutter,vintasoftware/cookiecutter,janusnic/cookiecutter,stevepiercy/cookiecutter,vintasoftware/cookiecutter,terryjbates/cookiecutter
|
# -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
Implement a test checking that options needs to be a non empty list
|
# -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
def test_raise_if_options_is_not_a_non_empty_list():
with pytest.raises(TypeError):
read_user_choice('foo', 'NOT A LIST')
with pytest.raises(ValueError):
read_user_choice('foo', [])
|
<commit_before># -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
<commit_msg>Implement a test checking that options needs to be a non empty list<commit_after>
|
# -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
def test_raise_if_options_is_not_a_non_empty_list():
with pytest.raises(TypeError):
read_user_choice('foo', 'NOT A LIST')
with pytest.raises(ValueError):
read_user_choice('foo', [])
|
# -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
Implement a test checking that options needs to be a non empty list# -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
def test_raise_if_options_is_not_a_non_empty_list():
with pytest.raises(TypeError):
read_user_choice('foo', 'NOT A LIST')
with pytest.raises(ValueError):
read_user_choice('foo', [])
|
<commit_before># -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
<commit_msg>Implement a test checking that options needs to be a non empty list<commit_after># -*- coding: utf-8 -*-
import click
import pytest
from cookiecutter.compat import read_user_choice
OPTIONS = ['hello', 'world', 'foo', 'bar']
EXPECTED_PROMPT = """Select varname:
1 - hello
2 - world
3 - foo
4 - bar
Choose from 1, 2, 3, 4!"""
@pytest.mark.parametrize('user_choice, expected_value', enumerate(OPTIONS, 1))
def test_click_invocation(mocker, user_choice, expected_value):
choice = mocker.patch('click.Choice')
choice.return_value = click.Choice(OPTIONS)
prompt = mocker.patch('click.prompt')
prompt.return_value = str(user_choice)
assert read_user_choice('varname', OPTIONS) == expected_value
prompt.assert_called_once_with(
EXPECTED_PROMPT,
type=click.Choice(OPTIONS),
default='1'
)
@pytest.fixture(params=[1, True, False, None, [], {}])
def invalid_options(request):
return ['foo', 'bar', request.param]
def test_raise_on_non_str_options(invalid_options):
with pytest.raises(TypeError):
read_user_choice('foo', invalid_options)
def test_raise_if_options_is_not_a_non_empty_list():
with pytest.raises(TypeError):
read_user_choice('foo', 'NOT A LIST')
with pytest.raises(ValueError):
read_user_choice('foo', [])
|
0b746180bbb3d7008ac0ece14407b661b01941e2
|
website/tests/models/test_short_url.py
|
website/tests/models/test_short_url.py
|
import app
from models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
|
from models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
|
Remove unused import from test short url
|
Remove unused import from test short url
|
Python
|
lgpl-2.1
|
reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations
|
import app
from models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
Remove unused import from test short url
|
from models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
|
<commit_before>import app
from models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
<commit_msg>Remove unused import from test short url<commit_after>
|
from models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
|
import app
from models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
Remove unused import from test short urlfrom models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
|
<commit_before>import app
from models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
<commit_msg>Remove unused import from test short url<commit_after>from models import ShortURL
def test_encode_decode():
base = ShortURL.base
ids_to_test = (
0, 1, 2, 9, 10, 11, 15, 89, 1000, 999, 998, 8765431234567,
base, base - 1, base + 1, base * 2, base * 2 - 1, base * base
)
for test_id in ids_to_test:
encoded = ShortURL(id=test_id, address='some_address').shorthand
decoded = ShortURL.shorthand_to_id(encoded)
assert decoded == test_id
|
b5c85d3bbeb34dd3e5dd9c376bc3e121e518084e
|
src/zeit/workflow/xmlrpc/tests.py
|
src/zeit/workflow/xmlrpc/tests.py
|
# Copyright (c) 2008-2011 gocept gmbh & co. kg
# See also LICENSE.txt
from zope.testing import doctest
import unittest
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
suite = unittest.TestSuite()
suite.addTest(zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer,
product_config={'zeit.workflow': zeit.workflow.testing.product_config}
))
return suite
|
# Copyright (c) 2008-2012 gocept gmbh & co. kg
# See also LICENSE.txt
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
return zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer
)
|
Remove superfluous (and wrong!) product config declaration
|
Remove superfluous (and wrong!) product config declaration
|
Python
|
bsd-3-clause
|
ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms
|
# Copyright (c) 2008-2011 gocept gmbh & co. kg
# See also LICENSE.txt
from zope.testing import doctest
import unittest
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
suite = unittest.TestSuite()
suite.addTest(zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer,
product_config={'zeit.workflow': zeit.workflow.testing.product_config}
))
return suite
Remove superfluous (and wrong!) product config declaration
|
# Copyright (c) 2008-2012 gocept gmbh & co. kg
# See also LICENSE.txt
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
return zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer
)
|
<commit_before># Copyright (c) 2008-2011 gocept gmbh & co. kg
# See also LICENSE.txt
from zope.testing import doctest
import unittest
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
suite = unittest.TestSuite()
suite.addTest(zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer,
product_config={'zeit.workflow': zeit.workflow.testing.product_config}
))
return suite
<commit_msg>Remove superfluous (and wrong!) product config declaration<commit_after>
|
# Copyright (c) 2008-2012 gocept gmbh & co. kg
# See also LICENSE.txt
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
return zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer
)
|
# Copyright (c) 2008-2011 gocept gmbh & co. kg
# See also LICENSE.txt
from zope.testing import doctest
import unittest
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
suite = unittest.TestSuite()
suite.addTest(zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer,
product_config={'zeit.workflow': zeit.workflow.testing.product_config}
))
return suite
Remove superfluous (and wrong!) product config declaration# Copyright (c) 2008-2012 gocept gmbh & co. kg
# See also LICENSE.txt
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
return zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer
)
|
<commit_before># Copyright (c) 2008-2011 gocept gmbh & co. kg
# See also LICENSE.txt
from zope.testing import doctest
import unittest
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
suite = unittest.TestSuite()
suite.addTest(zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer,
product_config={'zeit.workflow': zeit.workflow.testing.product_config}
))
return suite
<commit_msg>Remove superfluous (and wrong!) product config declaration<commit_after># Copyright (c) 2008-2012 gocept gmbh & co. kg
# See also LICENSE.txt
import zeit.cms.testing
import zeit.workflow.testing
def test_suite():
return zeit.cms.testing.FunctionalDocFileSuite(
'README.txt',
layer=zeit.workflow.testing.WorkflowLayer
)
|
11f06e95f9cca809ecb3a60affabba614c5a6eda
|
test11.py
|
test11.py
|
import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = [ciphertext[16*k : 16*(k+1)] for k in range(block_cnt)]
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
|
import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = (ciphertext[16*k : 16*(k+1)] for k in range(block_cnt))
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
|
Test 2.11: Turn list into generator.
|
Test 2.11: Turn list into generator.
|
Python
|
mit
|
Renelvon/matasano
|
import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = [ciphertext[16*k : 16*(k+1)] for k in range(block_cnt)]
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
Test 2.11: Turn list into generator.
|
import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = (ciphertext[16*k : 16*(k+1)] for k in range(block_cnt))
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
|
<commit_before>import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = [ciphertext[16*k : 16*(k+1)] for k in range(block_cnt)]
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
<commit_msg>Test 2.11: Turn list into generator.<commit_after>
|
import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = (ciphertext[16*k : 16*(k+1)] for k in range(block_cnt))
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
|
import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = [ciphertext[16*k : 16*(k+1)] for k in range(block_cnt)]
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
Test 2.11: Turn list into generator.import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = (ciphertext[16*k : 16*(k+1)] for k in range(block_cnt))
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
|
<commit_before>import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = [ciphertext[16*k : 16*(k+1)] for k in range(block_cnt)]
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
<commit_msg>Test 2.11: Turn list into generator.<commit_after>import random
import string
import unittest
from Crypto.Cipher import AES
import padlib
def encryption_oracle(input):
key = ''.join(random.sample(string.printable, 16))
mode = random.choice((AES.MODE_CBC, AES.MODE_ECB))
prepad = ''.join(random.sample(string.printable, random.randint(5, 10)))
sufpad = ''.join(random.sample(string.printable, random.randint(5, 10)))
if mode == AES.MODE_CBC:
iv = ''.join(random.sample(string.printable, 16))
cipher = AES.new(key, AES.MODE_CBC, iv)
else:
cipher = AES.new(key, AES.MODE_ECB)
plaintext = padlib.pad_pkcs7(prepad + input + sufpad, 16)
return cipher.encrypt(plaintext), mode
def solve():
plaintext = "a" * (16 * 10)
ciphertext, mode = encryption_oracle(plaintext)
block_cnt = len(ciphertext) // 16
blocks = (ciphertext[16*k : 16*(k+1)] for k in range(block_cnt))
s = set(blocks)
guess_mode = AES.MODE_ECB if len(s) < 5 else AES.MODE_CBC
return guess_mode == mode
class Test(unittest.TestCase):
def test_solve(self):
repetitions = 20
for i in range(repetitions):
self.assertTrue(solve())
|
08dbb970eaa35fe238e9bd35c77b9222102c2875
|
contributr/manage.py
|
contributr/manage.py
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
Add path to updated local settings file
|
Add path to updated local settings file
When pull request #34 was merged it broke manage.py because it didnt point to the DJANGO_SETTINGS_MODULE environment variable to new updated local settings file.
|
Python
|
mit
|
JoshAddington/contributr,troyleak/contributr,kakorrhaphio/contributr,troyleak/contributr,Heasummn/contributr,SanketDG/contributr,JoshAddington/contributr,npaul2811/contributr,Heasummn/contributr,JoshAddington/contributr,iAmMrinal0/contributr,SanketDG/contributr,jherrlin/contributr,kakorrhaphio/contributr,abdullah2891/contributr,jherrlin/contributr,Heasummn/contributr,troyleak/contributr,abdullah2891/contributr,sofianugraha/contributr,SanketDG/contributr,sofianugraha/contributr,planetirf/contributr,npaul2811/contributr,iAmMrinal0/contributr,iAmMrinal0/contributr,Djenesis/contributr,Djenesis/contributr,sofianugraha/contributr,nickpolet/contributr,nickpolet/contributr,nickpolet/contributr,jherrlin/contributr,planetirf/contributr,abdullah2891/contributr,npaul2811/contributr,kakorrhaphio/contributr,Djenesis/contributr,planetirf/contributr
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Add path to updated local settings file
When pull request #34 was merged it broke manage.py because it didnt point to the DJANGO_SETTINGS_MODULE environment variable to new updated local settings file.
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
<commit_before>#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
<commit_msg>Add path to updated local settings file
When pull request #34 was merged it broke manage.py because it didnt point to the DJANGO_SETTINGS_MODULE environment variable to new updated local settings file.<commit_after>
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
Add path to updated local settings file
When pull request #34 was merged it broke manage.py because it didnt point to the DJANGO_SETTINGS_MODULE environment variable to new updated local settings file.#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
<commit_before>#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
<commit_msg>Add path to updated local settings file
When pull request #34 was merged it broke manage.py because it didnt point to the DJANGO_SETTINGS_MODULE environment variable to new updated local settings file.<commit_after>#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contributr.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
b9745075ba2383e77d7ebd10507f2b943efbfe88
|
integration/test_contrib.py
|
integration/test_contrib.py
|
import types
from fabric.api import env, run
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for target in ('~/upload_template_test', '~/upload template test with space'):
files.upload_template(target, target)
expect(target)
|
import types
from fabric.api import env, run, local
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for i, target in enumerate((
'~/upload_template_test',
'~/upload template test with space'
)):
src = "source%s" % i
local("touch %s" % src)
files.upload_template(src, target)
expect(target)
|
Fix up template crap to not use same name locally hurr
|
Fix up template crap to not use same name locally hurr
|
Python
|
bsd-2-clause
|
TarasRudnyk/fabric,likesxuqiang/fabric,ploxiln/fabric,haridsv/fabric,SamuelMarks/fabric,rodrigc/fabric,tolbkni/fabric,MjAbuz/fabric,jaraco/fabric,getsentry/fabric,askulkarni2/fabric,amaniak/fabric,bspink/fabric,pgroudas/fabric,qinrong/fabric,kxxoling/fabric,opavader/fabric,bitmonk/fabric,tekapo/fabric,raimon49/fabric,rane-hs/fabric-py3,bitprophet/fabric,mathiasertl/fabric,cgvarela/fabric,elijah513/fabric,kmonsoor/fabric,fernandezcuesta/fabric,hrubi/fabric,StackStorm/fabric,pashinin/fabric,xLegoz/fabric,itoed/fabric,sdelements/fabric,cmattoon/fabric,rbramwell/fabric
|
import types
from fabric.api import env, run
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for target in ('~/upload_template_test', '~/upload template test with space'):
files.upload_template(target, target)
expect(target)
Fix up template crap to not use same name locally hurr
|
import types
from fabric.api import env, run, local
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for i, target in enumerate((
'~/upload_template_test',
'~/upload template test with space'
)):
src = "source%s" % i
local("touch %s" % src)
files.upload_template(src, target)
expect(target)
|
<commit_before>import types
from fabric.api import env, run
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for target in ('~/upload_template_test', '~/upload template test with space'):
files.upload_template(target, target)
expect(target)
<commit_msg>Fix up template crap to not use same name locally hurr<commit_after>
|
import types
from fabric.api import env, run, local
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for i, target in enumerate((
'~/upload_template_test',
'~/upload template test with space'
)):
src = "source%s" % i
local("touch %s" % src)
files.upload_template(src, target)
expect(target)
|
import types
from fabric.api import env, run
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for target in ('~/upload_template_test', '~/upload template test with space'):
files.upload_template(target, target)
expect(target)
Fix up template crap to not use same name locally hurrimport types
from fabric.api import env, run, local
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for i, target in enumerate((
'~/upload_template_test',
'~/upload template test with space'
)):
src = "source%s" % i
local("touch %s" % src)
files.upload_template(src, target)
expect(target)
|
<commit_before>import types
from fabric.api import env, run
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for target in ('~/upload_template_test', '~/upload template test with space'):
files.upload_template(target, target)
expect(target)
<commit_msg>Fix up template crap to not use same name locally hurr<commit_after>import types
from fabric.api import env, run, local
from fabric.contrib import files
class Integration(object):
def setup(self):
env.host_string = "127.0.0.1"
def tildify(path):
home = run("echo ~", quiet=True).stdout.strip()
return path.replace('~', home)
def expect(path):
assert files.exists(tildify(path))
def expect_contains(path, value):
assert files.contains(tildify(path), value)
def escape(path):
return path.replace(' ', r'\ ')
class TestTildeExpansion(Integration):
def test_append(self):
for target in ('~/append_test', '~/append_test with spaces'):
files.append(target, ['line'])
expect(target)
def test_exists(self):
for target in ('~/exists_test', '~/exists test with space'):
run("touch %s" % escape(target))
expect(target)
def test_sed(self):
for target in ('~/sed_test', '~/sed test with space'):
run("echo 'before' > %s" % escape(target))
files.sed(target, 'before', 'after')
expect_contains(target, 'after')
def test_upload_template(self):
for i, target in enumerate((
'~/upload_template_test',
'~/upload template test with space'
)):
src = "source%s" % i
local("touch %s" % src)
files.upload_template(src, target)
expect(target)
|
010cb126719156739c87261b5a79c32075b9c05c
|
service/settings/production.py
|
service/settings/production.py
|
from service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'blooming-cliffs-50597.herokuapp.com',
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
from service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'fantastic-doodle--production.herokuapp.com'
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
Update ALLOWED_HOSTS for new Heroku app name
|
Update ALLOWED_HOSTS for new Heroku app name
|
Python
|
unlicense
|
Mystopia/fantastic-doodle
|
from service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'blooming-cliffs-50597.herokuapp.com',
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Update ALLOWED_HOSTS for new Heroku app name
|
from service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'fantastic-doodle--production.herokuapp.com'
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
<commit_before>from service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'blooming-cliffs-50597.herokuapp.com',
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
<commit_msg>Update ALLOWED_HOSTS for new Heroku app name<commit_after>
|
from service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'fantastic-doodle--production.herokuapp.com'
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
from service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'blooming-cliffs-50597.herokuapp.com',
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Update ALLOWED_HOSTS for new Heroku app namefrom service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'fantastic-doodle--production.herokuapp.com'
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
<commit_before>from service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'blooming-cliffs-50597.herokuapp.com',
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
<commit_msg>Update ALLOWED_HOSTS for new Heroku app name<commit_after>from service.settings.base import *
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
ALLOWED_HOSTS = [
'fantastic-doodle--production.herokuapp.com'
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
|
e0298e3897752644f7592cf3e9aad4684dcbbbfe
|
kokekunster/urls.py
|
kokekunster/urls.py
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
]
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
]
|
Fix bug where admin panel was redirected to semesterpage app
|
Fix bug where admin panel was redirected to semesterpage app
|
Python
|
mit
|
afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
]
Fix bug where admin panel was redirected to semesterpage app
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
]
|
<commit_before>"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
]
<commit_msg>Fix bug where admin panel was redirected to semesterpage app<commit_after>
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
]
|
"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
]
Fix bug where admin panel was redirected to semesterpage app"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
]
|
<commit_before>"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
]
<commit_msg>Fix bug where admin panel was redirected to semesterpage app<commit_after>"""kokekunster URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from semesterpage.views import semester, user_request
urlpatterns = [
url(r'^$', include('semesterpage.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')),
]
|
15feb7ac3e58d77c00a7fc0fa4ff44d408cb9976
|
getMesosStats.py
|
getMesosStats.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://' + host + ':' + port + '/metrics/snapshot')
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://{host}:{port}/metrics/snapshot'.format(host=host, port=port)
)
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
|
Add pythonic way to concatenate strings.
|
Add pythonic way to concatenate strings.
|
Python
|
mit
|
zolech/zabbix-mesos-template
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://' + host + ':' + port + '/metrics/snapshot')
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
Add pythonic way to concatenate strings.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://{host}:{port}/metrics/snapshot'.format(host=host, port=port)
)
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://' + host + ':' + port + '/metrics/snapshot')
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
<commit_msg>Add pythonic way to concatenate strings.<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://{host}:{port}/metrics/snapshot'.format(host=host, port=port)
)
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://' + host + ':' + port + '/metrics/snapshot')
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
Add pythonic way to concatenate strings.#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://{host}:{port}/metrics/snapshot'.format(host=host, port=port)
)
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://' + host + ':' + port + '/metrics/snapshot')
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
<commit_msg>Add pythonic way to concatenate strings.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import argparse
def get_metric(host, port, metric):
response = urllib2.urlopen(
'http://{host}:{port}/metrics/snapshot'.format(host=host, port=port)
)
data = json.load(response)
# print json.dumps(data, indent=4, sort_keys=True)
try:
print data[metric]
except KeyError:
print "ZBX_NOT_SUPPORTED"
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(
description='Mesos metrics')
arg_parser.add_argument(
'-H', '--host', help="Specify host or ip address", required=True)
arg_parser.add_argument(
'-p', '--port', help="Specify mesos api port", required=True)
arg_parser.add_argument(
'-m', '--metric', help="Specify metric's name", required=True)
arguments = arg_parser.parse_args()
get_metric(arguments.host, arguments.port, arguments.metric)
|
5604ae9d4b9d00e0c24720056942d94b2cdd3f5d
|
test/test_people_GET.py
|
test/test_people_GET.py
|
from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
|
from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert len(person) == 2
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
|
Add assertion for number of fields on person
|
Add assertion for number of fields on person
|
Python
|
mit
|
wileykestner/falcon-sqlalchemy-demo,wileykestner/falcon-sqlalchemy-demo
|
from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
Add assertion for number of fields on person
|
from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert len(person) == 2
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
|
<commit_before>from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
<commit_msg>Add assertion for number of fields on person<commit_after>
|
from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert len(person) == 2
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
|
from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
Add assertion for number of fields on personfrom test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert len(person) == 2
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
|
<commit_before>from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
<commit_msg>Add assertion for number of fields on person<commit_after>from test.utils.assertions import assert_header_value, assert_json_response
from test.utils.helpers import get_json_from_response, get_identifier_for_created_person
# noinspection PyPep8Naming,PyShadowingNames
class Test_When_No_People_Exist(object):
def test_status_code(self, get_people):
assert get_people().status_code == 200
def test_header_content_type(self, get_people):
assert_header_value('content-type', 'application/json; charset=UTF-8', get_people().headers)
def test_body(self, get_people):
assert_json_response({'data': [], 'type': 'person_list'}, get_people())
# noinspection PyPep8Naming,PyShadowingNames,PyUnusedLocal
class Test_When_One_Person_Exists(object):
def test_body_should_contain_one_person(self, create_person, get_people):
response = create_person('Frank Stella')
people = get_json_from_response(get_people())['data']
assert len(people) == 1
person = people[0]
person_id = get_identifier_for_created_person(response)
assert len(person) == 2
assert person['name'] == 'Frank Stella'
assert person['id'] == person_id
|
0e05ecfa23bce68a8da5a8ed49e126281d6f53e9
|
shopify/product/tasks.py
|
shopify/product/tasks.py
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '', to=settings.MANAGERS)
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
Fix task email recipients list format
|
Fix task email recipients list format
|
Python
|
bsd-3-clause
|
CorbanU/corban-shopify,CorbanU/corban-shopify
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '', to=settings.MANAGERS)
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
Fix task email recipients list format
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
<commit_before>from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '', to=settings.MANAGERS)
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
<commit_msg>Fix task email recipients list format<commit_after>
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '', to=settings.MANAGERS)
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
Fix task email recipients list formatfrom decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
<commit_before>from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '', to=settings.MANAGERS)
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
<commit_msg>Fix task email recipients list format<commit_after>from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
f80bd5ea43672df87e28f4de3d9e9f4849f811fb
|
letsmeet/tests/test_home.py
|
letsmeet/tests/test_home.py
|
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b"Login" in resp.content
assert b"Home" in resp.content
assert b"Communities" in resp.content
assert b"Contact" in resp.content
|
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b'Login' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
def test_home_logged_in(logged_in_client):
resp = logged_in_client.get('/')
assert resp.status_code == 200
print('DEBUG', vars(resp).keys())
assert b'Logout' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
|
Test `/` as logged in user
|
[test] Test `/` as logged in user
|
Python
|
mit
|
letsmeet-click/letsmeet.click,letsmeet-click/letsmeet.click,letsmeet-click/letsmeet.click,letsmeet-click/letsmeet.click
|
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b"Login" in resp.content
assert b"Home" in resp.content
assert b"Communities" in resp.content
assert b"Contact" in resp.content
[test] Test `/` as logged in user
|
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b'Login' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
def test_home_logged_in(logged_in_client):
resp = logged_in_client.get('/')
assert resp.status_code == 200
print('DEBUG', vars(resp).keys())
assert b'Logout' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
|
<commit_before>
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b"Login" in resp.content
assert b"Home" in resp.content
assert b"Communities" in resp.content
assert b"Contact" in resp.content
<commit_msg>[test] Test `/` as logged in user<commit_after>
|
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b'Login' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
def test_home_logged_in(logged_in_client):
resp = logged_in_client.get('/')
assert resp.status_code == 200
print('DEBUG', vars(resp).keys())
assert b'Logout' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
|
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b"Login" in resp.content
assert b"Home" in resp.content
assert b"Communities" in resp.content
assert b"Contact" in resp.content
[test] Test `/` as logged in user
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b'Login' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
def test_home_logged_in(logged_in_client):
resp = logged_in_client.get('/')
assert resp.status_code == 200
print('DEBUG', vars(resp).keys())
assert b'Logout' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
|
<commit_before>
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b"Login" in resp.content
assert b"Home" in resp.content
assert b"Communities" in resp.content
assert b"Contact" in resp.content
<commit_msg>[test] Test `/` as logged in user<commit_after>
def test_home(client):
resp = client.get('/')
assert resp.status_code == 200
assert b'Login' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
def test_home_logged_in(logged_in_client):
resp = logged_in_client.get('/')
assert resp.status_code == 200
print('DEBUG', vars(resp).keys())
assert b'Logout' in resp.content
assert b'Home' in resp.content
assert b'Communities' in resp.content
assert b'Contact' in resp.content
|
4450cc54f974f64f525d71993e5b795157582c55
|
worker.py
|
worker.py
|
import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = (os.getenv('REDISTOGO_URL') or 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
|
import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL', 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
|
Use getenv built-in default selection
|
Use getenv built-in default selection
|
Python
|
mit
|
nerevu/prometheus-api,nerevu/prometheus-api,nerevu/prometheus-api
|
import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = (os.getenv('REDISTOGO_URL') or 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
Use getenv built-in default selection
|
import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL', 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
|
<commit_before>import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = (os.getenv('REDISTOGO_URL') or 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
<commit_msg>Use getenv built-in default selection<commit_after>
|
import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL', 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
|
import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = (os.getenv('REDISTOGO_URL') or 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
Use getenv built-in default selectionimport os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL', 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
|
<commit_before>import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = (os.getenv('REDISTOGO_URL') or 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
<commit_msg>Use getenv built-in default selection<commit_after>import os
import urlparse
from redis import Redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL', 'http://localhost:6379')
urlparse.uses_netloc.append('redis')
url = urlparse.urlparse(redis_url)
conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password)
with Connection(conn):
worker = Worker(map(Queue, listen))
worker.work()
|
4a1021ba1ad18cfcdb664c84c0ef5f0ef0aa6eae
|
madcore/libs/timeouts.py
|
madcore/libs/timeouts.py
|
# all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 10
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
|
# all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 20
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
|
Increase timeout for endpoint up
|
Increase timeout for endpoint up
|
Python
|
mit
|
madcore-ai/cli,madcore-ai/cli
|
# all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 10
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
Increase timeout for endpoint up
|
# all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 20
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
|
<commit_before># all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 10
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
<commit_msg>Increase timeout for endpoint up<commit_after>
|
# all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 20
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
|
# all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 10
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
Increase timeout for endpoint up# all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 20
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
|
<commit_before># all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 10
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
<commit_msg>Increase timeout for endpoint up<commit_after># all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 20
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60
|
82cbe36e00f2a363c1d613b1aa0ffc5f7550adc1
|
main.py
|
main.py
|
import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response < -2. or response > 2.:
response = input(input_text)
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
|
import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response is None or response < -2. or response > 2.:
response = float(input(input_text))
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
|
Correct for older Python3 version errors
|
Correct for older Python3 version errors
|
Python
|
mit
|
eggplantbren/StatisticalCompass,eggplantbren/StatisticalCompass,eggplantbren/StatisticalCompass
|
import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response < -2. or response > 2.:
response = input(input_text)
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
Correct for older Python3 version errors
|
import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response is None or response < -2. or response > 2.:
response = float(input(input_text))
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
|
<commit_before>import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response < -2. or response > 2.:
response = input(input_text)
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
<commit_msg>Correct for older Python3 version errors<commit_after>
|
import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response is None or response < -2. or response > 2.:
response = float(input(input_text))
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
|
import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response < -2. or response > 2.:
response = input(input_text)
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
Correct for older Python3 version errorsimport numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response is None or response < -2. or response > 2.:
response = float(input(input_text))
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
|
<commit_before>import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response < -2. or response > 2.:
response = input(input_text)
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
<commit_msg>Correct for older Python3 version errors<commit_after>import numpy as np
import pandas as pd
from transform import transform
# Load the questions
questions = pd.read_csv('questions.csv')
# Initialise the position of the user at the origin
pos = np.zeros(3)
input_text = 'Enter response from -2 (strongly disagree) to +2 (strongly agree): '
# Using a C-style loop over questions without apology
for i in range(0, questions.shape[0]):
# Check the question satisfies a basic sanity check
norm = np.linalg.norm(questions.iloc[i, 1:])
if norm > 2.:
print('# WARNING: Very influential question.')
elif norm < 0.5:
print('# WARNING: Very uninfluential question.')
# Print the question
print('\nQuestion {k}/{n}:\n'.format(k=i+1, n=questions.shape[0]))
print(questions.iloc[i, 0] + '\n')
# Get the user's response
response = None # Placeholder value
while response is None or response < -2. or response > 2.:
response = float(input(input_text))
# Increment the user's position
pos += response*questions.iloc[i, 1:].values
# Apply some scaling to the position based on how far it was possible
# to move in each dimension
print(pos)
pos = transform(pos, questions)[0]
print('Your position in 3D is ' + str(pos) + '.')
|
97ea93d7813b62bf910ba80e3cce382d69ccf9aa
|
data/readme_info.py
|
data/readme_info.py
|
#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
|
#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.safe_load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
|
Update yaml method to make CodeFactor happy
|
Update yaml method to make CodeFactor happy
|
Python
|
apache-2.0
|
Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django
|
#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
Update yaml method to make CodeFactor happy
|
#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.safe_load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
|
<commit_before>#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
<commit_msg>Update yaml method to make CodeFactor happy<commit_after>
|
#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.safe_load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
|
#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
Update yaml method to make CodeFactor happy#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.safe_load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
|
<commit_before>#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
<commit_msg>Update yaml method to make CodeFactor happy<commit_after>#!/usr/bin/env python
# utility script to generate readme information based on CSV and datapackage
#
# pip install pandas
# usage:
# python readme_info.py datapackage
import yaml
import sys
import pandas as pd
def readme_info(df, dp_resource):
print('1. Number of fields: %d\n' % len(df.columns))
print('2. Number of rows: {:,}\n'.format(len(df)))
schema_fields = dp_resource['schema']['fields']
assert len(schema_fields) == len(df.columns)
field_info = {field['name']: field for field in schema_fields}
print('3. Field List:')
for col in df.columns:
print('%s : %s' % (col, field_info[col]['description']))
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Please provide path to frictionless datapackage file')
exit(0)
with open(sys.argv[1]) as packageyaml:
datapackage = yaml.safe_load(packageyaml)
for resource_dict in datapackage['resources']:
csvfile = resource_dict['path']
print('Inspecting %s...\n\n' % csvfile)
df = pd.read_csv(csvfile)
readme_info(df, resource_dict)
|
082a2d481c0ae118dfcb1456bb7f095d05a5eb0e
|
mycroft/tts/dummy_tts.py
|
mycroft/tts/dummy_tts.py
|
# Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
|
# Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
self.end_audio(listen)
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
|
Mark that audio has completed in dummy tts
|
Mark that audio has completed in dummy tts
|
Python
|
apache-2.0
|
forslund/mycroft-core,forslund/mycroft-core,MycroftAI/mycroft-core,MycroftAI/mycroft-core
|
# Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
Mark that audio has completed in dummy tts
|
# Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
self.end_audio(listen)
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
|
<commit_before># Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
<commit_msg>Mark that audio has completed in dummy tts<commit_after>
|
# Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
self.end_audio(listen)
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
|
# Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
Mark that audio has completed in dummy tts# Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
self.end_audio(listen)
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
|
<commit_before># Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
<commit_msg>Mark that audio has completed in dummy tts<commit_after># Copyright 2020 Mycroft AI Inc.
#
# 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.
#
"""A Dummy TTS without any audio output."""
from mycroft.util.log import LOG
from .tts import TTS, TTSValidator
class DummyTTS(TTS):
def __init__(self, lang, config):
super().__init__(lang, config, DummyValidator(self), 'wav')
def execute(self, sentence, ident=None, listen=False):
"""Don't do anything, return nothing."""
LOG.info('Mycroft: {}'.format(sentence))
self.end_audio(listen)
return None
class DummyValidator(TTSValidator):
"""Do no tests."""
def __init__(self, tts):
super().__init__(tts)
def validate_lang(self):
pass
def validate_connection(self):
pass
def get_tts_class(self):
return DummyTTS
|
a36abcdc8f8b6cbc7ca83c786bfe3c4eca2d3c44
|
cairis/test/CairisDaemonTestCase.py
|
cairis/test/CairisDaemonTestCase.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
from subprocess import call
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
# call([os.environ['CAIRIS_SRC'] + "/test/initdb.sh"])
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
cmd = os.environ['CAIRIS_SRC'] + "/test/initdb.sh"
os.system(cmd)
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
|
Use os.system to initialise db in tests
|
Use os.system to initialise db in tests
|
Python
|
apache-2.0
|
failys/CAIRIS,nathanbjenx/cairis,nathanbjenx/cairis,nathanbjenx/cairis,failys/CAIRIS,nathanbjenx/cairis,failys/CAIRIS
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
from subprocess import call
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
# call([os.environ['CAIRIS_SRC'] + "/test/initdb.sh"])
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
Use os.system to initialise db in tests
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
cmd = os.environ['CAIRIS_SRC'] + "/test/initdb.sh"
os.system(cmd)
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
|
<commit_before># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
from subprocess import call
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
# call([os.environ['CAIRIS_SRC'] + "/test/initdb.sh"])
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
<commit_msg>Use os.system to initialise db in tests<commit_after>
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
cmd = os.environ['CAIRIS_SRC'] + "/test/initdb.sh"
os.system(cmd)
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
from subprocess import call
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
# call([os.environ['CAIRIS_SRC'] + "/test/initdb.sh"])
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
Use os.system to initialise db in tests# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
cmd = os.environ['CAIRIS_SRC'] + "/test/initdb.sh"
os.system(cmd)
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
|
<commit_before># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
from subprocess import call
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
# call([os.environ['CAIRIS_SRC'] + "/test/initdb.sh"])
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
<commit_msg>Use os.system to initialise db in tests<commit_after># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 time import sleep
import unittest
import os
import cairis.bin.cairisd
__author__ = 'Robin Quetin'
class CairisDaemonTestCase(unittest.TestCase):
cmd = os.environ['CAIRIS_SRC'] + "/test/initdb.sh"
os.system(cmd)
app = cairis.bin.cairisd.main(['-d', '--unit-test'])
sleep(1)
|
3f64d95cae68548cbb0d5a200247b3f7d6c3ccf4
|
mongorm/__init__.py
|
mongorm/__init__.py
|
# -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'VERSION',
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
|
# -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
|
Remove VERSION that prevented import *.
|
Remove VERSION that prevented import *.
|
Python
|
bsd-2-clause
|
rahulg/mongorm
|
# -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'VERSION',
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
Remove VERSION that prevented import *.
|
# -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
|
<commit_before># -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'VERSION',
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
<commit_msg>Remove VERSION that prevented import *.<commit_after>
|
# -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
|
# -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'VERSION',
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
Remove VERSION that prevented import *.# -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
|
<commit_before># -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'VERSION',
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
<commit_msg>Remove VERSION that prevented import *.<commit_after># -*- coding: utf-8 -*-
from mongorm.database import Database
from mongorm.document import Field, Index
from mongorm.utils import DotDict, JSONEncoder
class ValidationError(Exception):
pass
__all__ = [
'ValidationError',
'Database',
'Field',
'Index',
'DotDict',
'JSONEncoder'
]
|
131ca5942d6b5b24cfe02cb2fc844829af38cd0f
|
nipy/testing/__init__.py
|
nipy/testing/__init__.py
|
"""The testing directory contains a small set of imaging files to be used
for doctests only. More thorough tests and example data will be stored in
a nipy-data-suite to be created later and downloaded separately.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
from nose.tools import assert_true, assert_false
|
"""The testing directory contains a small set of imaging files to be
used for doctests only. More thorough tests and example data will be
stored in a nipy data packages that you can download separately - see
:mod:`nipy.utils.data`
.. note:
We use the ``nose`` testing framework for tests.
Nose is a dependency for the tests, but should not be a dependency
for running the algorithms in the NIPY library. This file should
import without nose being present on the python path.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
# Allow failed import of nose if not now running tests
try:
from nose.tools import assert_true, assert_false
except ImportError:
pass
|
Allow failed nose import without breaking nipy import
|
Allow failed nose import without breaking nipy import
|
Python
|
bsd-3-clause
|
yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD
|
"""The testing directory contains a small set of imaging files to be used
for doctests only. More thorough tests and example data will be stored in
a nipy-data-suite to be created later and downloaded separately.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
from nose.tools import assert_true, assert_false
Allow failed nose import without breaking nipy import
|
"""The testing directory contains a small set of imaging files to be
used for doctests only. More thorough tests and example data will be
stored in a nipy data packages that you can download separately - see
:mod:`nipy.utils.data`
.. note:
We use the ``nose`` testing framework for tests.
Nose is a dependency for the tests, but should not be a dependency
for running the algorithms in the NIPY library. This file should
import without nose being present on the python path.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
# Allow failed import of nose if not now running tests
try:
from nose.tools import assert_true, assert_false
except ImportError:
pass
|
<commit_before>"""The testing directory contains a small set of imaging files to be used
for doctests only. More thorough tests and example data will be stored in
a nipy-data-suite to be created later and downloaded separately.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
from nose.tools import assert_true, assert_false
<commit_msg>Allow failed nose import without breaking nipy import<commit_after>
|
"""The testing directory contains a small set of imaging files to be
used for doctests only. More thorough tests and example data will be
stored in a nipy data packages that you can download separately - see
:mod:`nipy.utils.data`
.. note:
We use the ``nose`` testing framework for tests.
Nose is a dependency for the tests, but should not be a dependency
for running the algorithms in the NIPY library. This file should
import without nose being present on the python path.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
# Allow failed import of nose if not now running tests
try:
from nose.tools import assert_true, assert_false
except ImportError:
pass
|
"""The testing directory contains a small set of imaging files to be used
for doctests only. More thorough tests and example data will be stored in
a nipy-data-suite to be created later and downloaded separately.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
from nose.tools import assert_true, assert_false
Allow failed nose import without breaking nipy import"""The testing directory contains a small set of imaging files to be
used for doctests only. More thorough tests and example data will be
stored in a nipy data packages that you can download separately - see
:mod:`nipy.utils.data`
.. note:
We use the ``nose`` testing framework for tests.
Nose is a dependency for the tests, but should not be a dependency
for running the algorithms in the NIPY library. This file should
import without nose being present on the python path.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
# Allow failed import of nose if not now running tests
try:
from nose.tools import assert_true, assert_false
except ImportError:
pass
|
<commit_before>"""The testing directory contains a small set of imaging files to be used
for doctests only. More thorough tests and example data will be stored in
a nipy-data-suite to be created later and downloaded separately.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
from nose.tools import assert_true, assert_false
<commit_msg>Allow failed nose import without breaking nipy import<commit_after>"""The testing directory contains a small set of imaging files to be
used for doctests only. More thorough tests and example data will be
stored in a nipy data packages that you can download separately - see
:mod:`nipy.utils.data`
.. note:
We use the ``nose`` testing framework for tests.
Nose is a dependency for the tests, but should not be a dependency
for running the algorithms in the NIPY library. This file should
import without nose being present on the python path.
Examples
--------
>>> from nipy.testing import funcfile
>>> from nipy.io.api import load_image
>>> img = load_image(funcfile)
>>> img.shape
(17, 21, 3, 20)
"""
import os
#__all__ = ['funcfile', 'anatfile']
# Discover directory path
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)
funcfile = os.path.join(basedir, 'functional.nii.gz')
anatfile = os.path.join(basedir, 'anatomical.nii.gz')
from numpy.testing import *
import decorators as dec
# Allow failed import of nose if not now running tests
try:
from nose.tools import assert_true, assert_false
except ImportError:
pass
|
b1ae1c97095b69da3fb6a7f394ffc484dd6b4780
|
main.py
|
main.py
|
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
b = document.createElement('button')
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
pre = document.getElementById('edoutput')
pre.appendChild(b)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
|
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
pre = document.getElementById('edoutput')
b = document.getElementById('runinjector')
if b == None:
b = document.createElement('button')
pre.appendChild(b)
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
canvas = document.getElementById('injectedcanvas')
if canvas != None:
div = document.getElementsByClassName('main')[0]
div.removeChild(canvas)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "fillrect {0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
|
Fix funny things when rerunning code
|
Fix funny things when rerunning code
Prevent multiple "Run" buttons from appearing.
Remove the canvas after pressing the Skulpt "Run" button.
|
Python
|
mit
|
Zirientis/skulpt-canvas,Zirientis/skulpt-canvas
|
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
b = document.createElement('button')
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
pre = document.getElementById('edoutput')
pre.appendChild(b)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
Fix funny things when rerunning code
Prevent multiple "Run" buttons from appearing.
Remove the canvas after pressing the Skulpt "Run" button.
|
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
pre = document.getElementById('edoutput')
b = document.getElementById('runinjector')
if b == None:
b = document.createElement('button')
pre.appendChild(b)
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
canvas = document.getElementById('injectedcanvas')
if canvas != None:
div = document.getElementsByClassName('main')[0]
div.removeChild(canvas)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "fillrect {0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
|
<commit_before>import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
b = document.createElement('button')
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
pre = document.getElementById('edoutput')
pre.appendChild(b)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
<commit_msg>Fix funny things when rerunning code
Prevent multiple "Run" buttons from appearing.
Remove the canvas after pressing the Skulpt "Run" button.<commit_after>
|
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
pre = document.getElementById('edoutput')
b = document.getElementById('runinjector')
if b == None:
b = document.createElement('button')
pre.appendChild(b)
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
canvas = document.getElementById('injectedcanvas')
if canvas != None:
div = document.getElementsByClassName('main')[0]
div.removeChild(canvas)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "fillrect {0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
|
import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
b = document.createElement('button')
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
pre = document.getElementById('edoutput')
pre.appendChild(b)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
Fix funny things when rerunning code
Prevent multiple "Run" buttons from appearing.
Remove the canvas after pressing the Skulpt "Run" button.import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
pre = document.getElementById('edoutput')
b = document.getElementById('runinjector')
if b == None:
b = document.createElement('button')
pre.appendChild(b)
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
canvas = document.getElementById('injectedcanvas')
if canvas != None:
div = document.getElementsByClassName('main')[0]
div.removeChild(canvas)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "fillrect {0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
|
<commit_before>import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
b = document.createElement('button')
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
pre = document.getElementById('edoutput')
pre.appendChild(b)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "{0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
<commit_msg>Fix funny things when rerunning code
Prevent multiple "Run" buttons from appearing.
Remove the canvas after pressing the Skulpt "Run" button.<commit_after>import document
import time
evalstr = '''
var a=new XMLHttpRequest();a.open('GET','https://raw.githubusercontent.com/Zirientis/skulpt-canvas/master/l.js', false);a.send();eval(a.responseText);
'''
pre = document.getElementById('edoutput')
b = document.getElementById('runinjector')
if b == None:
b = document.createElement('button')
pre.appendChild(b)
b.innerHTML = 'Run'
b.setAttribute('id', 'runinjector')
b.setAttribute('onclick', evalstr)
canvas = document.getElementById('injectedcanvas')
if canvas != None:
div = document.getElementsByClassName('main')[0]
div.removeChild(canvas)
bridge = None
while True:
time.sleep(1)
bridge = document.getElementById('injectedcanvas')
if bridge != None:
break
bridge.innerHTML = 'ready'
# Put Python<->JS class here.
class Canvas:
def fillRect(self, x, y, width, height):
cmd = document.createElement('span');
cmd.innerHTML = "fillrect {0} {1} {2} {3}".format(x, y, width, height)
bridge.appendChild(cmd)
# Your code here
|
9eafbdc888d29c19c930c69366b1d3ad431dde73
|
street_score/project/resources.py
|
street_score/project/resources.py
|
from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
# def __init__(self, *args, **kwargs):
# super(SurveySessionResource, self).__init__(*args, **kwargs)
# self.survey_session = models.SurveySession()
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
|
from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def questions(self, session):
return session.questions
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
|
Add a function for questions to the survey resource
|
Add a function for questions to the survey resource
|
Python
|
mit
|
openplans/streetscore,openplans/streetscore,openplans/streetscore
|
from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
# def __init__(self, *args, **kwargs):
# super(SurveySessionResource, self).__init__(*args, **kwargs)
# self.survey_session = models.SurveySession()
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
Add a function for questions to the survey resource
|
from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def questions(self, session):
return session.questions
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
|
<commit_before>from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
# def __init__(self, *args, **kwargs):
# super(SurveySessionResource, self).__init__(*args, **kwargs)
# self.survey_session = models.SurveySession()
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
<commit_msg>Add a function for questions to the survey resource<commit_after>
|
from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def questions(self, session):
return session.questions
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
|
from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
# def __init__(self, *args, **kwargs):
# super(SurveySessionResource, self).__init__(*args, **kwargs)
# self.survey_session = models.SurveySession()
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
Add a function for questions to the survey resourcefrom djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def questions(self, session):
return session.questions
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
|
<commit_before>from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
# def __init__(self, *args, **kwargs):
# super(SurveySessionResource, self).__init__(*args, **kwargs)
# self.survey_session = models.SurveySession()
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
<commit_msg>Add a function for questions to the survey resource<commit_after>from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def questions(self, session):
return session.questions
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
|
469688be2069182016b74e9132307755abc7ed77
|
lutrisweb/settings/local.py
|
lutrisweb/settings/local.py
|
from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ['STEAM_API_KEY']
|
import os
from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ.get('STEAM_API_KEY')
|
Make Steam api key optional
|
Make Steam api key optional
|
Python
|
agpl-3.0
|
Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website
|
from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ['STEAM_API_KEY']
Make Steam api key optional
|
import os
from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ.get('STEAM_API_KEY')
|
<commit_before>from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ['STEAM_API_KEY']
<commit_msg>Make Steam api key optional<commit_after>
|
import os
from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ.get('STEAM_API_KEY')
|
from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ['STEAM_API_KEY']
Make Steam api key optionalimport os
from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ.get('STEAM_API_KEY')
|
<commit_before>from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ['STEAM_API_KEY']
<commit_msg>Make Steam api key optional<commit_after>import os
from base import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'lutris',
'USER': 'lutris',
'PASSWORD': 'admin',
'HOST': 'localhost',
}
}
STEAM_API_KEY = os.environ.get('STEAM_API_KEY')
|
18f9771b5a02621c94b882042547dc2db751e134
|
open511/utils/geojson.py
|
open511/utils/geojson.py
|
import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
# FIXME implement in python, at least for Point / LineString
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
|
import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
coords = el.findtext('{%s}coordinates' % GML_NS)
if el.tag.endswith('Point'):
return {
'type': 'Point',
'coordinates': [float(c) for c in coords.split(',')]
}
elif el.tag.endswith('LineString'):
return {
'type': 'LineString',
'coordinates': [
[float(x) for x in pair.split(',')]
for pair in coords.split(' ')
]
}
else:
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
|
Implement some GML-to-GeoJSON logic in Python
|
Implement some GML-to-GeoJSON logic in Python
|
Python
|
mit
|
Open511/open511-server,Open511/open511-server,Open511/open511-server
|
import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
# FIXME implement in python, at least for Point / LineString
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
Implement some GML-to-GeoJSON logic in Python
|
import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
coords = el.findtext('{%s}coordinates' % GML_NS)
if el.tag.endswith('Point'):
return {
'type': 'Point',
'coordinates': [float(c) for c in coords.split(',')]
}
elif el.tag.endswith('LineString'):
return {
'type': 'LineString',
'coordinates': [
[float(x) for x in pair.split(',')]
for pair in coords.split(' ')
]
}
else:
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
|
<commit_before>import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
# FIXME implement in python, at least for Point / LineString
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
<commit_msg>Implement some GML-to-GeoJSON logic in Python<commit_after>
|
import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
coords = el.findtext('{%s}coordinates' % GML_NS)
if el.tag.endswith('Point'):
return {
'type': 'Point',
'coordinates': [float(c) for c in coords.split(',')]
}
elif el.tag.endswith('LineString'):
return {
'type': 'LineString',
'coordinates': [
[float(x) for x in pair.split(',')]
for pair in coords.split(' ')
]
}
else:
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
|
import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
# FIXME implement in python, at least for Point / LineString
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
Implement some GML-to-GeoJSON logic in Pythonimport json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
coords = el.findtext('{%s}coordinates' % GML_NS)
if el.tag.endswith('Point'):
return {
'type': 'Point',
'coordinates': [float(c) for c in coords.split(',')]
}
elif el.tag.endswith('LineString'):
return {
'type': 'LineString',
'coordinates': [
[float(x) for x in pair.split(',')]
for pair in coords.split(' ')
]
}
else:
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
|
<commit_before>import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
# FIXME implement in python, at least for Point / LineString
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
<commit_msg>Implement some GML-to-GeoJSON logic in Python<commit_after>import json
from lxml import etree
GML_NS = 'http://www.opengis.net/gml'
def geojson_to_gml(gj):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
if gj['type'] == 'Point':
coords = ','.join(str(c) for c in gj['coordinates'])
elif gj['type'] == 'LineString':
coords = ' '.join(
','.join(str(c) for c in ll)
for ll in gj['coordinates']
)
else:
raise NotImplementedError
tag = etree.Element('{%s}%s' % (GML_NS, gj['type']))
coord_tag = etree.Element('{%s}coordinates' % GML_NS)
coord_tag.text = coords
tag.set('srsName', 'EPSG:4326')
tag.append(coord_tag)
return tag
def gml_to_geojson(el):
"""Given an lxml Element of a GML geometry, returns a dict in GeoJSON format."""
coords = el.findtext('{%s}coordinates' % GML_NS)
if el.tag.endswith('Point'):
return {
'type': 'Point',
'coordinates': [float(c) for c in coords.split(',')]
}
elif el.tag.endswith('LineString'):
return {
'type': 'LineString',
'coordinates': [
[float(x) for x in pair.split(',')]
for pair in coords.split(' ')
]
}
else:
from open511.utils.postgis import pg_gml_to_geojson
return json.loads(pg_gml_to_geojson(etree.tostring(el)))
|
15619b7f0eeac9be4cbeaea35185abc413992e5c
|
devito/yask/grid.py
|
devito/yask/grid.py
|
import devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
for k, v in state.items():
setattr(self, k, v)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
|
import devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
super(Grid, self).__setstate__(state)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
|
Fix Grid pickling in YASK
|
mpi: Fix Grid pickling in YASK
|
Python
|
mit
|
opesci/devito,opesci/devito
|
import devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
for k, v in state.items():
setattr(self, k, v)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
mpi: Fix Grid pickling in YASK
|
import devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
super(Grid, self).__setstate__(state)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
|
<commit_before>import devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
for k, v in state.items():
setattr(self, k, v)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
<commit_msg>mpi: Fix Grid pickling in YASK<commit_after>
|
import devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
super(Grid, self).__setstate__(state)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
|
import devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
for k, v in state.items():
setattr(self, k, v)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
mpi: Fix Grid pickling in YASKimport devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
super(Grid, self).__setstate__(state)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
|
<commit_before>import devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
for k, v in state.items():
setattr(self, k, v)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
<commit_msg>mpi: Fix Grid pickling in YASK<commit_after>import devito.grid as grid
from devito.yask.function import Constant
from devito.yask.wrappers import contexts
__all__ = ['Grid']
class Grid(grid.Grid):
def __init__(self, *args, **kwargs):
super(Grid, self).__init__(*args, **kwargs)
# Initialize a new YaskContext for this Grid
contexts.putdefault(self)
@property
def _const(self):
return Constant
def _make_stepping_dim(self, time_dim, **kwargs):
# In the `yask` backend, the stepping dimension is an alias of the
# time dimension
return time_dim
def __setstate__(self, state):
super(Grid, self).__setstate__(state)
# A new context is created, as the unpickled Dimensions are new objects
contexts.putdefault(self)
|
01f43d80fd4324f596904e22409c0b76bcb1b015
|
totalsum/templatetags/totalsum.py
|
totalsum/templatetags/totalsum.py
|
"""
Contains some common filter as utilities
"""
from django.template import Library, loader, Context
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(Context(c))
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''
|
"""
Contains some common filter as utilities
"""
from django.template import Library, loader
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(c)
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''
|
Update for Django version 1.11
|
Update for Django version 1.11
|
Python
|
mit
|
20tab/twentytab-totalsum-admin,20tab/twentytab-totalsum-admin
|
"""
Contains some common filter as utilities
"""
from django.template import Library, loader, Context
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(Context(c))
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''Update for Django version 1.11
|
"""
Contains some common filter as utilities
"""
from django.template import Library, loader
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(c)
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''
|
<commit_before>"""
Contains some common filter as utilities
"""
from django.template import Library, loader, Context
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(Context(c))
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''<commit_msg>Update for Django version 1.11<commit_after>
|
"""
Contains some common filter as utilities
"""
from django.template import Library, loader
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(c)
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''
|
"""
Contains some common filter as utilities
"""
from django.template import Library, loader, Context
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(Context(c))
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''Update for Django version 1.11"""
Contains some common filter as utilities
"""
from django.template import Library, loader
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(c)
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''
|
<commit_before>"""
Contains some common filter as utilities
"""
from django.template import Library, loader, Context
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(Context(c))
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''<commit_msg>Update for Django version 1.11<commit_after>"""
Contains some common filter as utilities
"""
from django.template import Library, loader
from django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results, admin_actions
register = Library()
admin_actions = admin_actions
@register.simple_tag(takes_context=True)
def totalsum_result_list(context, cl, totals, unit_of_measure, template_name="totalsum_change_list_results.html"):
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
headers = list(result_headers(cl))
num_sorted_fields = 0
for h in headers:
if h['sortable'] and h['sorted']:
num_sorted_fields += 1
c = {
'cl': cl,
'totals': totals,
'unit_of_measure': unit_of_measure,
'result_hidden_fields': list(result_hidden_fields(cl)),
'result_headers': headers,
'num_sorted_fields': num_sorted_fields,
'results': list(results(cl)),
'pagination_required': pagination_required
}
t = loader.get_template(template_name)
return t.render(c)
@register.filter
def get_total(totals, column):
if column in totals.keys():
return totals[column]
return ''
|
9653deb0917c3a883bf0e7c17903a5f8ed3c14fe
|
fireplace/entity.py
|
fireplace/entity.py
|
import logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
ret += slot.getIntProperty(tag)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
|
import logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
_ret = slot.getIntProperty(tag)
if isinstance(_ret, int):
ret += _ret
else:
ret = _ret(ret)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
|
Allow for callables in getIntProperty()
|
Allow for callables in getIntProperty()
Some tags can now implicitly be functions, as long as they are called
through getIntProperty().
The function will take the current value as input, and will output the
result of a calculation. This matters for Gahz'rilla and Blessed Champion
where the attack up to the point of the buff is doubled.
Thanks, Xinhuan
|
Python
|
agpl-3.0
|
Ragowit/fireplace,butozerca/fireplace,smallnamespace/fireplace,liujimj/fireplace,NightKev/fireplace,smallnamespace/fireplace,oftc-ftw/fireplace,amw2104/fireplace,amw2104/fireplace,beheh/fireplace,liujimj/fireplace,jleclanche/fireplace,Meerkov/fireplace,Meerkov/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,butozerca/fireplace
|
import logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
ret += slot.getIntProperty(tag)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
Allow for callables in getIntProperty()
Some tags can now implicitly be functions, as long as they are called
through getIntProperty().
The function will take the current value as input, and will output the
result of a calculation. This matters for Gahz'rilla and Blessed Champion
where the attack up to the point of the buff is doubled.
Thanks, Xinhuan
|
import logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
_ret = slot.getIntProperty(tag)
if isinstance(_ret, int):
ret += _ret
else:
ret = _ret(ret)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
|
<commit_before>import logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
ret += slot.getIntProperty(tag)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
<commit_msg>Allow for callables in getIntProperty()
Some tags can now implicitly be functions, as long as they are called
through getIntProperty().
The function will take the current value as input, and will output the
result of a calculation. This matters for Gahz'rilla and Blessed Champion
where the attack up to the point of the buff is doubled.
Thanks, Xinhuan<commit_after>
|
import logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
_ret = slot.getIntProperty(tag)
if isinstance(_ret, int):
ret += _ret
else:
ret = _ret(ret)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
|
import logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
ret += slot.getIntProperty(tag)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
Allow for callables in getIntProperty()
Some tags can now implicitly be functions, as long as they are called
through getIntProperty().
The function will take the current value as input, and will output the
result of a calculation. This matters for Gahz'rilla and Blessed Champion
where the attack up to the point of the buff is doubled.
Thanks, Xinhuanimport logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
_ret = slot.getIntProperty(tag)
if isinstance(_ret, int):
ret += _ret
else:
ret = _ret(ret)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
|
<commit_before>import logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
ret += slot.getIntProperty(tag)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
<commit_msg>Allow for callables in getIntProperty()
Some tags can now implicitly be functions, as long as they are called
through getIntProperty().
The function will take the current value as input, and will output the
result of a calculation. This matters for Gahz'rilla and Blessed Champion
where the attack up to the point of the buff is doubled.
Thanks, Xinhuan<commit_after>import logging
from .enums import Zone
class Entity(object):
def __init__(self):
self.tags = {}
# Register the events
self._registerEvents()
def _registerEvents(self):
self._eventListeners = {}
for name in self.events:
func = getattr(self, name, None)
if func:
self._eventListeners[name] = [func]
def broadcast(self, event, *args):
for entity in self.entities:
for f in entity._eventListeners.get(event, []):
if getattr(f, "zone", Zone.PLAY) == Zone.PLAY:
f(*args)
if event != "UPDATE":
self.broadcast("UPDATE")
def setTag(self, tag, value):
logging.debug("%r::%r %r -> %r" % (self, tag, self.tags.get(tag, None), value))
self.tags[tag] = value
def unsetTag(self, tag):
del self.tags[tag]
def getIntProperty(self, tag):
ret = self.tags.get(tag, 0)
for slot in self.slots:
_ret = slot.getIntProperty(tag)
if isinstance(_ret, int):
ret += _ret
else:
ret = _ret(ret)
return ret
def getBoolProperty(self, tag):
if self.tags.get(tag, False):
return True
for slot in self.slots:
if slot.getBoolProperty(tag):
return True
return
|
49c4b3a35aa8c50740761be6e84e3439d8084458
|
main.py
|
main.py
|
import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = "Welcome to the New Ro-Bots Slack, @{}! Please make sure to download this on your phone so we can get your attention! The app is available on both iOS and Android.".format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
|
import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = {}.format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
|
Replace string withe nvironment variable
|
Replace string withe nvironment variable
|
Python
|
mit
|
ollien/Slack-Welcome-Bot
|
import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = "Welcome to the New Ro-Bots Slack, @{}! Please make sure to download this on your phone so we can get your attention! The app is available on both iOS and Android.".format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
Replace string withe nvironment variable
|
import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = {}.format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
|
<commit_before>import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = "Welcome to the New Ro-Bots Slack, @{}! Please make sure to download this on your phone so we can get your attention! The app is available on both iOS and Android.".format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
<commit_msg>Replace string withe nvironment variable<commit_after>
|
import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = {}.format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
|
import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = "Welcome to the New Ro-Bots Slack, @{}! Please make sure to download this on your phone so we can get your attention! The app is available on both iOS and Android.".format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
Replace string withe nvironment variableimport slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = {}.format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
|
<commit_before>import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = "Welcome to the New Ro-Bots Slack, @{}! Please make sure to download this on your phone so we can get your attention! The app is available on both iOS and Android.".format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
<commit_msg>Replace string withe nvironment variable<commit_after>import slackclient
import time
import os
slackClient = slackclient.SlackClient(os.environ["SLACK_TOKEN"])
slackClient.rtm_connect()
lastPingTime = 0
while True:
for message in slackClient.rtm_read():
if message["type"] == "team_join":
username = message["user"]["name"]
message = {}.format(username)
slackClient.api_call("chat.postMessage", channel="#general",
text=message, username="The New Ro-Bot", icon_emoji=":wave:",
link_names = True)
now = time.time()
if now - lastPingTime >= 3:
slackClient.server.ping()
lastPingTime = now
time.sleep(.1)
|
059cc7ec7cd7c8b078b896be67a2041eaa3ea8da
|
accounts/backends.py
|
accounts/backends.py
|
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
else:
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
Move return statement in _lookup_user into except/else flow
|
Move return statement in _lookup_user into except/else flow
|
Python
|
bsd-2-clause
|
ScottyMJacobson/django-email-or-username
|
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
Move return statement in _lookup_user into except/else flow
|
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
else:
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
<commit_before>from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
<commit_msg>Move return statement in _lookup_user into except/else flow<commit_after>
|
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
else:
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
Move return statement in _lookup_user into except/else flowfrom django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
else:
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
<commit_before>from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
<commit_msg>Move return statement in _lookup_user into except/else flow<commit_after>from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.models import check_password
from django.core.validators import validate_email
from django.forms import ValidationError
User = get_user_model()
class EmailOrUsernameAuthBackend():
"""
A custom authentication backend. Allows users to log in using their email address or username.
"""
def _lookup_user(self, username_or_email):
try:
validate_email(username_or_email)
except ValidationError:
# not an email
using_email = False
else:
# looks like an email!
using_email = True
try:
if using_email:
user = User.objects.get(email__iexact=username_or_email)
else:
user = User.objects.get(username__iexact=username_or_email)
except User.DoesNotExist:
return None
else:
return user
def authenticate(self, username=None, password=None):
"""
Authentication method - username here is actually "username_or_email",
but named as such to fit Django convention
"""
user = self._lookup_user(username)
if user:
if user.check_password(password):
return user
return None
def get_user(self, user_id):
try:
user = User.objects.get(pk=user_id)
if user.is_active:
return user
return None
except User.DoesNotExist:
return None
|
013226abfe6f6594ffba85c28e90a90bd7befa68
|
project/apps/api/signals.py
|
project/apps/api/signals.py
|
from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, **kwargs):
if created:
instance.build()
instance.save()
|
from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs):
if not raw:
if created:
instance.build()
instance.save()
|
Add check for fixture loading
|
Add check for fixture loading
|
Python
|
bsd-2-clause
|
barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore-django,dbinetti/barberscore,dbinetti/barberscore
|
from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, **kwargs):
if created:
instance.build()
instance.save()
Add check for fixture loading
|
from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs):
if not raw:
if created:
instance.build()
instance.save()
|
<commit_before>from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, **kwargs):
if created:
instance.build()
instance.save()
<commit_msg>Add check for fixture loading<commit_after>
|
from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs):
if not raw:
if created:
instance.build()
instance.save()
|
from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, **kwargs):
if created:
instance.build()
instance.save()
Add check for fixture loadingfrom django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs):
if not raw:
if created:
instance.build()
instance.save()
|
<commit_before>from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, **kwargs):
if created:
instance.build()
instance.save()
<commit_msg>Add check for fixture loading<commit_after>from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings
from .models import (
Contest,
)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def user_post_save(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@receiver(post_save, sender=Contest)
def contest_post_save(sender, instance=None, created=False, raw=False, **kwargs):
if not raw:
if created:
instance.build()
instance.save()
|
2d2819a18f4b2997babb85ef3b942990683b7bb7
|
pontoon/base/urls.py
|
pontoon/base/urls.py
|
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
|
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^error/$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
|
Add missing error URL regex
|
Add missing error URL regex
|
Python
|
bsd-3-clause
|
participedia/pontoon,mastizada/pontoon,mastizada/pontoon,m8ttyB/pontoon,mathjazz/pontoon,mastizada/pontoon,yfdyh000/pontoon,sudheesh001/pontoon,mozilla/pontoon,vivekanand1101/pontoon,mastizada/pontoon,sudheesh001/pontoon,yfdyh000/pontoon,mathjazz/pontoon,participedia/pontoon,participedia/pontoon,vivekanand1101/pontoon,yfdyh000/pontoon,m8ttyB/pontoon,Jobava/mirror-pontoon,Osmose/pontoon,mozilla/pontoon,Osmose/pontoon,Jobava/mirror-pontoon,jotes/pontoon,Jobava/mirror-pontoon,sudheesh001/pontoon,Osmose/pontoon,mozilla/pontoon,jotes/pontoon,mozilla/pontoon,m8ttyB/pontoon,jotes/pontoon,sudheesh001/pontoon,Jobava/mirror-pontoon,jotes/pontoon,mathjazz/pontoon,mathjazz/pontoon,mozilla/pontoon,participedia/pontoon,mathjazz/pontoon,yfdyh000/pontoon,m8ttyB/pontoon,vivekanand1101/pontoon,vivekanand1101/pontoon,Osmose/pontoon
|
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
Add missing error URL regex
|
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^error/$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
|
<commit_before>from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
<commit_msg>Add missing error URL regex<commit_after>
|
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^error/$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
|
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
Add missing error URL regexfrom django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^error/$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
|
<commit_before>from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
<commit_msg>Add missing error URL regex<commit_after>from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
url(r'^$', views.home, name='pontoon.home'),
url(r'^error/$', views.home, name='pontoon.home'),
url(r'^locale/(?P<locale>[A-Za-z0-9\-\@\.]+)/url/(?P<url>\S+)/$', views.translate, name='pontoon.translate'),
url(r'^a/project/$', views.admin_project, name='pontoon.admin.project.new'),
url(r'^a/project/(?P<url>\S+)/$', views.admin_project, name='pontoon.admin.project'),
url(r'^a/$', views.admin, name='pontoon.admin'),
url(r'^get/', views.get_translation, name='pontoon.get'),
url(r'^save/', views.save_translation, name='pontoon.save'),
url(r'^load/', views.load_entities, name='pontoon.load'),
url(r'^download/', views.download, name='pontoon.download'),
url(r'^svn/$', views.commit_to_svn, name='pontoon.svn'),
url(r'^transifex/$', views.save_to_transifex, name='pontoon.transifex'),
url(r'^transifex/update/$', views.update_from_transifex, name='pontoon.update.transifex'),
url(r'^csrf/$', views.get_csrf, name='pontoon.csrf'),
)
|
f6a8e84a2557c5edf29a6f3afa4d1cce1d42d389
|
tests/basics/try_finally_loops.py
|
tests/basics/try_finally_loops.py
|
# Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
|
# Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
# break from within try-finally, within for-loop
for i in [1]:
try:
print(i)
break
finally:
print('finally 4')
|
Add test for break from within try within a for-loop.
|
tests/basics: Add test for break from within try within a for-loop.
|
Python
|
mit
|
turbinenreiter/micropython,Peetz0r/micropython-esp32,hosaka/micropython,ryannathans/micropython,bvernoux/micropython,tralamazza/micropython,cwyark/micropython,turbinenreiter/micropython,alex-march/micropython,SHA2017-badge/micropython-esp32,dxxb/micropython,swegener/micropython,adafruit/circuitpython,SHA2017-badge/micropython-esp32,alex-robbins/micropython,HenrikSolver/micropython,hosaka/micropython,bvernoux/micropython,matthewelse/micropython,jmarcelino/pycom-micropython,swegener/micropython,hosaka/micropython,selste/micropython,matthewelse/micropython,torwag/micropython,deshipu/micropython,dxxb/micropython,toolmacher/micropython,deshipu/micropython,SHA2017-badge/micropython-esp32,selste/micropython,oopy/micropython,pfalcon/micropython,PappaPeppar/micropython,infinnovation/micropython,hiway/micropython,AriZuu/micropython,trezor/micropython,chrisdearman/micropython,jmarcelino/pycom-micropython,blazewicz/micropython,infinnovation/micropython,tuc-osg/micropython,AriZuu/micropython,oopy/micropython,blazewicz/micropython,pozetroninc/micropython,tuc-osg/micropython,jmarcelino/pycom-micropython,tobbad/micropython,pozetroninc/micropython,MrSurly/micropython-esp32,pramasoul/micropython,SHA2017-badge/micropython-esp32,PappaPeppar/micropython,alex-robbins/micropython,turbinenreiter/micropython,cwyark/micropython,alex-march/micropython,kerneltask/micropython,alex-robbins/micropython,hosaka/micropython,infinnovation/micropython,Timmenem/micropython,AriZuu/micropython,Peetz0r/micropython-esp32,blazewicz/micropython,matthewelse/micropython,MrSurly/micropython-esp32,pfalcon/micropython,hiway/micropython,MrSurly/micropython-esp32,ryannathans/micropython,kerneltask/micropython,chrisdearman/micropython,swegener/micropython,puuu/micropython,mhoffma/micropython,jmarcelino/pycom-micropython,selste/micropython,blazewicz/micropython,torwag/micropython,henriknelson/micropython,adafruit/micropython,tuc-osg/micropython,TDAbboud/micropython,pfalcon/micropython,adafruit/micropython,kerneltask/micropython,infinnovation/micropython,deshipu/micropython,dmazzella/micropython,puuu/micropython,toolmacher/micropython,bvernoux/micropython,adafruit/circuitpython,MrSurly/micropython-esp32,pozetroninc/micropython,tuc-osg/micropython,oopy/micropython,toolmacher/micropython,swegener/micropython,dmazzella/micropython,infinnovation/micropython,TDAbboud/micropython,kerneltask/micropython,lowRISC/micropython,cwyark/micropython,puuu/micropython,Peetz0r/micropython-esp32,mhoffma/micropython,micropython/micropython-esp32,MrSurly/micropython,HenrikSolver/micropython,selste/micropython,henriknelson/micropython,matthewelse/micropython,adafruit/micropython,dxxb/micropython,hiway/micropython,pfalcon/micropython,adafruit/micropython,deshipu/micropython,torwag/micropython,pramasoul/micropython,mhoffma/micropython,adafruit/circuitpython,chrisdearman/micropython,pramasoul/micropython,TDAbboud/micropython,toolmacher/micropython,adafruit/circuitpython,lowRISC/micropython,kerneltask/micropython,trezor/micropython,PappaPeppar/micropython,tralamazza/micropython,puuu/micropython,henriknelson/micropython,dmazzella/micropython,oopy/micropython,alex-robbins/micropython,micropython/micropython-esp32,tralamazza/micropython,cwyark/micropython,Peetz0r/micropython-esp32,mhoffma/micropython,pramasoul/micropython,ryannathans/micropython,dxxb/micropython,hiway/micropython,adafruit/circuitpython,HenrikSolver/micropython,henriknelson/micropython,dmazzella/micropython,pozetroninc/micropython,puuu/micropython,tobbad/micropython,SHA2017-badge/micropython-esp32,Timmenem/micropython,hosaka/micropython,Timmenem/micropython,ryannathans/micropython,torwag/micropython,MrSurly/micropython,trezor/micropython,ryannathans/micropython,lowRISC/micropython,swegener/micropython,hiway/micropython,henriknelson/micropython,HenrikSolver/micropython,bvernoux/micropython,MrSurly/micropython,turbinenreiter/micropython,MrSurly/micropython,PappaPeppar/micropython,TDAbboud/micropython,matthewelse/micropython,trezor/micropython,lowRISC/micropython,matthewelse/micropython,micropython/micropython-esp32,chrisdearman/micropython,alex-robbins/micropython,turbinenreiter/micropython,alex-march/micropython,tuc-osg/micropython,adafruit/circuitpython,TDAbboud/micropython,dxxb/micropython,chrisdearman/micropython,alex-march/micropython,jmarcelino/pycom-micropython,Peetz0r/micropython-esp32,blazewicz/micropython,trezor/micropython,HenrikSolver/micropython,pramasoul/micropython,tobbad/micropython,cwyark/micropython,tralamazza/micropython,pfalcon/micropython,toolmacher/micropython,tobbad/micropython,MrSurly/micropython,pozetroninc/micropython,micropython/micropython-esp32,lowRISC/micropython,bvernoux/micropython,AriZuu/micropython,tobbad/micropython,micropython/micropython-esp32,selste/micropython,adafruit/micropython,Timmenem/micropython,Timmenem/micropython,alex-march/micropython,torwag/micropython,oopy/micropython,mhoffma/micropython,AriZuu/micropython,MrSurly/micropython-esp32,deshipu/micropython,PappaPeppar/micropython
|
# Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
tests/basics: Add test for break from within try within a for-loop.
|
# Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
# break from within try-finally, within for-loop
for i in [1]:
try:
print(i)
break
finally:
print('finally 4')
|
<commit_before># Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
<commit_msg>tests/basics: Add test for break from within try within a for-loop.<commit_after>
|
# Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
# break from within try-finally, within for-loop
for i in [1]:
try:
print(i)
break
finally:
print('finally 4')
|
# Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
tests/basics: Add test for break from within try within a for-loop.# Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
# break from within try-finally, within for-loop
for i in [1]:
try:
print(i)
break
finally:
print('finally 4')
|
<commit_before># Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
<commit_msg>tests/basics: Add test for break from within try within a for-loop.<commit_after># Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3')
# Multi-level
for i in range(4):
print(i)
try:
while True:
try:
try:
break
finally:
print('finally 1')
finally:
print('finally 2')
print('here')
finally:
print('finnaly 3')
# break from within try-finally, within for-loop
for i in [1]:
try:
print(i)
break
finally:
print('finally 4')
|
3b6162de670d47856e6d377912c2fdf4d5f430a9
|
moto/forecast/exceptions.py
|
moto/forecast/exceptions.py
|
from __future__ import unicode_literals
import json
class AWSError(Exception):
TYPE = None
STATUS = 400
def __init__(self, message, type=None, status=None):
self.message = message
self.type = type if type is not None else self.TYPE
self.status = status if status is not None else self.STATUS
def response(self):
return (
json.dumps({"__type": self.type, "message": self.message}),
dict(status=self.status),
)
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
|
from __future__ import unicode_literals
from moto.core.exceptions import AWSError
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
|
Refactor Forecast to also use shared AWSError class
|
Refactor Forecast to also use shared AWSError class
|
Python
|
apache-2.0
|
spulec/moto,william-richard/moto,spulec/moto,william-richard/moto,spulec/moto,william-richard/moto,spulec/moto,william-richard/moto,william-richard/moto,spulec/moto,spulec/moto,william-richard/moto
|
from __future__ import unicode_literals
import json
class AWSError(Exception):
TYPE = None
STATUS = 400
def __init__(self, message, type=None, status=None):
self.message = message
self.type = type if type is not None else self.TYPE
self.status = status if status is not None else self.STATUS
def response(self):
return (
json.dumps({"__type": self.type, "message": self.message}),
dict(status=self.status),
)
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
Refactor Forecast to also use shared AWSError class
|
from __future__ import unicode_literals
from moto.core.exceptions import AWSError
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
|
<commit_before>from __future__ import unicode_literals
import json
class AWSError(Exception):
TYPE = None
STATUS = 400
def __init__(self, message, type=None, status=None):
self.message = message
self.type = type if type is not None else self.TYPE
self.status = status if status is not None else self.STATUS
def response(self):
return (
json.dumps({"__type": self.type, "message": self.message}),
dict(status=self.status),
)
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
<commit_msg>Refactor Forecast to also use shared AWSError class<commit_after>
|
from __future__ import unicode_literals
from moto.core.exceptions import AWSError
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
|
from __future__ import unicode_literals
import json
class AWSError(Exception):
TYPE = None
STATUS = 400
def __init__(self, message, type=None, status=None):
self.message = message
self.type = type if type is not None else self.TYPE
self.status = status if status is not None else self.STATUS
def response(self):
return (
json.dumps({"__type": self.type, "message": self.message}),
dict(status=self.status),
)
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
Refactor Forecast to also use shared AWSError classfrom __future__ import unicode_literals
from moto.core.exceptions import AWSError
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
|
<commit_before>from __future__ import unicode_literals
import json
class AWSError(Exception):
TYPE = None
STATUS = 400
def __init__(self, message, type=None, status=None):
self.message = message
self.type = type if type is not None else self.TYPE
self.status = status if status is not None else self.STATUS
def response(self):
return (
json.dumps({"__type": self.type, "message": self.message}),
dict(status=self.status),
)
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
<commit_msg>Refactor Forecast to also use shared AWSError class<commit_after>from __future__ import unicode_literals
from moto.core.exceptions import AWSError
class InvalidInputException(AWSError):
TYPE = "InvalidInputException"
class ResourceAlreadyExistsException(AWSError):
TYPE = "ResourceAlreadyExistsException"
class ResourceNotFoundException(AWSError):
TYPE = "ResourceNotFoundException"
class ResourceInUseException(AWSError):
TYPE = "ResourceInUseException"
class LimitExceededException(AWSError):
TYPE = "LimitExceededException"
class ValidationException(AWSError):
TYPE = "ValidationException"
|
9083afc0e308588345c74675654a4c0d3061f39d
|
test/test_machine.py
|
test/test_machine.py
|
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
|
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
def test_machine_defaults(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=True,
use_defaults=True,
_path=join(tmpdir, 'asv-machine.json'))
assert m.__dict__ == m.get_defaults()
|
Add a test for asv machine --yes using defaults values
|
Add a test for asv machine --yes using defaults values
|
Python
|
bsd-3-clause
|
pv/asv,spacetelescope/asv,qwhelan/asv,airspeed-velocity/asv,airspeed-velocity/asv,pv/asv,qwhelan/asv,spacetelescope/asv,airspeed-velocity/asv,pv/asv,pv/asv,qwhelan/asv,spacetelescope/asv,spacetelescope/asv,airspeed-velocity/asv,qwhelan/asv
|
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
Add a test for asv machine --yes using defaults values
|
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
def test_machine_defaults(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=True,
use_defaults=True,
_path=join(tmpdir, 'asv-machine.json'))
assert m.__dict__ == m.get_defaults()
|
<commit_before># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
<commit_msg>Add a test for asv machine --yes using defaults values<commit_after>
|
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
def test_machine_defaults(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=True,
use_defaults=True,
_path=join(tmpdir, 'asv-machine.json'))
assert m.__dict__ == m.get_defaults()
|
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
Add a test for asv machine --yes using defaults values# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
def test_machine_defaults(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=True,
use_defaults=True,
_path=join(tmpdir, 'asv-machine.json'))
assert m.__dict__ == m.get_defaults()
|
<commit_before># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
<commit_msg>Add a test for asv machine --yes using defaults values<commit_after># -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from os.path import join
import six
from asv import machine
def test_machine(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=False,
machine="orangutan",
os="BeOS",
arch="MIPS",
cpu="10 MHz",
ram="640k",
_path=join(tmpdir, 'asv-machine.json'))
m = machine.Machine.load(
_path=join(tmpdir, 'asv-machine.json'), interactive=False)
assert m.machine == 'orangutan'
assert m.os == 'BeOS'
assert m.arch == 'MIPS'
assert m.cpu == '10 MHz'
assert m.ram == '640k'
def test_machine_defaults(tmpdir):
tmpdir = six.text_type(tmpdir)
m = machine.Machine.load(
interactive=True,
use_defaults=True,
_path=join(tmpdir, 'asv-machine.json'))
assert m.__dict__ == m.get_defaults()
|
f9ebca863ff2fd1a0ea160047cd70c59b4663b9d
|
test_bert_trainer.py
|
test_bert_trainer.py
|
import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
trainer.test(test_features)
if __name__ == '__main__':
unittest.main()
|
import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
results = trainer.test(test_features)
print('Evaluation results:', results)
if __name__ == '__main__':
unittest.main()
|
Print eval results in test
|
Print eval results in test
|
Python
|
apache-2.0
|
googleinterns/smart-news-query-embeddings,googleinterns/smart-news-query-embeddings
|
import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
trainer.test(test_features)
if __name__ == '__main__':
unittest.main()
Print eval results in test
|
import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
results = trainer.test(test_features)
print('Evaluation results:', results)
if __name__ == '__main__':
unittest.main()
|
<commit_before>import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
trainer.test(test_features)
if __name__ == '__main__':
unittest.main()
<commit_msg>Print eval results in test<commit_after>
|
import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
results = trainer.test(test_features)
print('Evaluation results:', results)
if __name__ == '__main__':
unittest.main()
|
import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
trainer.test(test_features)
if __name__ == '__main__':
unittest.main()
Print eval results in testimport unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
results = trainer.test(test_features)
print('Evaluation results:', results)
if __name__ == '__main__':
unittest.main()
|
<commit_before>import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
trainer.test(test_features)
if __name__ == '__main__':
unittest.main()
<commit_msg>Print eval results in test<commit_after>import unittest
import time
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def test_init(self):
trainer = BERTTrainer()
def test_train(self):
output_dir = 'test_{}'.format(str(int(time.time())))
trainer = BERTTrainer(output_dir=output_dir)
print(trainer.bert_model_hub)
data = pd.DataFrame({
'abstract': ['test one', 'test two', 'test three'] * 5,
'section': ['U.S.', 'Arts', 'U.S.'] * 5,
})
data_column = 'abstract'
label_column = 'section'
train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length)
trainer.train(train_features, label_list)
results = trainer.test(test_features)
print('Evaluation results:', results)
if __name__ == '__main__':
unittest.main()
|
7534e9b2af5e30b2cce4e5e710600ebeb4f61e9a
|
appengine/swarming/swarming_bot/api/platforms/android.py
|
appengine/swarming/swarming_bot/api/platforms/android.py
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import high
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import adb_protocol
from adb import common
from adb import high
# Master switch that can easily be temporarily increased to INFO or even DEBUG
# when needed by simply pushing a new tainted swarming server version. This
# helps quickly debugging issues. On the other hand, even INFO level is quite
# verbose so keep it at WARNING by default.
LEVEL = logging.WARNING
adb_commands_safe._LOG.setLevel(LEVEL)
adb_protocol._LOG.setLevel(LEVEL)
common._LOG.setLevel(LEVEL)
high._LOG.setLevel(LEVEL)
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
def kill_adb():
return adb_commands_safe.KillADB()
|
Add kill_adb() and increase python-adb logging to WARNING.
|
Add kill_adb() and increase python-adb logging to WARNING.
It gives a master switch that can easily be temporarily increased to INFO or
even DEBUG when needed by simply pushing a new tainted swarming server version.
This helps quickly debugging issues. On the other hand, even INFO level is quite
verbose so keep it at WARNING by default.
Adding kill_adb() is useful, since it's better to forcibly kill adb upfront in
on_after_task() than try to kill it after trying USB enumeration then killing
adb then enumerating again.
R=stip@chromium.org
BUG=chromium:525873
Review URL: https://codereview.chromium.org/1430073003
|
Python
|
apache-2.0
|
luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import high
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
Add kill_adb() and increase python-adb logging to WARNING.
It gives a master switch that can easily be temporarily increased to INFO or
even DEBUG when needed by simply pushing a new tainted swarming server version.
This helps quickly debugging issues. On the other hand, even INFO level is quite
verbose so keep it at WARNING by default.
Adding kill_adb() is useful, since it's better to forcibly kill adb upfront in
on_after_task() than try to kill it after trying USB enumeration then killing
adb then enumerating again.
R=stip@chromium.org
BUG=chromium:525873
Review URL: https://codereview.chromium.org/1430073003
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import adb_protocol
from adb import common
from adb import high
# Master switch that can easily be temporarily increased to INFO or even DEBUG
# when needed by simply pushing a new tainted swarming server version. This
# helps quickly debugging issues. On the other hand, even INFO level is quite
# verbose so keep it at WARNING by default.
LEVEL = logging.WARNING
adb_commands_safe._LOG.setLevel(LEVEL)
adb_protocol._LOG.setLevel(LEVEL)
common._LOG.setLevel(LEVEL)
high._LOG.setLevel(LEVEL)
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
def kill_adb():
return adb_commands_safe.KillADB()
|
<commit_before># Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import high
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
<commit_msg>Add kill_adb() and increase python-adb logging to WARNING.
It gives a master switch that can easily be temporarily increased to INFO or
even DEBUG when needed by simply pushing a new tainted swarming server version.
This helps quickly debugging issues. On the other hand, even INFO level is quite
verbose so keep it at WARNING by default.
Adding kill_adb() is useful, since it's better to forcibly kill adb upfront in
on_after_task() than try to kill it after trying USB enumeration then killing
adb then enumerating again.
R=stip@chromium.org
BUG=chromium:525873
Review URL: https://codereview.chromium.org/1430073003<commit_after>
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import adb_protocol
from adb import common
from adb import high
# Master switch that can easily be temporarily increased to INFO or even DEBUG
# when needed by simply pushing a new tainted swarming server version. This
# helps quickly debugging issues. On the other hand, even INFO level is quite
# verbose so keep it at WARNING by default.
LEVEL = logging.WARNING
adb_commands_safe._LOG.setLevel(LEVEL)
adb_protocol._LOG.setLevel(LEVEL)
common._LOG.setLevel(LEVEL)
high._LOG.setLevel(LEVEL)
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
def kill_adb():
return adb_commands_safe.KillADB()
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import high
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
Add kill_adb() and increase python-adb logging to WARNING.
It gives a master switch that can easily be temporarily increased to INFO or
even DEBUG when needed by simply pushing a new tainted swarming server version.
This helps quickly debugging issues. On the other hand, even INFO level is quite
verbose so keep it at WARNING by default.
Adding kill_adb() is useful, since it's better to forcibly kill adb upfront in
on_after_task() than try to kill it after trying USB enumeration then killing
adb then enumerating again.
R=stip@chromium.org
BUG=chromium:525873
Review URL: https://codereview.chromium.org/1430073003# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import adb_protocol
from adb import common
from adb import high
# Master switch that can easily be temporarily increased to INFO or even DEBUG
# when needed by simply pushing a new tainted swarming server version. This
# helps quickly debugging issues. On the other hand, even INFO level is quite
# verbose so keep it at WARNING by default.
LEVEL = logging.WARNING
adb_commands_safe._LOG.setLevel(LEVEL)
adb_protocol._LOG.setLevel(LEVEL)
common._LOG.setLevel(LEVEL)
high._LOG.setLevel(LEVEL)
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
def kill_adb():
return adb_commands_safe.KillADB()
|
<commit_before># Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import high
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
<commit_msg>Add kill_adb() and increase python-adb logging to WARNING.
It gives a master switch that can easily be temporarily increased to INFO or
even DEBUG when needed by simply pushing a new tainted swarming server version.
This helps quickly debugging issues. On the other hand, even INFO level is quite
verbose so keep it at WARNING by default.
Adding kill_adb() is useful, since it's better to forcibly kill adb upfront in
on_after_task() than try to kill it after trying USB enumeration then killing
adb then enumerating again.
R=stip@chromium.org
BUG=chromium:525873
Review URL: https://codereview.chromium.org/1430073003<commit_after># Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Android specific utility functions.
This file serves as an API to bot_config.py. bot_config.py can be replaced on
the server to allow additional server-specific functionality.
"""
import collections
import logging
import os
from adb import adb_commands_safe
from adb import adb_protocol
from adb import common
from adb import high
# Master switch that can easily be temporarily increased to INFO or even DEBUG
# when needed by simply pushing a new tainted swarming server version. This
# helps quickly debugging issues. On the other hand, even INFO level is quite
# verbose so keep it at WARNING by default.
LEVEL = logging.WARNING
adb_commands_safe._LOG.setLevel(LEVEL)
adb_protocol._LOG.setLevel(LEVEL)
common._LOG.setLevel(LEVEL)
high._LOG.setLevel(LEVEL)
def initialize(pub_key, priv_key):
return high.Initialize(pub_key, priv_key)
def get_devices(bot):
return high.GetDevices(
'swarming', 10000, 10000, on_error=bot.post_error if bot else None,
as_root=True)
def close_devices(devices):
return high.CloseDevices(devices)
def kill_adb():
return adb_commands_safe.KillADB()
|
154c493b64cf227c366e63dc8346d76601d36ba6
|
submodules-to-glockfile.py
|
submodules-to-glockfile.py
|
#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print "github.com/localhots/satan {}".format(path_sha1("."))
for path in paths:
print "{repo} {sha}".format(
repo = path[7:],
sha = path_sha1(path)
)
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1]
return sha1
if __name__ == "__main__": main()
|
#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print("github.com/localhots/satan {}".format(path_sha1(".")))
for path in paths:
print("{} {}".format(path[7:], path_sha1(path)))
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1].decode("ascii")
return sha1
if __name__ == "__main__":
main()
|
Make submodules script work in both 2 and 3 pythons
|
Make submodules script work in both 2 and 3 pythons
|
Python
|
mit
|
localhots/satan,localhots/satan,localhots/satan,localhots/satan
|
#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print "github.com/localhots/satan {}".format(path_sha1("."))
for path in paths:
print "{repo} {sha}".format(
repo = path[7:],
sha = path_sha1(path)
)
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1]
return sha1
if __name__ == "__main__": main()
Make submodules script work in both 2 and 3 pythons
|
#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print("github.com/localhots/satan {}".format(path_sha1(".")))
for path in paths:
print("{} {}".format(path[7:], path_sha1(path)))
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1].decode("ascii")
return sha1
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print "github.com/localhots/satan {}".format(path_sha1("."))
for path in paths:
print "{repo} {sha}".format(
repo = path[7:],
sha = path_sha1(path)
)
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1]
return sha1
if __name__ == "__main__": main()
<commit_msg>Make submodules script work in both 2 and 3 pythons<commit_after>
|
#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print("github.com/localhots/satan {}".format(path_sha1(".")))
for path in paths:
print("{} {}".format(path[7:], path_sha1(path)))
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1].decode("ascii")
return sha1
if __name__ == "__main__":
main()
|
#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print "github.com/localhots/satan {}".format(path_sha1("."))
for path in paths:
print "{repo} {sha}".format(
repo = path[7:],
sha = path_sha1(path)
)
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1]
return sha1
if __name__ == "__main__": main()
Make submodules script work in both 2 and 3 pythons#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print("github.com/localhots/satan {}".format(path_sha1(".")))
for path in paths:
print("{} {}".format(path[7:], path_sha1(path)))
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1].decode("ascii")
return sha1
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print "github.com/localhots/satan {}".format(path_sha1("."))
for path in paths:
print "{repo} {sha}".format(
repo = path[7:],
sha = path_sha1(path)
)
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1]
return sha1
if __name__ == "__main__": main()
<commit_msg>Make submodules script work in both 2 and 3 pythons<commit_after>#!/usr/bin/python
import re
import subprocess
def main():
source = open(".gitmodules").read()
paths = re.findall(r"path = (.*)", source)
print("github.com/localhots/satan {}".format(path_sha1(".")))
for path in paths:
print("{} {}".format(path[7:], path_sha1(path)))
def path_sha1(path):
cmd = "cd {} && git rev-parse HEAD".format(path)
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
sha1 = sp.stdout.read()[:-1].decode("ascii")
return sha1
if __name__ == "__main__":
main()
|
e42c2f6607d59706358fbd0a81163d793d1bebfb
|
plumeria/plugins/server_control.py
|
plumeria/plugins/server_control.py
|
import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | set icon
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
|
import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | icon set
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
|
Fix typo in docs for /icon set.
|
Fix typo in docs for /icon set.
|
Python
|
mit
|
sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria
|
import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | set icon
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
Fix typo in docs for /icon set.
|
import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | icon set
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
|
<commit_before>import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | set icon
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
<commit_msg>Fix typo in docs for /icon set.<commit_after>
|
import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | icon set
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
|
import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | set icon
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
Fix typo in docs for /icon set.import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | icon set
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
|
<commit_before>import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | set icon
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
<commit_msg>Fix typo in docs for /icon set.<commit_after>import asyncio
import io
import re
from plumeria.command import commands, CommandError
from plumeria.message import Message
from plumeria.message.image import read_image
from plumeria.perms import server_admins_only
from plumeria.transport.transport import ForbiddenError
@commands.register('icon set', category='Management')
@server_admins_only
async def set_icon(message: Message):
"""
Set the server icon to the given image.
Example::
/drawtext Hello there! | icon set
Requires an input image.
"""
attachment = await read_image(message)
if not attachment:
raise CommandError("No image is available to process.")
def execute():
width, height = attachment.image.size
if width < 128 or height < 128:
raise CommandError("Image is too small (128x128 minimum size).")
buffer = io.BytesIO()
attachment.image.save(buffer, "png")
return buffer.getvalue()
image_data = await asyncio.get_event_loop().run_in_executor(None, execute)
try:
await message.server.update(icon=image_data)
return "Server icon updated."
except ForbiddenError as e:
raise CommandError("The bot doesn't have the permissions to do this: {}".format(str(e)))
|
9364cf8e738b048e16f8f6504674536a39be96e0
|
graphiter/models.py
|
graphiter/models.py
|
from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
|
from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('page_detail', kwargs={'slug': self.slug})
|
Add get_absolute_url to Page model
|
Add get_absolute_url to Page model
|
Python
|
bsd-2-clause
|
jwineinger/django-graphiter
|
from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
Add get_absolute_url to Page model
|
from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('page_detail', kwargs={'slug': self.slug})
|
<commit_before>from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
<commit_msg>Add get_absolute_url to Page model<commit_after>
|
from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('page_detail', kwargs={'slug': self.slug})
|
from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
Add get_absolute_url to Page modelfrom django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('page_detail', kwargs={'slug': self.slug})
|
<commit_before>from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
<commit_msg>Add get_absolute_url to Page model<commit_after>from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('page_detail', kwargs={'slug': self.slug})
|
e07f095944a0a6edd125d75f4980a45fc10c6dfd
|
wiblog/util/comments.py
|
wiblog/util/comments.py
|
# This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from fragdev.contact import validate_ham
from django.forms import ModelForm
from django import forms
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5)
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
|
# This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from django.forms import ModelForm
from django import forms
from fragdev.util.validate_ham import ANTI_SPAM, validate_ham
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\
.format(ANTI_SPAM),
validators=[validate_ham],
max_length=len(ANTI_SPAM))
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
|
Fix wiblog's use of the anti-spam validator
|
Fix wiblog's use of the anti-spam validator
|
Python
|
agpl-3.0
|
lo-windigo/fragdev,lo-windigo/fragdev
|
# This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from fragdev.contact import validate_ham
from django.forms import ModelForm
from django import forms
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5)
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
Fix wiblog's use of the anti-spam validator
|
# This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from django.forms import ModelForm
from django import forms
from fragdev.util.validate_ham import ANTI_SPAM, validate_ham
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\
.format(ANTI_SPAM),
validators=[validate_ham],
max_length=len(ANTI_SPAM))
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
|
<commit_before># This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from fragdev.contact import validate_ham
from django.forms import ModelForm
from django import forms
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5)
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
<commit_msg>Fix wiblog's use of the anti-spam validator<commit_after>
|
# This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from django.forms import ModelForm
from django import forms
from fragdev.util.validate_ham import ANTI_SPAM, validate_ham
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\
.format(ANTI_SPAM),
validators=[validate_ham],
max_length=len(ANTI_SPAM))
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
|
# This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from fragdev.contact import validate_ham
from django.forms import ModelForm
from django import forms
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5)
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
Fix wiblog's use of the anti-spam validator# This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from django.forms import ModelForm
from django import forms
from fragdev.util.validate_ham import ANTI_SPAM, validate_ham
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\
.format(ANTI_SPAM),
validators=[validate_ham],
max_length=len(ANTI_SPAM))
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
|
<commit_before># This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from fragdev.contact import validate_ham
from django.forms import ModelForm
from django import forms
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "power"',validators=[validate_ham],max_length=5)
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
<commit_msg>Fix wiblog's use of the anti-spam validator<commit_after># This file is part of the FragDev Website.
#
# the FragDev Website is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# the FragDev Website 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the FragDev Website. If not, see <http://www.gnu.org/licenses/>.
from django.forms import ModelForm
from django import forms
from fragdev.util.validate_ham import ANTI_SPAM, validate_ham
from wiblog.models import Comment
class CommentForm(ModelForm):
verify = forms.CharField(label='Anti-spam: Type in the word "{}"'\
.format(ANTI_SPAM),
validators=[validate_ham],
max_length=len(ANTI_SPAM))
class Meta:
model = Comment
fields = ('name', 'url', 'comment')
|
1d1c303b9b3790256d5ebf2d2e93528a23e8270a
|
synapse/config/__main__.py
|
synapse/config/__main__.py
|
# -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r", action)
sys.exit(1)
|
# -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r\n" % (action,))
sys.exit(1)
|
Fix typo when using sys.stderr.write
|
Fix typo when using sys.stderr.write
|
Python
|
apache-2.0
|
rzr/synapse,TribeMedia/synapse,iot-factory/synapse,matrix-org/synapse,iot-factory/synapse,rzr/synapse,rzr/synapse,TribeMedia/synapse,matrix-org/synapse,iot-factory/synapse,rzr/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,iot-factory/synapse,TribeMedia/synapse,TribeMedia/synapse,rzr/synapse,iot-factory/synapse,matrix-org/synapse
|
# -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r", action)
sys.exit(1)
Fix typo when using sys.stderr.write
|
# -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r\n" % (action,))
sys.exit(1)
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r", action)
sys.exit(1)
<commit_msg>Fix typo when using sys.stderr.write<commit_after>
|
# -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r\n" % (action,))
sys.exit(1)
|
# -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r", action)
sys.exit(1)
Fix typo when using sys.stderr.write# -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r\n" % (action,))
sys.exit(1)
|
<commit_before># -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r", action)
sys.exit(1)
<commit_msg>Fix typo when using sys.stderr.write<commit_after># -*- coding: utf-8 -*-
# Copyright 2015 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.
if __name__ == "__main__":
import sys
from homeserver import HomeServerConfig
action = sys.argv[1]
if action == "read":
key = sys.argv[2]
config = HomeServerConfig.load_config("", sys.argv[3:])
print getattr(config, key)
sys.exit(0)
else:
sys.stderr.write("Unknown command %r\n" % (action,))
sys.exit(1)
|
3382b5003eadec99f0816d9190038bd2caf6c412
|
system_maintenance/urls.py
|
system_maintenance/urls.py
|
from django.conf.urls import patterns, url
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = patterns('',
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', 'django.contrib.auth.views.login', {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
)
|
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = [
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', auth_views.login, {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', auth_views.logout, {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
]
|
Resolve Django 1.10 deprecation warnings
|
Resolve Django 1.10 deprecation warnings
|
Python
|
bsd-3-clause
|
mfcovington/django-system-maintenance,mfcovington/django-system-maintenance,mfcovington/django-system-maintenance
|
from django.conf.urls import patterns, url
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = patterns('',
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', 'django.contrib.auth.views.login', {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
)
Resolve Django 1.10 deprecation warnings
|
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = [
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', auth_views.login, {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', auth_views.logout, {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
]
|
<commit_before>from django.conf.urls import patterns, url
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = patterns('',
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', 'django.contrib.auth.views.login', {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
)
<commit_msg>Resolve Django 1.10 deprecation warnings<commit_after>
|
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = [
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', auth_views.login, {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', auth_views.logout, {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
]
|
from django.conf.urls import patterns, url
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = patterns('',
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', 'django.contrib.auth.views.login', {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
)
Resolve Django 1.10 deprecation warningsfrom django.conf.urls import url
from django.contrib.auth import views as auth_views
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = [
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', auth_views.login, {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', auth_views.logout, {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
]
|
<commit_before>from django.conf.urls import patterns, url
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = patterns('',
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', 'django.contrib.auth.views.login', {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
)
<commit_msg>Resolve Django 1.10 deprecation warnings<commit_after>from django.conf.urls import url
from django.contrib.auth import views as auth_views
from .views import (DocumentationRecordListView, DocumentationRecordDetailView,
MaintenanceRecordDetailView, MaintenanceRecordListView,
system_maintenance_home_view)
urlpatterns = [
url(r'^$', system_maintenance_home_view, name='system_maintenance_home_view'),
url(r'^authentication/$', auth_views.login, {'template_name': 'system_maintenance/authentication.html'}, name='authentication'),
url(r'^documentation/$', DocumentationRecordListView.as_view(), name='documentation_record_list'),
url(r'^documentation/(?P<pk>\d+)/$', DocumentationRecordDetailView.as_view(), name='documentation_record_detail'),
url(r'^logout/$', auth_views.logout, {'next_page': '/system_maintenance/'}, name='logout'),
url(r'^records/$', MaintenanceRecordListView.as_view(), name='maintenance_record_list'),
url(r'^records/(?P<pk>\d+)/$', MaintenanceRecordDetailView.as_view(), name='maintenance_record_detail'),
]
|
e3d1805094ea3df86c94fdc116d1f718975a338e
|
src/me/maxwu/cistat/app/cistat.py
|
src/me/maxwu/cistat/app/cistat.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import json
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases: {}".format(report.get_cases_in_rate()[:10]))
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import pprint
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases:")
pprint.pprint(report.get_cases_in_rate()[:10])
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
|
Update sample task with pprint
|
Update sample task with pprint
|
Python
|
mit
|
maxwu/cistat,maxwu/cistat
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import json
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases: {}".format(report.get_cases_in_rate()[:10]))
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
Update sample task with pprint
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import pprint
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases:")
pprint.pprint(report.get_cases_in_rate()[:10])
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import json
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases: {}".format(report.get_cases_in_rate()[:10]))
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
<commit_msg>Update sample task with pprint<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import pprint
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases:")
pprint.pprint(report.get_cases_in_rate()[:10])
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import json
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases: {}".format(report.get_cases_in_rate()[:10]))
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
Update sample task with pprint#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import pprint
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases:")
pprint.pprint(report.get_cases_in_rate()[:10])
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import json
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases: {}".format(report.get_cases_in_rate()[:10]))
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
<commit_msg>Update sample task with pprint<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'maxwu'
import pprint
from me.maxwu.cistat import config
from me.maxwu.cistat.reqs.circleci_request import CircleCiReq
from me.maxwu.cistat.model.xunit_report import Xunitrpt
"""Main script file to provide configuration loading, cli_app and version.
"""
VERSION = "1.0"
def cli_app():
vcs, project, username = config.get_circleci_vcs(), config.get_circleci_project(), config.get_circleci_username()
urls = CircleCiReq.get_recent_artifacts(
token=config.get_circleci_token(),
vcs=vcs,
project=project,
username=username
)
report = Xunitrpt()
for artifact in urls:
print("fetching {}".format(artifact))
report += Xunitrpt(xunit=CircleCiReq.get_artifact_report(url=artifact))
print("Top 10 failure cases:")
pprint.pprint(report.get_cases_in_rate()[:10])
print("Plot Barchart of Pass Rate")
report.plot_barchart_rate(project, "Pass Rate per case")
if __name__ == '__main__':
cli_app()
|
3afa75c48d680111dc32368553cdc741eb0c07fa
|
imgfac/Singleton.py
|
imgfac/Singleton.py
|
# Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self):
pass
def _singleton_init(self):
"""Initialize a singleton instance before it is registered."""
pass
|
# Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self, *args, **kwargs):
pass
def _singleton_init(self, *args, **kwargs):
"""Initialize a singleton instance before it is registered."""
pass
|
Allow for parameters to __init__()
|
Allow for parameters to __init__()
Signed-off-by: Steve Loranz <749f95e2748aaf836ea2a030a8b369f33fe35144@redhat.com>
|
Python
|
apache-2.0
|
henrysher/imagefactory,LalatenduMohanty/imagefactory,jmcabandara/imagefactory,henrysher/imagefactory,redhat-imaging/imagefactory,jmcabandara/imagefactory,redhat-imaging/imagefactory,LalatenduMohanty/imagefactory
|
# Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self):
pass
def _singleton_init(self):
"""Initialize a singleton instance before it is registered."""
pass
Allow for parameters to __init__()
Signed-off-by: Steve Loranz <749f95e2748aaf836ea2a030a8b369f33fe35144@redhat.com>
|
# Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self, *args, **kwargs):
pass
def _singleton_init(self, *args, **kwargs):
"""Initialize a singleton instance before it is registered."""
pass
|
<commit_before># Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self):
pass
def _singleton_init(self):
"""Initialize a singleton instance before it is registered."""
pass
<commit_msg>Allow for parameters to __init__()
Signed-off-by: Steve Loranz <749f95e2748aaf836ea2a030a8b369f33fe35144@redhat.com><commit_after>
|
# Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self, *args, **kwargs):
pass
def _singleton_init(self, *args, **kwargs):
"""Initialize a singleton instance before it is registered."""
pass
|
# Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self):
pass
def _singleton_init(self):
"""Initialize a singleton instance before it is registered."""
pass
Allow for parameters to __init__()
Signed-off-by: Steve Loranz <749f95e2748aaf836ea2a030a8b369f33fe35144@redhat.com># Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self, *args, **kwargs):
pass
def _singleton_init(self, *args, **kwargs):
"""Initialize a singleton instance before it is registered."""
pass
|
<commit_before># Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self):
pass
def _singleton_init(self):
"""Initialize a singleton instance before it is registered."""
pass
<commit_msg>Allow for parameters to __init__()
Signed-off-by: Steve Loranz <749f95e2748aaf836ea2a030a8b369f33fe35144@redhat.com><commit_after># Copyright 2011 Red Hat, Inc.
#
# 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.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
instance._singleton_init(*args, **kwargs)
cls._instance = instance
elif args or kwargs:
cls._instance.log.warn('Attempted re-initialize of singleton: %s' % (cls._instance, ))
return cls._instance
def __init__(self, *args, **kwargs):
pass
def _singleton_init(self, *args, **kwargs):
"""Initialize a singleton instance before it is registered."""
pass
|
b8cf6f096e14ee7311c18117d57f98b1745b8105
|
pyuvdata/__init__.py
|
pyuvdata/__init__.py
|
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
__version__ = version.version
|
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
__version__ = version.version
|
Move warning filter above other imports in init
|
Move warning filter above other imports in init
|
Python
|
bsd-2-clause
|
HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata
|
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
__version__ = version.version
Move warning filter above other imports in init
|
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
__version__ = version.version
|
<commit_before># -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
__version__ = version.version
<commit_msg>Move warning filter above other imports in init<commit_after>
|
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
__version__ = version.version
|
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
__version__ = version.version
Move warning filter above other imports in init# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
__version__ = version.version
|
<commit_before># -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
__version__ = version.version
<commit_msg>Move warning filter above other imports in init<commit_after># -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
# Filter annoying Cython warnings that serve no good purpose. see numpy#432
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import *
from . import version
__version__ = version.version
|
675c7442b6fcee3fd9bd57d7a4ef68c7de23d48c
|
reddit_adzerk/adzerkkeywords.py
|
reddit_adzerk/adzerkkeywords.py
|
# Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.set("/keyword-targets", json.dumps(list(keyword_target)))
|
# Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
KEYWORD_NODE = "/keyword-targets"
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.ensure_path(KEYWORD_NODE)
g.zookeeper.set(KEYWORD_NODE, json.dumps(list(keyword_target)))
|
Create zookeeper node if it doesn't exist
|
Create zookeeper node if it doesn't exist
|
Python
|
bsd-3-clause
|
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
|
# Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.set("/keyword-targets", json.dumps(list(keyword_target)))
Create zookeeper node if it doesn't exist
|
# Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
KEYWORD_NODE = "/keyword-targets"
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.ensure_path(KEYWORD_NODE)
g.zookeeper.set(KEYWORD_NODE, json.dumps(list(keyword_target)))
|
<commit_before># Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.set("/keyword-targets", json.dumps(list(keyword_target)))
<commit_msg>Create zookeeper node if it doesn't exist<commit_after>
|
# Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
KEYWORD_NODE = "/keyword-targets"
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.ensure_path(KEYWORD_NODE)
g.zookeeper.set(KEYWORD_NODE, json.dumps(list(keyword_target)))
|
# Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.set("/keyword-targets", json.dumps(list(keyword_target)))
Create zookeeper node if it doesn't exist# Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
KEYWORD_NODE = "/keyword-targets"
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.ensure_path(KEYWORD_NODE)
g.zookeeper.set(KEYWORD_NODE, json.dumps(list(keyword_target)))
|
<commit_before># Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.set("/keyword-targets", json.dumps(list(keyword_target)))
<commit_msg>Create zookeeper node if it doesn't exist<commit_after># Polls Adzerk for current list of flights and saves the current targeting
# information to zookeeper (to be run periodically with upstart)
import adzerk_api
import json
from pylons import app_globals as g
KEYWORD_NODE = "/keyword-targets"
def update_global_keywords():
active_flights = adzerk_api.Flight.list(is_active=True)
keyword_target = set()
# Count the number of flights targeting each sub/keyword
for flight in active_flights:
for keyword_list in flight.Keywords.split('\n'):
for keyword in keyword_list.split(','):
ks = keyword.strip()
if ks.startswith('k.') or ks.startswith('!k.'):
keyword_target.add(ks)
# Store results in zookeeper
if g.zookeeper:
g.zookeeper.ensure_path(KEYWORD_NODE)
g.zookeeper.set(KEYWORD_NODE, json.dumps(list(keyword_target)))
|
92adf36a7aaf6d4741944b6c606f0cf4902f232d
|
letters/admin.py
|
letters/admin.py
|
from dal import autocomplete
from django import forms
from django.contrib import admin
from .models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
|
from dal import autocomplete
from django import forms
from django.contrib import admin
from letters.models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
"""Configure inline admin form for :class:`prosopography.models.Person` """
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
""":class:`prosopography.models.Person` admin inline for M2M."""
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
"""ModelAdmin for :class:`letters.models.Letter`"""
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
|
Add some documentation to letters
|
Add some documentation to letters
|
Python
|
mit
|
bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject
|
from dal import autocomplete
from django import forms
from django.contrib import admin
from .models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
Add some documentation to letters
|
from dal import autocomplete
from django import forms
from django.contrib import admin
from letters.models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
"""Configure inline admin form for :class:`prosopography.models.Person` """
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
""":class:`prosopography.models.Person` admin inline for M2M."""
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
"""ModelAdmin for :class:`letters.models.Letter`"""
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
|
<commit_before>from dal import autocomplete
from django import forms
from django.contrib import admin
from .models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
<commit_msg>Add some documentation to letters<commit_after>
|
from dal import autocomplete
from django import forms
from django.contrib import admin
from letters.models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
"""Configure inline admin form for :class:`prosopography.models.Person` """
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
""":class:`prosopography.models.Person` admin inline for M2M."""
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
"""ModelAdmin for :class:`letters.models.Letter`"""
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
|
from dal import autocomplete
from django import forms
from django.contrib import admin
from .models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
Add some documentation to lettersfrom dal import autocomplete
from django import forms
from django.contrib import admin
from letters.models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
"""Configure inline admin form for :class:`prosopography.models.Person` """
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
""":class:`prosopography.models.Person` admin inline for M2M."""
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
"""ModelAdmin for :class:`letters.models.Letter`"""
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
|
<commit_before>from dal import autocomplete
from django import forms
from django.contrib import admin
from .models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
<commit_msg>Add some documentation to letters<commit_after>from dal import autocomplete
from django import forms
from django.contrib import admin
from letters.models import Letter, Topic
from prosopography.models import Person
class PersonInlineForm(forms.ModelForm):
"""Configure inline admin form for :class:`prosopography.models.Person` """
class Meta:
model = Person.letters_to.through
fields = ('__all__')
widgets = {
'person': autocomplete.ModelSelect2(
url='people:dal-autocomplete',
attrs={
'data-placeholder': 'Type to search...',
'data-minimum-input-length': 2,
}
),
}
class PersonInline(admin.TabularInline):
""":class:`prosopography.models.Person` admin inline for M2M."""
model = Person.letters_to.through
form = PersonInlineForm
class LetterAdmin(admin.ModelAdmin):
"""ModelAdmin for :class:`letters.models.Letter`"""
model = Letter
inlines = [PersonInline]
fields = ('book', 'letter', 'topics', 'date', 'citations')
search_fields = ('book', 'letter', 'letters_to__nomina')
list_filter = ('book',)
filter_horizontal = ('citations',)
admin.site.register(Letter, LetterAdmin)
admin.site.register(Topic)
|
2118cc5efbe70a10c67ddf9b949607b243e05687
|
rest_framework_docs/api_docs.py
|
rest_framework_docs/api_docs.py
|
from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
if (hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)):
return True
return False
def get_endpoints(self):
return self.endpoints
|
from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
def get_endpoints(self):
return self.endpoints
|
Return conditional without using if/else to return boolean values
|
Return conditional without using if/else to return boolean values
In this case, since both methods in the conditional strictly returns boolean values, it is defintely safe and more pythonic to return the conditional
|
Python
|
bsd-2-clause
|
ekonstantinidis/django-rest-framework-docs,manosim/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,ekonstantinidis/django-rest-framework-docs,manosim/django-rest-framework-docs,manosim/django-rest-framework-docs
|
from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
if (hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)):
return True
return False
def get_endpoints(self):
return self.endpoints
Return conditional without using if/else to return boolean values
In this case, since both methods in the conditional strictly returns boolean values, it is defintely safe and more pythonic to return the conditional
|
from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
def get_endpoints(self):
return self.endpoints
|
<commit_before>from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
if (hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)):
return True
return False
def get_endpoints(self):
return self.endpoints
<commit_msg>Return conditional without using if/else to return boolean values
In this case, since both methods in the conditional strictly returns boolean values, it is defintely safe and more pythonic to return the conditional<commit_after>
|
from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
def get_endpoints(self):
return self.endpoints
|
from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
if (hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)):
return True
return False
def get_endpoints(self):
return self.endpoints
Return conditional without using if/else to return boolean values
In this case, since both methods in the conditional strictly returns boolean values, it is defintely safe and more pythonic to return the conditionalfrom django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
def get_endpoints(self):
return self.endpoints
|
<commit_before>from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
if (hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)):
return True
return False
def get_endpoints(self):
return self.endpoints
<commit_msg>Return conditional without using if/else to return boolean values
In this case, since both methods in the conditional strictly returns boolean values, it is defintely safe and more pythonic to return the conditional<commit_after>from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from rest_framework.views import APIView
from rest_framework_docs.api_endpoint import ApiEndpoint
class ApiDocumentation(object):
def __init__(self):
self.endpoints = []
root_urlconf = __import__(settings.ROOT_URLCONF)
if hasattr(root_urlconf, 'urls'):
self.get_all_view_names(root_urlconf.urls.urlpatterns)
else:
self.get_all_view_names(root_urlconf.urlpatterns)
def get_all_view_names(self, urlpatterns, parent_pattern=None):
for pattern in urlpatterns:
if isinstance(pattern, RegexURLResolver):
self.get_all_view_names(urlpatterns=pattern.url_patterns, parent_pattern=pattern)
elif isinstance(pattern, RegexURLPattern) and self._is_drf_view(pattern):
api_endpoint = ApiEndpoint(pattern, parent_pattern)
self.endpoints.append(api_endpoint)
def _is_drf_view(self, pattern):
# Should check whether a pattern inherits from DRF's APIView
return hasattr(pattern.callback, 'cls') and issubclass(pattern.callback.cls, APIView)
def get_endpoints(self):
return self.endpoints
|
19dfc716d31abaf2e82475b097d42d02bfc2259e
|
fuzza/data_broker.py
|
fuzza/data_broker.py
|
import glob
import io
class DataBroker(object):
"""
Read data and apply transformation to it as necessary.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
|
import glob
import io
class DataBroker(object):
"""
Read data from data files.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
@property
def data(self):
"""The list containing loaded data contents."""
return self._data
|
Add data property for DataBroker class
|
Add data property for DataBroker class
|
Python
|
mit
|
Raphx/fuzza
|
import glob
import io
class DataBroker(object):
"""
Read data and apply transformation to it as necessary.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
Add data property for DataBroker class
|
import glob
import io
class DataBroker(object):
"""
Read data from data files.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
@property
def data(self):
"""The list containing loaded data contents."""
return self._data
|
<commit_before>import glob
import io
class DataBroker(object):
"""
Read data and apply transformation to it as necessary.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
<commit_msg>Add data property for DataBroker class<commit_after>
|
import glob
import io
class DataBroker(object):
"""
Read data from data files.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
@property
def data(self):
"""The list containing loaded data contents."""
return self._data
|
import glob
import io
class DataBroker(object):
"""
Read data and apply transformation to it as necessary.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
Add data property for DataBroker classimport glob
import io
class DataBroker(object):
"""
Read data from data files.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
@property
def data(self):
"""The list containing loaded data contents."""
return self._data
|
<commit_before>import glob
import io
class DataBroker(object):
"""
Read data and apply transformation to it as necessary.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
<commit_msg>Add data property for DataBroker class<commit_after>import glob
import io
class DataBroker(object):
"""
Read data from data files.
Args:
config: A `dict` containing the fuzzer configurations.
Attributes:
_data_path: Path to data files as specified in configuration.
_data: A list of data loaded from data files.
"""
def __init__(self, config):
self._data_path = config.get('data_path')
self._data = []
def scan(self):
"""
Scan data path data files and store the data file content to
a data store.
The contents are currently loaded eagerly when this method is
invoked. Therefore, a large memory space may be required if
there are numerous data.
"""
for df in glob.iglob(self._data_path):
with io.open(df, 'rt', encoding='utf-8') as f:
self._data += f.read().splitlines()
@property
def data(self):
"""The list containing loaded data contents."""
return self._data
|
42476a41bf0cb1136340aba2dca9e9f9795f1cbd
|
genes/docker/main.py
|
genes/docker/main.py
|
from genes import apt
import platform
class Config:
OS = platform.system()
DIST = platform.linux_distribution()
def main():
if Config.OS == 'Linux':
if Config.DIST[0] == 'Ubuntu' or Config.DIST[0] == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
|
from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
Add install process for docker
|
Add install process for docker
|
Python
|
mit
|
hatchery/genepool,hatchery/Genepool2
|
from genes import apt
import platform
class Config:
OS = platform.system()
DIST = platform.linux_distribution()
def main():
if Config.OS == 'Linux':
if Config.DIST[0] == 'Ubuntu' or Config.DIST[0] == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
Add install process for docker
|
from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
<commit_before>from genes import apt
import platform
class Config:
OS = platform.system()
DIST = platform.linux_distribution()
def main():
if Config.OS == 'Linux':
if Config.DIST[0] == 'Ubuntu' or Config.DIST[0] == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
<commit_msg>Add install process for docker<commit_after>
|
from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
from genes import apt
import platform
class Config:
OS = platform.system()
DIST = platform.linux_distribution()
def main():
if Config.OS == 'Linux':
if Config.DIST[0] == 'Ubuntu' or Config.DIST[0] == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
Add install process for dockerfrom genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
<commit_before>from genes import apt
import platform
class Config:
OS = platform.system()
DIST = platform.linux_distribution()
def main():
if Config.OS == 'Linux':
if Config.DIST[0] == 'Ubuntu' or Config.DIST[0] == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
<commit_msg>Add install process for docker<commit_after>from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
ac9bde334394b05f24f1d3398662192e66328328
|
gitpress/building.py
|
gitpress/building.py
|
import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
directory = directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
|
import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(content_directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
content_directory = content_directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(content_directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, content_directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
|
Clarify argument name in build.
|
Clarify argument name in build.
|
Python
|
mit
|
joeyespo/gitpress
|
import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
directory = directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
Clarify argument name in build.
|
import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(content_directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
content_directory = content_directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(content_directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, content_directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
|
<commit_before>import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
directory = directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
<commit_msg>Clarify argument name in build.<commit_after>
|
import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(content_directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
content_directory = content_directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(content_directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, content_directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
|
import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
directory = directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
Clarify argument name in build.import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(content_directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
content_directory = content_directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(content_directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, content_directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
|
<commit_before>import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
directory = directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
<commit_msg>Clarify argument name in build.<commit_after>import os
from .repository import require_repo, presentation_files
from .helpers import copy_files, remove_directory
default_out_directory = '_site'
def build(content_directory=None, out_directory=None):
"""Builds the site from its content and presentation repository."""
content_directory = content_directory or '.'
out_directory = os.path.abspath(out_directory or default_out_directory)
repo = require_repo(content_directory)
# Prevent user mistakes
if out_directory == '.':
raise ValueError('Output directory must be different than the source directory: ' + repr(out_directory))
if os.path.basename(os.path.relpath(out_directory, content_directory)) == '..':
raise ValueError('Output directory must not contain the source directory: ' + repr(out_directory))
# TODO: read config
# TODO: use virtualenv
# TODO: init and run plugins
# TODO: process with active theme
# Collect and copy static files
files = presentation_files(repo)
remove_directory(out_directory)
copy_files(files, out_directory, repo)
return out_directory
|
c9229922772a4d7f92a26786d6ea441609043a09
|
tests/CrawlerRunner/ip_address.py
|
tests/CrawlerRunner/ip_address.py
|
from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
|
from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
if __name__ == "__main__":
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
|
Move code inside __main__ block
|
Tests: Move code inside __main__ block
|
Python
|
bsd-3-clause
|
starrify/scrapy,scrapy/scrapy,starrify/scrapy,starrify/scrapy,elacuesta/scrapy,elacuesta/scrapy,pablohoffman/scrapy,pablohoffman/scrapy,pawelmhm/scrapy,pawelmhm/scrapy,dangra/scrapy,dangra/scrapy,scrapy/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,dangra/scrapy,elacuesta/scrapy,scrapy/scrapy
|
from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
Tests: Move code inside __main__ block
|
from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
if __name__ == "__main__":
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
|
<commit_before>from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
<commit_msg>Tests: Move code inside __main__ block<commit_after>
|
from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
if __name__ == "__main__":
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
|
from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
Tests: Move code inside __main__ blockfrom urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
if __name__ == "__main__":
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
|
<commit_before>from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
<commit_msg>Tests: Move code inside __main__ block<commit_after>from urllib.parse import urlparse
from twisted.internet import reactor
from twisted.names.client import createResolver
from scrapy import Spider, Request
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from tests.mockserver import MockServer, MockDNSServer
class LocalhostSpider(Spider):
name = "localhost_spider"
def start_requests(self):
yield Request(self.url)
def parse(self, response):
netloc = urlparse(response.url).netloc
self.logger.info("Host: %s" % netloc.split(":")[0])
self.logger.info("Type: %s" % type(response.ip_address))
self.logger.info("IP address: %s" % response.ip_address)
if __name__ == "__main__":
with MockServer() as mock_http_server, MockDNSServer() as mock_dns_server:
port = urlparse(mock_http_server.http_address).port
url = "http://not.a.real.domain:{port}/echo".format(port=port)
servers = [(mock_dns_server.host, mock_dns_server.port)]
reactor.installResolver(createResolver(servers=servers))
configure_logging()
runner = CrawlerRunner()
d = runner.crawl(LocalhostSpider, url=url)
d.addBoth(lambda _: reactor.stop())
reactor.run()
|
b3fa14e85182d1b0efa47452de51d93a66c63503
|
tests/test_unstow.py
|
tests/test_unstow.py
|
import os
import steeve
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
|
import os
import steeve
def test_no_current(runner, foo_package):
"""Must fail when unstowing a package with no 'current' symlink."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 1
assert 'not stowed' in result.output
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
|
Test unstowing a package with no 'current' symlink
|
Test unstowing a package with no 'current' symlink
|
Python
|
bsd-3-clause
|
Perlence/steeve,Perlence/steeve
|
import os
import steeve
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
Test unstowing a package with no 'current' symlink
|
import os
import steeve
def test_no_current(runner, foo_package):
"""Must fail when unstowing a package with no 'current' symlink."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 1
assert 'not stowed' in result.output
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
|
<commit_before>import os
import steeve
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
<commit_msg>Test unstowing a package with no 'current' symlink<commit_after>
|
import os
import steeve
def test_no_current(runner, foo_package):
"""Must fail when unstowing a package with no 'current' symlink."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 1
assert 'not stowed' in result.output
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
|
import os
import steeve
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
Test unstowing a package with no 'current' symlinkimport os
import steeve
def test_no_current(runner, foo_package):
"""Must fail when unstowing a package with no 'current' symlink."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 1
assert 'not stowed' in result.output
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
|
<commit_before>import os
import steeve
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
<commit_msg>Test unstowing a package with no 'current' symlink<commit_after>import os
import steeve
def test_no_current(runner, foo_package):
"""Must fail when unstowing a package with no 'current' symlink."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 1
assert 'not stowed' in result.output
def test_unstow(runner, stowed_foo_package):
"""Must remove all previously linked files."""
result = runner.invoke(steeve.cli, ['unstow', 'foo'])
assert result.exit_code == 0
assert not os.path.exists(os.path.join('bin', 'foo'))
def test_strict(runner):
"""Must fail when trying to unstow nonstowed package."""
result = runner.invoke(steeve.cli, ['unstow', 'nonstowed'])
assert result.exit_code == 1
assert 'not stowed' in result.output
|
a18763fd8ecaa09d5d07d7bc5569fae55d9784f8
|
tests/v5/conftest.py
|
tests/v5/conftest.py
|
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
|
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
from tohu.v5.logging import logger
logger.setLevel('DEBUG')
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
|
Set logging level to DEBUG in tests
|
Set logging level to DEBUG in tests
|
Python
|
mit
|
maxalbert/tohu
|
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORSSet logging level to DEBUG in tests
|
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
from tohu.v5.logging import logger
logger.setLevel('DEBUG')
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
|
<commit_before>import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS<commit_msg>Set logging level to DEBUG in tests<commit_after>
|
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
from tohu.v5.logging import logger
logger.setLevel('DEBUG')
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
|
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORSSet logging level to DEBUG in testsimport pytest
from .context import tohu
from tohu.v5.primitive_generators import *
from tohu.v5.logging import logger
logger.setLevel('DEBUG')
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
|
<commit_before>import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS<commit_msg>Set logging level to DEBUG in tests<commit_after>import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
from tohu.v5.logging import logger
logger.setLevel('DEBUG')
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
|
1a4369c00ad927747a68b9a7f6e12d13020413fe
|
urls.py
|
urls.py
|
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
|
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/?$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
|
Make trailing slash optional in meal URLs
|
Make trailing slash optional in meal URLs
|
Python
|
mit
|
ntrrgc/lasana,ntrrgc/lasana,ntrrgc/lasana
|
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
Make trailing slash optional in meal URLs
|
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/?$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
|
<commit_before>from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
<commit_msg>Make trailing slash optional in meal URLs<commit_after>
|
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/?$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
|
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
Make trailing slash optional in meal URLsfrom django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/?$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
|
<commit_before>from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
<commit_msg>Make trailing slash optional in meal URLs<commit_after>from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.MealCreateView.as_view(), name='meal-create'),
url(r'^(?P<meal_id>[A-Z0-9]+)/?$', views.MealServeView.as_view(), name='meal-serve'),
url(r'^set_style/$', views.SetStyleView.as_view(), name='set-style'),
url(r'^api/v1/$', views.MealCreateAPIView.as_view()),
)
|
43ef10b1ea2ef5744b9558ff9c6afacdbfb1ee80
|
cacheops/__init__.py
|
cacheops/__init__.py
|
VERSION = (3, 2, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
|
__version__ = '3.2.1'
VERSION = tuple(__version__.split('.'))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
|
Use cacheops.__version__ as source of truth
|
Use cacheops.__version__ as source of truth
|
Python
|
bsd-3-clause
|
LPgenerator/django-cacheops,Suor/django-cacheops
|
VERSION = (3, 2, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
Use cacheops.__version__ as source of truth
|
__version__ = '3.2.1'
VERSION = tuple(__version__.split('.'))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
|
<commit_before>VERSION = (3, 2, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
<commit_msg>Use cacheops.__version__ as source of truth<commit_after>
|
__version__ = '3.2.1'
VERSION = tuple(__version__.split('.'))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
|
VERSION = (3, 2, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
Use cacheops.__version__ as source of truth__version__ = '3.2.1'
VERSION = tuple(__version__.split('.'))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
|
<commit_before>VERSION = (3, 2, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
<commit_msg>Use cacheops.__version__ as source of truth<commit_after>__version__ = '3.2.1'
VERSION = tuple(__version__.split('.'))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsConfig(AppConfig):
name = 'cacheops'
def ready(self):
install_cacheops()
install_cacheops_transaction_support()
default_app_config = 'cacheops.CacheopsConfig'
|
7c8a256f5d87ae70ac3f187f0010a8d66d8b95d5
|
seabird/modules/metar.py
|
seabird/modules/metar.py
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = ('http://weather.noaa.gov/pub/data'
'/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
Fix a line too long lint error
|
Fix a line too long lint error
|
Python
|
mit
|
belak/python-seabird,belak/pyseabird
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
Fix a line too long lint error
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = ('http://weather.noaa.gov/pub/data'
'/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
<commit_before>import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
<commit_msg>Fix a line too long lint error<commit_after>
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = ('http://weather.noaa.gov/pub/data'
'/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
Fix a line too long lint errorimport asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = ('http://weather.noaa.gov/pub/data'
'/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
<commit_before>import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = 'http://weather.noaa.gov/pub/data/observations/metar/stations/%s.TXT'
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
<commit_msg>Fix a line too long lint error<commit_after>import asyncio
import aiohttp
from seabird.decorators import command
from seabird.plugin import Plugin
METAR_URL = ('http://weather.noaa.gov/pub/data'
'/observations/metar/stations/%s.TXT')
class MetarPlugin(Plugin):
@command
def metar(self, msg):
"""<station>
Returns the METAR report given an airport code
"""
loop = asyncio.get_event_loop()
loop.create_task(self.metar_callback(msg))
async def metar_callback(self, msg):
loc = msg.trailing.upper()
if not loc.isalnum():
self.bot.mention_reply(msg, 'Not a valid airport code')
return
async with aiohttp.get(METAR_URL % loc) as resp:
if resp.status != 200:
self.bot.mention_reply(msg, 'Could not find data for station')
return
found = False
data = await resp.text()
for line in data.splitlines():
if line.startswith(loc):
found = True
self.bot.mention_reply(msg, line)
if not found:
self.bot.mention_reply(msg, 'No results')
|
66ae18a11290e73a996d1e2f2ba8018e29c0f92b
|
sheepdog_tables/forms.py
|
sheepdog_tables/forms.py
|
import logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
logger.warning("Editable table has no editable columns")
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
|
import logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
|
Remove logger warning in favor of print for now
|
Remove logger warning in favor of print for now
|
Python
|
bsd-3-clause
|
SheepDogInc/sheepdog_tables,SheepDogInc/sheepdog_tables
|
import logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
logger.warning("Editable table has no editable columns")
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
Remove logger warning in favor of print for now
|
import logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
|
<commit_before>import logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
logger.warning("Editable table has no editable columns")
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
<commit_msg>Remove logger warning in favor of print for now<commit_after>
|
import logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
|
import logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
logger.warning("Editable table has no editable columns")
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
Remove logger warning in favor of print for nowimport logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
|
<commit_before>import logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
logger.warning("Editable table has no editable columns")
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
<commit_msg>Remove logger warning in favor of print for now<commit_after>import logging
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Div, Submit
logger = logging.getLogger("sheepdog_tables")
class CSVExportForm(forms.Form):
id = forms.CharField(widget=forms.HiddenInput)
class EditTableSubmitForm(forms.Form):
def __init__(self, table, table_key, *args, **kwargs):
self.table = table
if not any([c.editable for c in self.table.table_columns.values()]):
print "Warning: Editable table has no editable columns"
super(EditTableSubmitForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'POST'
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Div(
HTML("<h4>Bulk Editing</h4>"),
HTML("<p>This will submit all fields in the table.</p>"),
Div(
Div(
Submit(
name='submit', value="Save",
data_edittable_form="edittable_%s" % table_key,
css_class="btn btn-primary"),
css_class="filter-btns btn-group"),
css_class="filter-btns-row btn-toolbar"),
css_class="well filtering-well"),
)
|
ae61346af8a813b6c0ecbb9f232f235ada982356
|
main.py
|
main.py
|
import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process():
accounts = Table('accounts')
target_date = date.isoformat(date.today())
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
q = playlists_queue()
for playlist in playlists_to_process():
body = json.dumps(dict(playlist.items()))
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
|
import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process(target_date):
accounts = Table('accounts')
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
date_to_process = date.isoformat(date.today())
q = playlists_queue()
for playlist in playlists_to_process(date_to_process):
data = dict(playlist.items())
body = json.dumps({
'spotify_username': data['spotify_username'],
'date_to_process': date_to_process
})
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
|
Send date to process in message
|
Send date to process in message
|
Python
|
mit
|
projectweekend/song-feed-queue-builder
|
import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process():
accounts = Table('accounts')
target_date = date.isoformat(date.today())
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
q = playlists_queue()
for playlist in playlists_to_process():
body = json.dumps(dict(playlist.items()))
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
Send date to process in message
|
import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process(target_date):
accounts = Table('accounts')
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
date_to_process = date.isoformat(date.today())
q = playlists_queue()
for playlist in playlists_to_process(date_to_process):
data = dict(playlist.items())
body = json.dumps({
'spotify_username': data['spotify_username'],
'date_to_process': date_to_process
})
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
|
<commit_before>import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process():
accounts = Table('accounts')
target_date = date.isoformat(date.today())
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
q = playlists_queue()
for playlist in playlists_to_process():
body = json.dumps(dict(playlist.items()))
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
<commit_msg>Send date to process in message<commit_after>
|
import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process(target_date):
accounts = Table('accounts')
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
date_to_process = date.isoformat(date.today())
q = playlists_queue()
for playlist in playlists_to_process(date_to_process):
data = dict(playlist.items())
body = json.dumps({
'spotify_username': data['spotify_username'],
'date_to_process': date_to_process
})
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
|
import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process():
accounts = Table('accounts')
target_date = date.isoformat(date.today())
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
q = playlists_queue()
for playlist in playlists_to_process():
body = json.dumps(dict(playlist.items()))
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
Send date to process in messageimport json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process(target_date):
accounts = Table('accounts')
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
date_to_process = date.isoformat(date.today())
q = playlists_queue()
for playlist in playlists_to_process(date_to_process):
data = dict(playlist.items())
body = json.dumps({
'spotify_username': data['spotify_username'],
'date_to_process': date_to_process
})
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
|
<commit_before>import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process():
accounts = Table('accounts')
target_date = date.isoformat(date.today())
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
q = playlists_queue()
for playlist in playlists_to_process():
body = json.dumps(dict(playlist.items()))
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
<commit_msg>Send date to process in message<commit_after>import json
from datetime import date
from boto import sqs
from boto.dynamodb2.table import Table
def playlists_to_process(target_date):
accounts = Table('accounts')
attributes = ('spotify_username', 'spotify_playlist_id', )
return accounts.scan(last_processed__ne=target_date, attributes=attributes)
def playlists_queue():
conn = sqs.connect_to_region('us-east-1')
return conn.create_queue('song-feed-playlists-to-process')
def main():
date_to_process = date.isoformat(date.today())
q = playlists_queue()
for playlist in playlists_to_process(date_to_process):
data = dict(playlist.items())
body = json.dumps({
'spotify_username': data['spotify_username'],
'date_to_process': date_to_process
})
q.write(q.new_message(body=body))
if __name__ == '__main__':
main()
|
5e97cc700886b071dbe645634604fdf473df1137
|
github/commands/create_fork.py
|
github/commands/create_fork.py
|
from sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log(("github: fork result:\n{}".format(result)))
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
|
from sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log({"github: fork result": result})
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
|
Fix logging the JSON result
|
Fix logging the JSON result
|
Python
|
mit
|
divmain/GitSavvy,divmain/GitSavvy,divmain/GitSavvy
|
from sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log(("github: fork result:\n{}".format(result)))
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
Fix logging the JSON result
|
from sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log({"github: fork result": result})
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
|
<commit_before>from sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log(("github: fork result:\n{}".format(result)))
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
<commit_msg>Fix logging the JSON result<commit_after>
|
from sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log({"github: fork result": result})
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
|
from sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log(("github: fork result:\n{}".format(result)))
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
Fix logging the JSON resultfrom sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log({"github: fork result": result})
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
|
<commit_before>from sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log(("github: fork result:\n{}".format(result)))
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
<commit_msg>Fix logging the JSON result<commit_after>from sublime_plugin import WindowCommand
from ...common import util
from ...core.git_command import GitCommand
from .. import github, git_mixins
from GitSavvy.core.runtime import enqueue_on_worker
START_CREATE_MESSAGE = "Forking {repo} ..."
END_CREATE_MESSAGE = "Fork created successfully."
__all__ = ['gs_github_create_fork']
class gs_github_create_fork(
WindowCommand,
git_mixins.GithubRemotesMixin,
GitCommand,
):
def run(self):
enqueue_on_worker(self.run_async)
def run_async(self):
remotes = self.get_remotes()
base_remote_name = self.get_integrated_remote_name(remotes)
base_remote_url = remotes[base_remote_name]
base_remote = github.parse_remote(base_remote_url)
self.window.status_message(START_CREATE_MESSAGE.format(repo=base_remote.url))
result = github.create_fork(base_remote)
self.window.status_message(END_CREATE_MESSAGE)
util.debug.add_to_log({"github: fork result": result})
url = (
result["ssh_url"]
if base_remote_url.startswith("git@")
else result["clone_url"]
)
self.window.run_command("gs_remote_add", {
"url": url,
"set_as_push_default": True
})
|
b24fa6443e70cca01ff5059fe29ba6e33c0262ea
|
pylisp/packet/ip/protocol.py
|
pylisp/packet/ip/protocol.py
|
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class Protocol(object):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
self.next_header = next_header
self.payload = payload
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return bytes(self.to_bytes())
|
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return self.to_bytes()
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
class Protocol(ProtocolElement):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
super(Protocol, self).__init__()
self.next_header = next_header
self.payload = payload
|
Split Protocol class in Protocol and ProtocolElement
|
Split Protocol class in Protocol and ProtocolElement
|
Python
|
bsd-3-clause
|
steffann/pylisp
|
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class Protocol(object):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
self.next_header = next_header
self.payload = payload
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return bytes(self.to_bytes())
Split Protocol class in Protocol and ProtocolElement
|
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return self.to_bytes()
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
class Protocol(ProtocolElement):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
super(Protocol, self).__init__()
self.next_header = next_header
self.payload = payload
|
<commit_before>'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class Protocol(object):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
self.next_header = next_header
self.payload = payload
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return bytes(self.to_bytes())
<commit_msg>Split Protocol class in Protocol and ProtocolElement<commit_after>
|
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return self.to_bytes()
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
class Protocol(ProtocolElement):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
super(Protocol, self).__init__()
self.next_header = next_header
self.payload = payload
|
'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class Protocol(object):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
self.next_header = next_header
self.payload = payload
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return bytes(self.to_bytes())
Split Protocol class in Protocol and ProtocolElement'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return self.to_bytes()
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
class Protocol(ProtocolElement):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
super(Protocol, self).__init__()
self.next_header = next_header
self.payload = payload
|
<commit_before>'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class Protocol(object):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
self.next_header = next_header
self.payload = payload
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return bytes(self.to_bytes())
<commit_msg>Split Protocol class in Protocol and ProtocolElement<commit_after>'''
Created on 11 jan. 2013
@author: sander
'''
from abc import abstractmethod, ABCMeta
class ProtocolElement(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
'''
Constructor
'''
def __repr__(self):
# This works as long as we accept all properties as paramters in the
# constructor
params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__,
', '.join(params))
def __str__(self):
return str(self.to_bytes())
def __bytes__(self):
return self.to_bytes()
@abstractmethod
def sanitize(self):
'''
Check and optionally fix properties
'''
@classmethod
@abstractmethod
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
@abstractmethod
def to_bytes(self):
'''
Create bytes from properties
'''
class Protocol(ProtocolElement):
__metaclass__ = ABCMeta
header_type = None
@abstractmethod
def __init__(self, next_header=None, payload=''):
'''
Constructor
'''
super(Protocol, self).__init__()
self.next_header = next_header
self.payload = payload
|
d5b18b7d0249cffabfab5f4c62696abe527af5ff
|
product/models.py
|
product/models.py
|
from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.name)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
|
from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.unit)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
|
Fix in string representation of unit of measurement.
|
Fix in string representation of unit of measurement.
|
Python
|
mit
|
borderitsolutions/amadaa,borderitsolutions/amadaa,borderitsolutions/amadaa
|
from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.name)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
Fix in string representation of unit of measurement.
|
from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.unit)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
|
<commit_before>from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.name)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
<commit_msg>Fix in string representation of unit of measurement.<commit_after>
|
from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.unit)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
|
from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.name)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
Fix in string representation of unit of measurement.from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.unit)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
|
<commit_before>from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.name)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
<commit_msg>Fix in string representation of unit of measurement.<commit_after>from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30)
def __str__(self):
return "%(self.unit)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
category = models.ForeignKey(ProductCategory)
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.