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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b2c2c5ea21b7f14820937276148c280303db241b | froide/frontpage/models.py | froide/frontpage/models.py | from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except self.model.DoesNotExist:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
| from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except (self.model.DoesNotExist, IndexError):
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
| Add IndexError to getFeatured call | Add IndexError to getFeatured call | Python | mit | stefanw/froide,LilithWittmann/froide,stefanw/froide,ryankanno/froide,ryankanno/froide,CodeforHawaii/froide,catcosmo/froide,CodeforHawaii/froide,stefanw/froide,ryankanno/froide,stefanw/froide,fin/froide,ryankanno/froide,okfse/froide,catcosmo/froide,CodeforHawaii/froide,catcosmo/froide,stefanw/froide,okfse/froide,okfse/froide,LilithWittmann/froide,LilithWittmann/froide,catcosmo/froide,LilithWittmann/froide,fin/froide,LilithWittmann/froide,okfse/froide,catcosmo/froide,okfse/froide,CodeforHawaii/froide,ryankanno/froide,fin/froide,CodeforHawaii/froide,fin/froide | from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except self.model.DoesNotExist:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
Add IndexError to getFeatured call | from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except (self.model.DoesNotExist, IndexError):
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
| <commit_before>from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except self.model.DoesNotExist:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
<commit_msg>Add IndexError to getFeatured call<commit_after> | from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except (self.model.DoesNotExist, IndexError):
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
| from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except self.model.DoesNotExist:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
Add IndexError to getFeatured callfrom django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except (self.model.DoesNotExist, IndexError):
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
| <commit_before>from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except self.model.DoesNotExist:
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
<commit_msg>Add IndexError to getFeatured call<commit_after>from django.db import models
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from foirequest.models import FoiRequest
class FeaturedRequestManager(CurrentSiteManager):
def getFeatured(self):
try:
return self.get_query_set().order_by("-timestamp").select_related('request', 'request__publicbody')[0]
except (self.model.DoesNotExist, IndexError):
return None
class FeaturedRequest(models.Model):
request = models.ForeignKey(FoiRequest,
verbose_name=_("Featured Request"))
timestamp = models.DateTimeField()
title = models.CharField(max_length=255)
text = models.TextField()
url = models.CharField(max_length=255, blank=True)
user = models.ForeignKey(User, null=True,
on_delete=models.SET_NULL,
verbose_name=_("User"))
site = models.ForeignKey(Site, null=True,
on_delete=models.SET_NULL, verbose_name=_("Site"))
objects = FeaturedRequestManager()
|
960d38d139895dcefa946e29655d5f6eee3c4cf5 | smileys/__init__.py | smileys/__init__.py | """django-emoticons"""
__version__ = '0.1'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/django-emoticons'
| Add package datas in the module, with the new name and repo | Add package datas in the module, with the new name and repo
| Python | bsd-3-clause | Fantomas42/django-emoticons,Fantomas42/django-emoticons | Add package datas in the module, with the new name and repo | """django-emoticons"""
__version__ = '0.1'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/django-emoticons'
| <commit_before><commit_msg>Add package datas in the module, with the new name and repo<commit_after> | """django-emoticons"""
__version__ = '0.1'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/django-emoticons'
| Add package datas in the module, with the new name and repo"""django-emoticons"""
__version__ = '0.1'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/django-emoticons'
| <commit_before><commit_msg>Add package datas in the module, with the new name and repo<commit_after>"""django-emoticons"""
__version__ = '0.1'
__license__ = 'BSD License'
__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'
__url__ = 'https://github.com/Fantomas42/django-emoticons'
| |
db81eaa5f05309be69f7b8d3aa12023c75387194 | fellowms/forms.py | fellowms/forms.py | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
| from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
| Fix public fields from Event | Fix public fields from Event
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
Fix public fields from Event | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
| <commit_before>from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
<commit_msg>Fix public fields from Event<commit_after> | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
| from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
Fix public fields from Eventfrom django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
| <commit_before>from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
<commit_msg>Fix public fields from Event<commit_after>from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
fields = '__all__'
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
widgets = {
'fellow': widgets.TextInput(),
}
labels = {
'fellow': 'Your email',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = ['status']
class BlogForm(ModelForm):
class Meta:
model = Blog
fields = '__all__'
|
480d15042af807cea3e7e182d4588dc3a2f93e92 | website/members/signals.py | website/members/signals.py | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.dispatch import receiver
from django.template import loader
from simple_email_confirmation import unconfirmed_email_created
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user or sender
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
| import datetime
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template import loader
from django.utils import timezone
from simple_email_confirmation import unconfirmed_email_created
from members.models import Member
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
@receiver(pre_save, sender=Member, dispatch_uid='member_check_membership')
def check_membership(sender, instance, **kwargs):
if timezone.now() - instance.status_changed > datetime.timedelta(1):
instance.update_status()
| Check membership when a Member is saved | Check membership when a Member is saved
| Python | agpl-3.0 | UTNkar/moore,Dekker1/moore,Dekker1/moore,UTNkar/moore,Dekker1/moore,UTNkar/moore,UTNkar/moore,Dekker1/moore | from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.dispatch import receiver
from django.template import loader
from simple_email_confirmation import unconfirmed_email_created
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user or sender
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
Check membership when a Member is saved | import datetime
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template import loader
from django.utils import timezone
from simple_email_confirmation import unconfirmed_email_created
from members.models import Member
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
@receiver(pre_save, sender=Member, dispatch_uid='member_check_membership')
def check_membership(sender, instance, **kwargs):
if timezone.now() - instance.status_changed > datetime.timedelta(1):
instance.update_status()
| <commit_before>from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.dispatch import receiver
from django.template import loader
from simple_email_confirmation import unconfirmed_email_created
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user or sender
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
<commit_msg>Check membership when a Member is saved<commit_after> | import datetime
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template import loader
from django.utils import timezone
from simple_email_confirmation import unconfirmed_email_created
from members.models import Member
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
@receiver(pre_save, sender=Member, dispatch_uid='member_check_membership')
def check_membership(sender, instance, **kwargs):
if timezone.now() - instance.status_changed > datetime.timedelta(1):
instance.update_status()
| from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.dispatch import receiver
from django.template import loader
from simple_email_confirmation import unconfirmed_email_created
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user or sender
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
Check membership when a Member is savedimport datetime
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template import loader
from django.utils import timezone
from simple_email_confirmation import unconfirmed_email_created
from members.models import Member
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
@receiver(pre_save, sender=Member, dispatch_uid='member_check_membership')
def check_membership(sender, instance, **kwargs):
if timezone.now() - instance.status_changed > datetime.timedelta(1):
instance.update_status()
| <commit_before>from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.dispatch import receiver
from django.template import loader
from simple_email_confirmation import unconfirmed_email_created
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user or sender
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
<commit_msg>Check membership when a Member is saved<commit_after>import datetime
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template import loader
from django.utils import timezone
from simple_email_confirmation import unconfirmed_email_created
from members.models import Member
@receiver(unconfirmed_email_created, dispatch_uid='send_email_confirmation')
def send_confirmation_email(sender, email, user=None, **kwargs):
member = user
context = {
'email': email,
'domain': settings.BASE_URL,
'site_name': settings.WAGTAIL_SITE_NAME,
'token': member.get_confirmation_key(email),
}
subject = loader.render_to_string(
'members/email_change_subject.txt', context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
body = loader.render_to_string('members/email_change_email.html',
context)
email_message = EmailMultiAlternatives(subject, body, None, [email])
email_message.send()
@receiver(pre_save, sender=Member, dispatch_uid='member_check_membership')
def check_membership(sender, instance, **kwargs):
if timezone.now() - instance.status_changed > datetime.timedelta(1):
instance.update_status()
|
54fddabcb1609755281adc54d6a71bea6c697f43 | parser.py | parser.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed URL:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry URL:\033[0m", item.link, "\n" | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed link:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry link:\033[0m", item.link, "\n" | Rename 'URL' to 'link' to match with .link property | Rename 'URL' to 'link' to match with .link property
| Python | mit | ZDroid/feedstyl | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed URL:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry URL:\033[0m", item.link, "\n"Rename 'URL' to 'link' to match with .link property | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed link:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry link:\033[0m", item.link, "\n" | <commit_before>#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed URL:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry URL:\033[0m", item.link, "\n"<commit_msg>Rename 'URL' to 'link' to match with .link property<commit_after> | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed link:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry link:\033[0m", item.link, "\n" | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed URL:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry URL:\033[0m", item.link, "\n"Rename 'URL' to 'link' to match with .link property#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed link:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry link:\033[0m", item.link, "\n" | <commit_before>#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed URL:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry URL:\033[0m", item.link, "\n"<commit_msg>Rename 'URL' to 'link' to match with .link property<commit_after>#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Script for displaying pretty RSS feeds
#
from sys import argv
import feedparser
# Data for parsing
data = feedparser.parse(argv[1])
# Display core feed properties
print "\n\033[1mFeed title:\033[0m", data.feed.title
if "description" in data.feed:
if len(data.feed.description) > 59:
data.feed.description = data.feed.description[:59] + "..."
print "\033[1mFeed description:\033[0m", data.feed.description
print "\033[1mFeed link:\033[0m", data.feed.link
# Display core items properties
print "\n\033[1mFeed entries:\033[0m\n"
for item in data.entries:
print " \033[1mEntry title:\033[0m", item.title
if "description" in item:
if len(item.description) > 54:
item.description = item.description[:54] + "..."
print " \033[1mEntry description:\033[0m", item.description
print " \033[1mEntry link:\033[0m", item.link, "\n" |
a7b247d7fc44518b58a91eeadc12ac418daf3889 | syncplay/__init__.py | syncplay/__init__.py | version = '1.6.7'
revision = ' development'
milestone = 'Yoitsu'
release_number = '92'
projectURL = 'https://syncplay.pl/'
| version = '1.6.7'
revision = ' beta 1'
milestone = 'Yoitsu'
release_number = '93'
projectURL = 'https://syncplay.pl/'
| Mark as 1.6.7 beta 1 | Mark as 1.6.7 beta 1 | Python | apache-2.0 | alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay,alby128/syncplay | version = '1.6.7'
revision = ' development'
milestone = 'Yoitsu'
release_number = '92'
projectURL = 'https://syncplay.pl/'
Mark as 1.6.7 beta 1 | version = '1.6.7'
revision = ' beta 1'
milestone = 'Yoitsu'
release_number = '93'
projectURL = 'https://syncplay.pl/'
| <commit_before>version = '1.6.7'
revision = ' development'
milestone = 'Yoitsu'
release_number = '92'
projectURL = 'https://syncplay.pl/'
<commit_msg>Mark as 1.6.7 beta 1<commit_after> | version = '1.6.7'
revision = ' beta 1'
milestone = 'Yoitsu'
release_number = '93'
projectURL = 'https://syncplay.pl/'
| version = '1.6.7'
revision = ' development'
milestone = 'Yoitsu'
release_number = '92'
projectURL = 'https://syncplay.pl/'
Mark as 1.6.7 beta 1version = '1.6.7'
revision = ' beta 1'
milestone = 'Yoitsu'
release_number = '93'
projectURL = 'https://syncplay.pl/'
| <commit_before>version = '1.6.7'
revision = ' development'
milestone = 'Yoitsu'
release_number = '92'
projectURL = 'https://syncplay.pl/'
<commit_msg>Mark as 1.6.7 beta 1<commit_after>version = '1.6.7'
revision = ' beta 1'
milestone = 'Yoitsu'
release_number = '93'
projectURL = 'https://syncplay.pl/'
|
fdf7f92a76fb6848f86194507b9a6fe8f0ab0171 | hours_slept_time_series.py | hours_slept_time_series.py | import plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
sleep_dates = []
nap_durations = []
nap_dates = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
sleep_dates.append(dt)
nap_durations.append(nap_total)
nap_dates.append(dt)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
| import plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
nap_durations = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
nap_durations.append(nap_total)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
| Remove unused |date| array variables | Remove unused |date| array variables
| Python | mit | f-jiang/sleep-pattern-grapher | import plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
sleep_dates = []
nap_durations = []
nap_dates = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
sleep_dates.append(dt)
nap_durations.append(nap_total)
nap_dates.append(dt)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
Remove unused |date| array variables | import plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
nap_durations = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
nap_durations.append(nap_total)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
| <commit_before>import plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
sleep_dates = []
nap_durations = []
nap_dates = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
sleep_dates.append(dt)
nap_durations.append(nap_total)
nap_dates.append(dt)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
<commit_msg>Remove unused |date| array variables<commit_after> | import plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
nap_durations = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
nap_durations.append(nap_total)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
| import plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
sleep_dates = []
nap_durations = []
nap_dates = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
sleep_dates.append(dt)
nap_durations.append(nap_total)
nap_dates.append(dt)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
Remove unused |date| array variablesimport plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
nap_durations = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
nap_durations.append(nap_total)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
| <commit_before>import plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
sleep_dates = []
nap_durations = []
nap_dates = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
sleep_dates.append(dt)
nap_durations.append(nap_total)
nap_dates.append(dt)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
<commit_msg>Remove unused |date| array variables<commit_after>import plotly as py
import plotly.graph_objs as go
from datetime import datetime
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
nap_durations = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap = r
delta_h = (wake - rest).seconds / 3600
if is_nap:
nap_total += delta_h
else:
sleep_total += delta_h
dt = datetime.combine(date, datetime.min.time())
sleep_durations.append(sleep_total)
nap_durations.append(nap_total)
dates = list(raw_data.keys())
sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
data = go.Data([sleep_trace, nap_trace])
layout = go.Layout(title=names.graph_title('Hours Slept per Day', dates),
yaxis={'title': 'Hours Slept', 'dtick': 1})
figure = go.Figure(data=data, layout=layout)
py.offline.plot(figure, filename=names.output_file_name(__file__, dates))
|
69ce80d9bbba46a7934802f4693877cb26903f99 | usingnamespace/api/traversal/v1/entries.py | usingnamespace/api/traversal/v1/entries.py | import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=False)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.site = self.site.first()
if not self.site:
raise ValueError('Unable to get validate site ID')
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
| import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=True)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
| Call parent with last set to True | Call parent with last set to True
This way we get __parent__.site set to a valid site, or it raises an
error.
We may want to change this in the future...
| Python | isc | usingnamespace/usingnamespace | import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=False)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.site = self.site.first()
if not self.site:
raise ValueError('Unable to get validate site ID')
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
Call parent with last set to True
This way we get __parent__.site set to a valid site, or it raises an
error.
We may want to change this in the future... | import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=True)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
| <commit_before>import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=False)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.site = self.site.first()
if not self.site:
raise ValueError('Unable to get validate site ID')
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
<commit_msg>Call parent with last set to True
This way we get __parent__.site set to a valid site, or it raises an
error.
We may want to change this in the future...<commit_after> | import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=True)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
| import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=False)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.site = self.site.first()
if not self.site:
raise ValueError('Unable to get validate site ID')
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
Call parent with last set to True
This way we get __parent__.site set to a valid site, or it raises an
error.
We may want to change this in the future...import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=True)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
| <commit_before>import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=False)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.site = self.site.first()
if not self.site:
raise ValueError('Unable to get validate site ID')
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
<commit_msg>Call parent with last set to True
This way we get __parent__.site set to a valid site, or it raises an
error.
We may want to change this in the future...<commit_after>import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=True)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
|
22db373a8b33b201a8964b3f518434289b2a57af | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
| from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
| Remove duplicate Flask-Login session protection setting | Remove duplicate Flask-Login session protection setting
| Python | mit | richgieg/flask-now,richgieg/flask-now | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
Remove duplicate Flask-Login session protection setting | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
| <commit_before>from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
<commit_msg>Remove duplicate Flask-Login session protection setting<commit_after> | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
| from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
Remove duplicate Flask-Login session protection settingfrom flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
| <commit_before>from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
<commit_msg>Remove duplicate Flask-Login session protection setting<commit_after>from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint, url_prefix='/auth')
return app
|
6321d2e86db0de359886f5e69509dad428778bbf | shop/management/commands/shopcustomers.py | shop/management/commands/shopcustomers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
option_list = BaseCommand.option_list + (
make_option("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions.")),
)
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
def add_arguments(self, parser):
parser.add_argument("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions."))
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
| Use the new django management commands definition (ArgumentParser) | Use the new django management commands definition (ArgumentParser)
| Python | bsd-3-clause | jrief/django-shop,jrief/django-shop,divio/django-shop,awesto/django-shop,nimbis/django-shop,nimbis/django-shop,khchine5/django-shop,awesto/django-shop,jrief/django-shop,nimbis/django-shop,awesto/django-shop,khchine5/django-shop,nimbis/django-shop,jrief/django-shop,divio/django-shop,khchine5/django-shop,divio/django-shop,khchine5/django-shop | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
option_list = BaseCommand.option_list + (
make_option("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions.")),
)
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
Use the new django management commands definition (ArgumentParser) | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
def add_arguments(self, parser):
parser.add_argument("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions."))
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
option_list = BaseCommand.option_list + (
make_option("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions.")),
)
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
<commit_msg>Use the new django management commands definition (ArgumentParser)<commit_after> | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
def add_arguments(self, parser):
parser.add_argument("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions."))
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
option_list = BaseCommand.option_list + (
make_option("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions.")),
)
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
Use the new django management commands definition (ArgumentParser)# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
def add_arguments(self, parser):
parser.add_argument("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions."))
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
option_list = BaseCommand.option_list + (
make_option("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions.")),
)
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
<commit_msg>Use the new django management commands definition (ArgumentParser)<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
class Command(BaseCommand):
help = _("Collect information about all customers which accessed this shop.")
def add_arguments(self, parser):
parser.add_argument("--delete-expired", action='store_true', dest='delete_expired',
help=_("Delete customers with expired sessions."))
def handle(self, verbosity, delete_expired, *args, **options):
from shop.models.customer import CustomerModel
data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0)
for customer in CustomerModel.objects.iterator():
data['total'] += 1
if customer.user.is_active:
data['active'] += 1
if customer.user.is_staff:
data['staff'] += 1
if customer.is_registered():
data['registered'] += 1
elif customer.is_guest():
data['guests'] += 1
elif customer.is_anonymous():
data['anonymous'] += 1
if customer.is_expired():
data['expired'] += 1
if delete_expired:
customer.delete()
msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.")
self.stdout.write(msg.format(**data))
|
4647183697170ce22910bd6cde27746297543514 | python3_tools/get_edx_webservices.py | python3_tools/get_edx_webservices.py | import github
from get_repos import *
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
| import github
from get_repos import orgs, expanded_repos_list, get_remote_yaml
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
| Add tooling to get all of edx's web services. | Add tooling to get all of edx's web services.
| Python | apache-2.0 | edx/repo-tools,edx/repo-tools | import github
from get_repos import *
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
Add tooling to get all of edx's web services. | import github
from get_repos import orgs, expanded_repos_list, get_remote_yaml
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
| <commit_before>import github
from get_repos import *
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
<commit_msg>Add tooling to get all of edx's web services.<commit_after> | import github
from get_repos import orgs, expanded_repos_list, get_remote_yaml
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
| import github
from get_repos import *
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
Add tooling to get all of edx's web services.import github
from get_repos import orgs, expanded_repos_list, get_remote_yaml
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
| <commit_before>import github
from get_repos import *
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
<commit_msg>Add tooling to get all of edx's web services.<commit_after>import github
from get_repos import orgs, expanded_repos_list, get_remote_yaml
webservices = []
for repo in expanded_repos_list(orgs):
try:
metadata = get_remote_yaml(repo, 'openedx.yaml')
except github.GithubException:
continue
if 'tags' in metadata and 'webservice' in metadata['tags']:
print("{}".format(repo.html_url))
webservices.append(repo)
|
e1985056a11ca3fff3896d2e4126b6cdf048336d | scrape_affiliation.py | scrape_affiliation.py | import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Error! Unhandled Journal Site {}".format(page.url))
return None
| import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
# The ACM author affiliations are stored in a kind of nasty table layout,
# best to view source or inspect element on their page for an explanation of this.
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Warning! Unhandled Journal Site {}".format(page.url))
return None
| Add comment on ACM affil structure | Add comment on ACM affil structure
| Python | mit | Twinklebear/dataviscourse-pr-collaboration-networks,Twinklebear/dataviscourse-pr-collaboration-networks,Twinklebear/dataviscourse-pr-collaboration-networks | import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Error! Unhandled Journal Site {}".format(page.url))
return None
Add comment on ACM affil structure | import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
# The ACM author affiliations are stored in a kind of nasty table layout,
# best to view source or inspect element on their page for an explanation of this.
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Warning! Unhandled Journal Site {}".format(page.url))
return None
| <commit_before>import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Error! Unhandled Journal Site {}".format(page.url))
return None
<commit_msg>Add comment on ACM affil structure<commit_after> | import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
# The ACM author affiliations are stored in a kind of nasty table layout,
# best to view source or inspect element on their page for an explanation of this.
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Warning! Unhandled Journal Site {}".format(page.url))
return None
| import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Error! Unhandled Journal Site {}".format(page.url))
return None
Add comment on ACM affil structureimport requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
# The ACM author affiliations are stored in a kind of nasty table layout,
# best to view source or inspect element on their page for an explanation of this.
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Warning! Unhandled Journal Site {}".format(page.url))
return None
| <commit_before>import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Error! Unhandled Journal Site {}".format(page.url))
return None
<commit_msg>Add comment on ACM affil structure<commit_after>import requests
from lxml import html, etree
def scrape_acm(page):
tree = html.fromstring(page.content)
author_affiliations = []
# The ACM author affiliations are stored in a kind of nasty table layout,
# best to view source or inspect element on their page for an explanation of this.
authors = tree.xpath('//td/a[@title="Author Profile Page"]')
for a in authors:
affiliation = a.getparent().getnext().find("a/small")
# If we don't find it under a URL it's likely just a <small>
if affiliation == None:
affiliation = a.getparent().getnext().find("small")
if affiliation:
affiliation = affiliation.text
else:
affiliation = "None"
author_affiliations.append(affiliation)
return author_affiliations
# Returns an array of the author affilations, ordered by the author appearance list on the paper
# e.g. first author, second author, etc. This is done because we can't assume the names in the DBLP
# database exactly match the names shown on the webpage.
def scrape_affiliation(doi):
# The doi urls are typically just http://dx.doi.org/... and we get the actual publication host
# by following the redirect, so we must hit the page before we know if we can handle the URL
# or not.
page = requests.get(doi)
if page.url.startswith("http://dl.acm.org/"):
return scrape_acm(page)
print("Warning! Unhandled Journal Site {}".format(page.url))
return None
|
457e220ec4a401325b5078c6561c4ca8634d8b60 | projecteuler/problems/problem_12.py | projecteuler/problems/problem_12.py | """Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
half = number / 2
number_plus = number + 1
factor_number = factor_count(half) + factor_count(number_plus)
if factor_number > 500:
answer = int(half * number_plus)
break
else:
half_plus = (number + 1) / 2
factor_number = factor_count(half_plus) * factor_count(number)
if factor_number > 500:
answer = int(half_plus * number)
break
return answer
| """Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
factor_one = number / 2
factor_two = number + 1
else:
factor_one = (number + 1) / 2
factor_two = number
total_factors = factor_count(factor_one) * factor_count(factor_two)
if total_factors > 500:
return int(factor_one * factor_two)
| Refactor problem 12 to increase test coverage | Refactor problem 12 to increase test coverage
| Python | mit | hjheath/ProjectEuler,heathy/ProjectEuler | """Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
half = number / 2
number_plus = number + 1
factor_number = factor_count(half) + factor_count(number_plus)
if factor_number > 500:
answer = int(half * number_plus)
break
else:
half_plus = (number + 1) / 2
factor_number = factor_count(half_plus) * factor_count(number)
if factor_number > 500:
answer = int(half_plus * number)
break
return answer
Refactor problem 12 to increase test coverage | """Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
factor_one = number / 2
factor_two = number + 1
else:
factor_one = (number + 1) / 2
factor_two = number
total_factors = factor_count(factor_one) * factor_count(factor_two)
if total_factors > 500:
return int(factor_one * factor_two)
| <commit_before>"""Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
half = number / 2
number_plus = number + 1
factor_number = factor_count(half) + factor_count(number_plus)
if factor_number > 500:
answer = int(half * number_plus)
break
else:
half_plus = (number + 1) / 2
factor_number = factor_count(half_plus) * factor_count(number)
if factor_number > 500:
answer = int(half_plus * number)
break
return answer
<commit_msg>Refactor problem 12 to increase test coverage<commit_after> | """Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
factor_one = number / 2
factor_two = number + 1
else:
factor_one = (number + 1) / 2
factor_two = number
total_factors = factor_count(factor_one) * factor_count(factor_two)
if total_factors > 500:
return int(factor_one * factor_two)
| """Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
half = number / 2
number_plus = number + 1
factor_number = factor_count(half) + factor_count(number_plus)
if factor_number > 500:
answer = int(half * number_plus)
break
else:
half_plus = (number + 1) / 2
factor_number = factor_count(half_plus) * factor_count(number)
if factor_number > 500:
answer = int(half_plus * number)
break
return answer
Refactor problem 12 to increase test coverage"""Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
factor_one = number / 2
factor_two = number + 1
else:
factor_one = (number + 1) / 2
factor_two = number
total_factors = factor_count(factor_one) * factor_count(factor_two)
if total_factors > 500:
return int(factor_one * factor_two)
| <commit_before>"""Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
half = number / 2
number_plus = number + 1
factor_number = factor_count(half) + factor_count(number_plus)
if factor_number > 500:
answer = int(half * number_plus)
break
else:
half_plus = (number + 1) / 2
factor_number = factor_count(half_plus) * factor_count(number)
if factor_number > 500:
answer = int(half_plus * number)
break
return answer
<commit_msg>Refactor problem 12 to increase test coverage<commit_after>"""Problem 12 of https://projecteuler.net"""
from projecteuler.maths_functions import factor_count
from itertools import count
def problem_12():
"""Solution to problem 12."""
# Triangle number can be defined as n(n+1)/2.
# n and n+1 share only the factor 1.
# Therefore the total number of factors of a triangle number is the product
# of the factors of n/2 and n+1 or (n+1)/2 and n depending on if n is
# even or odd.
for number in count():
if number % 2 == 0:
factor_one = number / 2
factor_two = number + 1
else:
factor_one = (number + 1) / 2
factor_two = number
total_factors = factor_count(factor_one) * factor_count(factor_two)
if total_factors > 500:
return int(factor_one * factor_two)
|
d60d4a039008775b80a56eda4830f06ab9250f2c | waterfall_wall/serializers.py | waterfall_wall/serializers.py | from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('url', 'nude_percent')
| from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('id', 'url', 'nude_percent')
| Add id in image API response | Add id in image API response
| Python | mit | carlcarl/rcard,carlcarl/rcard | from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('url', 'nude_percent')
Add id in image API response | from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('id', 'url', 'nude_percent')
| <commit_before>from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('url', 'nude_percent')
<commit_msg>Add id in image API response<commit_after> | from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('id', 'url', 'nude_percent')
| from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('url', 'nude_percent')
Add id in image API responsefrom django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('id', 'url', 'nude_percent')
| <commit_before>from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('url', 'nude_percent')
<commit_msg>Add id in image API response<commit_after>from django.contrib.auth.models import User, Group
from waterfall_wall.models import Image
from rest_framework import serializers
class ImageSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.SerializerMethodField()
def get_url(self, obj):
return obj.path.url
class Meta:
model = Image
fields = ('id', 'url', 'nude_percent')
|
88393283ff5e7f7720a98eda5eec8fa53b30f700 | grains/grains.py | grains/grains.py | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
| # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
if num == 1:
return 1
else:
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
| Add condition to avoid index error | Add condition to avoid index error
| Python | mit | amalshehu/exercism-python | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
Add condition to avoid index error | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
if num == 1:
return 1
else:
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
| <commit_before># File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
<commit_msg>Add condition to avoid index error<commit_after> | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
if num == 1:
return 1
else:
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
| # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
Add condition to avoid index error# File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
if num == 1:
return 1
else:
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
| <commit_before># File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
<commit_msg>Add condition to avoid index error<commit_after># File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in range(1, 65)]
grains = [2 ** x for x in range(0, 65)]
board = dict(zip(square, grains))
def on_square(num):
for k, v in board.iteritems():
if k == num:
return v
def total_after(num):
if num == 1:
return 1
else:
for k, v in board.iteritems():
if k == num:
total_after = sum(map(board.get, itertools.takewhile(lambda key: key != v, board)))
return total_after
print (board)
print (total_after(1))
print(on_square(1))
|
9accbde96f493ba795eef3d102a41aeecc039dce | grep_sal_code.py | grep_sal_code.py | #!/usr/bin/python
import argparse
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
for option in args.options or []:
cmd += ' -{}'.format(option)
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
return parser.parse_args()
if __name__ == "__main__":
main() | #!/usr/bin/python
import argparse
import os
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
options = args.options if args.options else []
for option in options:
cmd += ' -{}'.format(option)
if args.edit and 'l' not in options:
cmd += ' -l'
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
if args.edit:
subprocess.check_call([os.getenv('EDITOR')] + [l.strip() for l in results.splitlines()])
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
msg = 'Open files with matches in {}.'.format(os.getenv('EDITOR') or '<No EDITOR set>')
parser.add_argument('--edit', action='store_true', help=msg)
return parser.parse_args()
if __name__ == "__main__":
main() | Add straight-to-editor feature to grep script. | Add straight-to-editor feature to grep script.
| Python | apache-2.0 | sheagcraig/sal,salopensource/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal | #!/usr/bin/python
import argparse
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
for option in args.options or []:
cmd += ' -{}'.format(option)
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
return parser.parse_args()
if __name__ == "__main__":
main()Add straight-to-editor feature to grep script. | #!/usr/bin/python
import argparse
import os
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
options = args.options if args.options else []
for option in options:
cmd += ' -{}'.format(option)
if args.edit and 'l' not in options:
cmd += ' -l'
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
if args.edit:
subprocess.check_call([os.getenv('EDITOR')] + [l.strip() for l in results.splitlines()])
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
msg = 'Open files with matches in {}.'.format(os.getenv('EDITOR') or '<No EDITOR set>')
parser.add_argument('--edit', action='store_true', help=msg)
return parser.parse_args()
if __name__ == "__main__":
main() | <commit_before>#!/usr/bin/python
import argparse
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
for option in args.options or []:
cmd += ' -{}'.format(option)
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
return parser.parse_args()
if __name__ == "__main__":
main()<commit_msg>Add straight-to-editor feature to grep script.<commit_after> | #!/usr/bin/python
import argparse
import os
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
options = args.options if args.options else []
for option in options:
cmd += ' -{}'.format(option)
if args.edit and 'l' not in options:
cmd += ' -l'
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
if args.edit:
subprocess.check_call([os.getenv('EDITOR')] + [l.strip() for l in results.splitlines()])
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
msg = 'Open files with matches in {}.'.format(os.getenv('EDITOR') or '<No EDITOR set>')
parser.add_argument('--edit', action='store_true', help=msg)
return parser.parse_args()
if __name__ == "__main__":
main() | #!/usr/bin/python
import argparse
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
for option in args.options or []:
cmd += ' -{}'.format(option)
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
return parser.parse_args()
if __name__ == "__main__":
main()Add straight-to-editor feature to grep script.#!/usr/bin/python
import argparse
import os
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
options = args.options if args.options else []
for option in options:
cmd += ' -{}'.format(option)
if args.edit and 'l' not in options:
cmd += ' -l'
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
if args.edit:
subprocess.check_call([os.getenv('EDITOR')] + [l.strip() for l in results.splitlines()])
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
msg = 'Open files with matches in {}.'.format(os.getenv('EDITOR') or '<No EDITOR set>')
parser.add_argument('--edit', action='store_true', help=msg)
return parser.parse_args()
if __name__ == "__main__":
main() | <commit_before>#!/usr/bin/python
import argparse
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
for option in args.options or []:
cmd += ' -{}'.format(option)
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
return parser.parse_args()
if __name__ == "__main__":
main()<commit_msg>Add straight-to-editor feature to grep script.<commit_after>#!/usr/bin/python
import argparse
import os
import subprocess
import sys
EXCLUSIONS = ['*.pyc', '*.log', 'venv*', 'static/*', 'site_static/*', 'datatableview/*', '*.db']
def main():
args = parse_args()
# Normally we like to build subprocess commands in lists, but it's
# a lot easier to do all of the globbing we want with shell=True,
# so we'll build up a string.
cmd = 'grep -R --colour=always '
cmd += " ".join("--exclude='{}'".format(i) for i in EXCLUSIONS)
options = args.options if args.options else []
for option in options:
cmd += ' -{}'.format(option)
if args.edit and 'l' not in options:
cmd += ' -l'
cmd += " '{}'".format(r'\|'.join(args.search_terms))
cmd += ' *'
try:
results = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
# Most common error is that there are no results!
results = ''
print results.strip()
if args.edit:
subprocess.check_call([os.getenv('EDITOR')] + [l.strip() for l in results.splitlines()])
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('search_terms', nargs='*')
parser.add_argument('--options', nargs='*')
msg = 'Open files with matches in {}.'.format(os.getenv('EDITOR') or '<No EDITOR set>')
parser.add_argument('--edit', action='store_true', help=msg)
return parser.parse_args()
if __name__ == "__main__":
main() |
647707293524440f014ed0a3ef7d4322a96775e4 | tests/example_app/flask_app.py | tests/example_app/flask_app.py | import flask
from pale.adapters import flask as pale_flask_adapter
from tests.example_app import api
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
| import flask
from pale.adapters import flask as pale_flask_adapter
from pale.config import authenticator, context_creator
from tests.example_app import api
@authenticator
def authenticate_pale_context(context):
"""Don't actually authenticate anything in this test."""
return context
@context_creator
def create_pale_context(endpoint,request):
return pale_flask_adapter.DefaultFlaskContext(endpoint, request)
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
| Add authenticator and context creator to example app | Add authenticator and context creator to example app
| Python | mit | Loudr/pale | import flask
from pale.adapters import flask as pale_flask_adapter
from tests.example_app import api
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
Add authenticator and context creator to example app | import flask
from pale.adapters import flask as pale_flask_adapter
from pale.config import authenticator, context_creator
from tests.example_app import api
@authenticator
def authenticate_pale_context(context):
"""Don't actually authenticate anything in this test."""
return context
@context_creator
def create_pale_context(endpoint,request):
return pale_flask_adapter.DefaultFlaskContext(endpoint, request)
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
| <commit_before>import flask
from pale.adapters import flask as pale_flask_adapter
from tests.example_app import api
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
<commit_msg>Add authenticator and context creator to example app<commit_after> | import flask
from pale.adapters import flask as pale_flask_adapter
from pale.config import authenticator, context_creator
from tests.example_app import api
@authenticator
def authenticate_pale_context(context):
"""Don't actually authenticate anything in this test."""
return context
@context_creator
def create_pale_context(endpoint,request):
return pale_flask_adapter.DefaultFlaskContext(endpoint, request)
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
| import flask
from pale.adapters import flask as pale_flask_adapter
from tests.example_app import api
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
Add authenticator and context creator to example appimport flask
from pale.adapters import flask as pale_flask_adapter
from pale.config import authenticator, context_creator
from tests.example_app import api
@authenticator
def authenticate_pale_context(context):
"""Don't actually authenticate anything in this test."""
return context
@context_creator
def create_pale_context(endpoint,request):
return pale_flask_adapter.DefaultFlaskContext(endpoint, request)
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
| <commit_before>import flask
from pale.adapters import flask as pale_flask_adapter
from tests.example_app import api
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
<commit_msg>Add authenticator and context creator to example app<commit_after>import flask
from pale.adapters import flask as pale_flask_adapter
from pale.config import authenticator, context_creator
from tests.example_app import api
@authenticator
def authenticate_pale_context(context):
"""Don't actually authenticate anything in this test."""
return context
@context_creator
def create_pale_context(endpoint,request):
return pale_flask_adapter.DefaultFlaskContext(endpoint, request)
def create_pale_flask_app():
"""Creates a flask app, and registers a blueprint bound to pale."""
blueprint = flask.Blueprint('api', 'tests.example_app')
pale_flask_adapter.bind_blueprint(api, blueprint)
app = flask.Flask(__name__)
app.register_blueprint(blueprint, url_prefix='/api')
return app
|
1df4a955e80fc82cc88c049e2d9a606845cfb326 | azure-mgmt-resource/azure/mgmt/resource/__init__.py | azure-mgmt-resource/azure/mgmt/resource/__init__.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ManagedApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ManagedApplicationClient'
]
| # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ApplicationClient'
]
| Update alias ManagedApplicationClient to ApplicationClient | Update alias ManagedApplicationClient to ApplicationClient | Python | mit | Azure/azure-sdk-for-python,AutorestCI/azure-sdk-for-python,Azure/azure-sdk-for-python,Azure/azure-sdk-for-python,Azure/azure-sdk-for-python,lmazuel/azure-sdk-for-python | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ManagedApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ManagedApplicationClient'
]
Update alias ManagedApplicationClient to ApplicationClient | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ApplicationClient'
]
| <commit_before># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ManagedApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ManagedApplicationClient'
]
<commit_msg>Update alias ManagedApplicationClient to ApplicationClient<commit_after> | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ApplicationClient'
]
| # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ManagedApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ManagedApplicationClient'
]
Update alias ManagedApplicationClient to ApplicationClient# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ApplicationClient'
]
| <commit_before># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ManagedApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ManagedApplicationClient'
]
<commit_msg>Update alias ManagedApplicationClient to ApplicationClient<commit_after># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .features import FeatureClient
from .locks import ManagementLockClient
from .policy import PolicyClient
from .resources import ResourceManagementClient
from .subscriptions import SubscriptionClient
from .links import ManagementLinkClient
from .managedapplications import ApplicationClient
from .version import VERSION
__version__ = VERSION
__all__ = [
'FeatureClient',
'ManagementLockClient',
'PolicyClient',
'ResourceManagementClient',
'SubscriptionClient',
'ManagementLinkClient',
'ApplicationClient'
]
|
1ec5327918e11f76cb3d0dd2699585433d4d6058 | reddit_adzerk/__init__.py | reddit_adzerk/__init__.py | from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit': Module('reddit.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
| from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit-init': Module('reddit-init.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
| Move adzerk.js into reddit-init to fix race condition. | Move adzerk.js into reddit-init to fix race condition.
This should ensure that the Adzerk postMessage receiver is loaded before
Adzerk gets its payloads.
| Python | bsd-3-clause | madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk | from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit': Module('reddit.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
Move adzerk.js into reddit-init to fix race condition.
This should ensure that the Adzerk postMessage receiver is loaded before
Adzerk gets its payloads. | from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit-init': Module('reddit-init.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
| <commit_before>from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit': Module('reddit.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
<commit_msg>Move adzerk.js into reddit-init to fix race condition.
This should ensure that the Adzerk postMessage receiver is loaded before
Adzerk gets its payloads.<commit_after> | from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit-init': Module('reddit-init.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
| from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit': Module('reddit.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
Move adzerk.js into reddit-init to fix race condition.
This should ensure that the Adzerk postMessage receiver is loaded before
Adzerk gets its payloads.from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit-init': Module('reddit-init.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
| <commit_before>from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit': Module('reddit.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
<commit_msg>Move adzerk.js into reddit-init to fix race condition.
This should ensure that the Adzerk postMessage receiver is loaded before
Adzerk gets its payloads.<commit_after>from r2.lib.plugin import Plugin
from r2.lib.js import Module
class Adzerk(Plugin):
needs_static_build = True
js = {
'reddit-init': Module('reddit-init.js',
'adzerk/adzerk.js',
)
}
def load_controllers(self):
# replace the standard Ads view with an Adzerk specific one.
import r2.lib.pages.pages
from adzerkads import Ads as AdzerkAds
r2.lib.pages.pages.Ads = AdzerkAds
|
4227b5fb52c58304f993d2def11aeb1ed4d5a157 | src/urldecorators/urlresolvers.py | src/urldecorators/urlresolvers.py |
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
callback, args, kwargs = match
callback = self.apply_decorators(callback)
return callback, args, kwargs
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
|
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
try:
# In Django 1.3 match is an instance of ResolverMatch class
match.func = self.apply_decorators(match.func)
except AttributeError:
# Before Django 1.3 match is a tuple
match = self.apply_decorators(match[0]), match[1], match[2]
return match
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
| Fix for the new ResolverMatch object in Django 1.3. | Fix for the new ResolverMatch object in Django 1.3.
| Python | bsd-3-clause | mila/django-urldecorators,mila/django-urldecorators |
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
callback, args, kwargs = match
callback = self.apply_decorators(callback)
return callback, args, kwargs
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
Fix for the new ResolverMatch object in Django 1.3. |
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
try:
# In Django 1.3 match is an instance of ResolverMatch class
match.func = self.apply_decorators(match.func)
except AttributeError:
# Before Django 1.3 match is a tuple
match = self.apply_decorators(match[0]), match[1], match[2]
return match
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
| <commit_before>
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
callback, args, kwargs = match
callback = self.apply_decorators(callback)
return callback, args, kwargs
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
<commit_msg>Fix for the new ResolverMatch object in Django 1.3.<commit_after> |
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
try:
# In Django 1.3 match is an instance of ResolverMatch class
match.func = self.apply_decorators(match.func)
except AttributeError:
# Before Django 1.3 match is a tuple
match = self.apply_decorators(match[0]), match[1], match[2]
return match
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
|
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
callback, args, kwargs = match
callback = self.apply_decorators(callback)
return callback, args, kwargs
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
Fix for the new ResolverMatch object in Django 1.3.
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
try:
# In Django 1.3 match is an instance of ResolverMatch class
match.func = self.apply_decorators(match.func)
except AttributeError:
# Before Django 1.3 match is a tuple
match = self.apply_decorators(match[0]), match[1], match[2]
return match
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
| <commit_before>
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
callback, args, kwargs = match
callback = self.apply_decorators(callback)
return callback, args, kwargs
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
<commit_msg>Fix for the new ResolverMatch object in Django 1.3.<commit_after>
import types
from django.core import urlresolvers as django_urlresolvers
from django.utils.functional import curry
class DecoratorMixin(object):
"""
Mixin class to return decorated views from RegexURLPattern/RegexURLResolver
"""
def __init__(self, *args, **kwargs):
super(DecoratorMixin, self).__init__(*args, **kwargs)
self.decorators = []
def resolve(self, path):
match = super(DecoratorMixin, self).resolve(path)
if not match:
return match
try:
# In Django 1.3 match is an instance of ResolverMatch class
match.func = self.apply_decorators(match.func)
except AttributeError:
# Before Django 1.3 match is a tuple
match = self.apply_decorators(match[0]), match[1], match[2]
return match
def apply_decorators(self, callback):
if not isinstance(callback, types.FunctionType):
callback = curry(callback) # Some decorators do not work with class views
for decorator in self.decorators:
callback = decorator(callback)
return callback
class RegexURLPattern(DecoratorMixin, django_urlresolvers.RegexURLPattern):
pass
class RegexURLResolver(DecoratorMixin, django_urlresolvers.RegexURLResolver):
pass
|
48f281127eb1adf2c1a88dee3759cec41fb95924 | gears/finders.py | gears/finders.py | import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
| import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches if all else None
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
| Fix FileSystemFinder's find return value if not all | Fix FileSystemFinder's find return value if not all
| Python | isc | gears/gears,gears/gears,gears/gears | import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
Fix FileSystemFinder's find return value if not all | import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches if all else None
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
| <commit_before>import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
<commit_msg>Fix FileSystemFinder's find return value if not all<commit_after> | import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches if all else None
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
| import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
Fix FileSystemFinder's find return value if not allimport os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches if all else None
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
| <commit_before>import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
<commit_msg>Fix FileSystemFinder's find return value if not all<commit_after>import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches if all else None
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
|
9aafe3ded97aee0f8f3623f0de1c13cfb555d7a6 | getwork_store.py | getwork_store.py | import time
class Getwork_store:
def __init__(self):
self.data = {}
def add(self, server, merkle_root):
self.data[merkle_root] = {'name':server["name"], 'timestamp':time.time()}
return
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root]['name']
return None
def prune(self):
for key, work in self.data.items():
if work['timestamp'] < (time.time() - (60*5)):
del self.data[key]
return
| #License#
#bitHopper by Colin Rice is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#Based on a work at github.com.
import time
from twisted.internet.task import LoopingCall
class Getwork_store:
def __init__(self):
self.data = {}
call = LoopingCall(self.prune)
call.start(60)
def add(self, server, merkle_root):
self.data[merkle_root] = [server["name"], time.time()]
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root][0]
return None
def prune(self):
for key, work in self.data.items():
if work[1] < (time.time() - (60*5)):
del self.data[key]
| Update getwork to prune itself and use a list instead of a dictionary | Update getwork to prune itself and use a list instead of a dictionary
| Python | mit | c00w/bitHopper,c00w/bitHopper | import time
class Getwork_store:
def __init__(self):
self.data = {}
def add(self, server, merkle_root):
self.data[merkle_root] = {'name':server["name"], 'timestamp':time.time()}
return
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root]['name']
return None
def prune(self):
for key, work in self.data.items():
if work['timestamp'] < (time.time() - (60*5)):
del self.data[key]
return
Update getwork to prune itself and use a list instead of a dictionary | #License#
#bitHopper by Colin Rice is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#Based on a work at github.com.
import time
from twisted.internet.task import LoopingCall
class Getwork_store:
def __init__(self):
self.data = {}
call = LoopingCall(self.prune)
call.start(60)
def add(self, server, merkle_root):
self.data[merkle_root] = [server["name"], time.time()]
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root][0]
return None
def prune(self):
for key, work in self.data.items():
if work[1] < (time.time() - (60*5)):
del self.data[key]
| <commit_before>import time
class Getwork_store:
def __init__(self):
self.data = {}
def add(self, server, merkle_root):
self.data[merkle_root] = {'name':server["name"], 'timestamp':time.time()}
return
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root]['name']
return None
def prune(self):
for key, work in self.data.items():
if work['timestamp'] < (time.time() - (60*5)):
del self.data[key]
return
<commit_msg>Update getwork to prune itself and use a list instead of a dictionary<commit_after> | #License#
#bitHopper by Colin Rice is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#Based on a work at github.com.
import time
from twisted.internet.task import LoopingCall
class Getwork_store:
def __init__(self):
self.data = {}
call = LoopingCall(self.prune)
call.start(60)
def add(self, server, merkle_root):
self.data[merkle_root] = [server["name"], time.time()]
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root][0]
return None
def prune(self):
for key, work in self.data.items():
if work[1] < (time.time() - (60*5)):
del self.data[key]
| import time
class Getwork_store:
def __init__(self):
self.data = {}
def add(self, server, merkle_root):
self.data[merkle_root] = {'name':server["name"], 'timestamp':time.time()}
return
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root]['name']
return None
def prune(self):
for key, work in self.data.items():
if work['timestamp'] < (time.time() - (60*5)):
del self.data[key]
return
Update getwork to prune itself and use a list instead of a dictionary#License#
#bitHopper by Colin Rice is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#Based on a work at github.com.
import time
from twisted.internet.task import LoopingCall
class Getwork_store:
def __init__(self):
self.data = {}
call = LoopingCall(self.prune)
call.start(60)
def add(self, server, merkle_root):
self.data[merkle_root] = [server["name"], time.time()]
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root][0]
return None
def prune(self):
for key, work in self.data.items():
if work[1] < (time.time() - (60*5)):
del self.data[key]
| <commit_before>import time
class Getwork_store:
def __init__(self):
self.data = {}
def add(self, server, merkle_root):
self.data[merkle_root] = {'name':server["name"], 'timestamp':time.time()}
return
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root]['name']
return None
def prune(self):
for key, work in self.data.items():
if work['timestamp'] < (time.time() - (60*5)):
del self.data[key]
return
<commit_msg>Update getwork to prune itself and use a list instead of a dictionary<commit_after>#License#
#bitHopper by Colin Rice is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#Based on a work at github.com.
import time
from twisted.internet.task import LoopingCall
class Getwork_store:
def __init__(self):
self.data = {}
call = LoopingCall(self.prune)
call.start(60)
def add(self, server, merkle_root):
self.data[merkle_root] = [server["name"], time.time()]
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
return self.data[merkle_root][0]
return None
def prune(self):
for key, work in self.data.items():
if work[1] < (time.time() - (60*5)):
del self.data[key]
|
b16016994f20945a8a2bbb63b9cb920d856ab66f | web/attempts/migrations/0008_add_submission_date.py | web/attempts/migrations/0008_add_submission_date.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = (
SELECT max(history_date)
FROM attempts_historicalattempt
WHERE attempts_attempt.user_id = user_id
AND attempts_attempt.part_id = part_id
)
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = subquery.submission_date
FROM (
SELECT user_id, part_id, max(history_date) AS submission_date
FROM attempts_historicalattempt
GROUP BY user_id, part_id
) AS subquery
WHERE attempts_attempt.user_id = subquery.user_id
AND attempts_attempt.part_id = subquery.part_id
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
| Revert "Make migration SQLite compatible" | Revert "Make migration SQLite compatible"
This reverts commit 768d85cccb17c8757dd8d14dad220d0b87568264.
| Python | agpl-3.0 | ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = (
SELECT max(history_date)
FROM attempts_historicalattempt
WHERE attempts_attempt.user_id = user_id
AND attempts_attempt.part_id = part_id
)
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
Revert "Make migration SQLite compatible"
This reverts commit 768d85cccb17c8757dd8d14dad220d0b87568264. | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = subquery.submission_date
FROM (
SELECT user_id, part_id, max(history_date) AS submission_date
FROM attempts_historicalattempt
GROUP BY user_id, part_id
) AS subquery
WHERE attempts_attempt.user_id = subquery.user_id
AND attempts_attempt.part_id = subquery.part_id
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
| <commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = (
SELECT max(history_date)
FROM attempts_historicalattempt
WHERE attempts_attempt.user_id = user_id
AND attempts_attempt.part_id = part_id
)
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
<commit_msg>Revert "Make migration SQLite compatible"
This reverts commit 768d85cccb17c8757dd8d14dad220d0b87568264.<commit_after> | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = subquery.submission_date
FROM (
SELECT user_id, part_id, max(history_date) AS submission_date
FROM attempts_historicalattempt
GROUP BY user_id, part_id
) AS subquery
WHERE attempts_attempt.user_id = subquery.user_id
AND attempts_attempt.part_id = subquery.part_id
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = (
SELECT max(history_date)
FROM attempts_historicalattempt
WHERE attempts_attempt.user_id = user_id
AND attempts_attempt.part_id = part_id
)
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
Revert "Make migration SQLite compatible"
This reverts commit 768d85cccb17c8757dd8d14dad220d0b87568264.# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = subquery.submission_date
FROM (
SELECT user_id, part_id, max(history_date) AS submission_date
FROM attempts_historicalattempt
GROUP BY user_id, part_id
) AS subquery
WHERE attempts_attempt.user_id = subquery.user_id
AND attempts_attempt.part_id = subquery.part_id
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
| <commit_before># -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = (
SELECT max(history_date)
FROM attempts_historicalattempt
WHERE attempts_attempt.user_id = user_id
AND attempts_attempt.part_id = part_id
)
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
<commit_msg>Revert "Make migration SQLite compatible"
This reverts commit 768d85cccb17c8757dd8d14dad220d0b87568264.<commit_after># -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-05-09 09:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attempts', '0007_auto_20161004_0927'),
]
operations = [
migrations.AddField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.AddField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(null=True),
),
migrations.RunSQL(
'UPDATE attempts_historicalattempt SET submission_date = history_date'
),
migrations.RunSQL(
'''UPDATE attempts_attempt
SET submission_date = subquery.submission_date
FROM (
SELECT user_id, part_id, max(history_date) AS submission_date
FROM attempts_historicalattempt
GROUP BY user_id, part_id
) AS subquery
WHERE attempts_attempt.user_id = subquery.user_id
AND attempts_attempt.part_id = subquery.part_id
'''
),
migrations.AlterField(
model_name='attempt',
name='submission_date',
field=models.DateTimeField(auto_now=True),
),
migrations.AlterField(
model_name='historicalattempt',
name='submission_date',
field=models.DateTimeField(blank=True, editable=False),
),
]
|
5283bddb36bf4016609c130ddbe63cb234dceb73 | tools/ocd_restore.py | tools/ocd_restore.py | #!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
jurisdiction = args.jurisdiction
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
with cd(args.root):
print os.getcwd()
| #!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import sys
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
TABLES = {
"ocd-jurisdiction": db.jurisdictions,
"ocd-bill": db.bills,
"ocd-organization": db.organizations,
"ocd-person": db.people,
"ocd-vote": db.votes,
}
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
def insert(obj):
id_ = obj['_id']
etype, _ = id_.split("/", 1)
sys.stdout.write(etype.split("-")[1][0].lower())
sys.stdout.flush()
return TABLES[etype].save(obj)
with cd(args.root):
# OK. Let's load stuff up.
for path, dirs, nodes in os.walk("."):
for entry in (os.path.join(path, x) for x in nodes):
data = json.load(open(entry, 'r'))
insert(data)
| Add more to the restore script. | Add more to the restore script.
| Python | bsd-3-clause | influence-usa/pupa,datamade/pupa,influence-usa/pupa,rshorey/pupa,opencivicdata/pupa,mileswwatkins/pupa,opencivicdata/pupa,rshorey/pupa,mileswwatkins/pupa,datamade/pupa | #!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
jurisdiction = args.jurisdiction
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
with cd(args.root):
print os.getcwd()
Add more to the restore script. | #!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import sys
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
TABLES = {
"ocd-jurisdiction": db.jurisdictions,
"ocd-bill": db.bills,
"ocd-organization": db.organizations,
"ocd-person": db.people,
"ocd-vote": db.votes,
}
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
def insert(obj):
id_ = obj['_id']
etype, _ = id_.split("/", 1)
sys.stdout.write(etype.split("-")[1][0].lower())
sys.stdout.flush()
return TABLES[etype].save(obj)
with cd(args.root):
# OK. Let's load stuff up.
for path, dirs, nodes in os.walk("."):
for entry in (os.path.join(path, x) for x in nodes):
data = json.load(open(entry, 'r'))
insert(data)
| <commit_before>#!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
jurisdiction = args.jurisdiction
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
with cd(args.root):
print os.getcwd()
<commit_msg>Add more to the restore script.<commit_after> | #!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import sys
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
TABLES = {
"ocd-jurisdiction": db.jurisdictions,
"ocd-bill": db.bills,
"ocd-organization": db.organizations,
"ocd-person": db.people,
"ocd-vote": db.votes,
}
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
def insert(obj):
id_ = obj['_id']
etype, _ = id_.split("/", 1)
sys.stdout.write(etype.split("-")[1][0].lower())
sys.stdout.flush()
return TABLES[etype].save(obj)
with cd(args.root):
# OK. Let's load stuff up.
for path, dirs, nodes in os.walk("."):
for entry in (os.path.join(path, x) for x in nodes):
data = json.load(open(entry, 'r'))
insert(data)
| #!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
jurisdiction = args.jurisdiction
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
with cd(args.root):
print os.getcwd()
Add more to the restore script.#!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import sys
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
TABLES = {
"ocd-jurisdiction": db.jurisdictions,
"ocd-bill": db.bills,
"ocd-organization": db.organizations,
"ocd-person": db.people,
"ocd-vote": db.votes,
}
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
def insert(obj):
id_ = obj['_id']
etype, _ = id_.split("/", 1)
sys.stdout.write(etype.split("-")[1][0].lower())
sys.stdout.flush()
return TABLES[etype].save(obj)
with cd(args.root):
# OK. Let's load stuff up.
for path, dirs, nodes in os.walk("."):
for entry in (os.path.join(path, x) for x in nodes):
data = json.load(open(entry, 'r'))
insert(data)
| <commit_before>#!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
jurisdiction = args.jurisdiction
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
with cd(args.root):
print os.getcwd()
<commit_msg>Add more to the restore script.<commit_after>#!/usr/bin/env python
from pupa.utils import JSONEncoderPlus
from contextlib import contextmanager
from pymongo import Connection
import argparse
import json
import sys
import os
parser = argparse.ArgumentParser(description='Re-convert a jurisdiction.')
parser.add_argument('--server', type=str, help='Mongo Server',
default="localhost")
parser.add_argument('--database', type=str, help='Mongo Database',
default="opencivicdata")
parser.add_argument('--port', type=int, help='Mongo Server Port',
default=27017)
parser.add_argument('--output', type=str, help='Output Directory',
default="dump")
parser.add_argument('root', type=str, help='root', default='dump')
args = parser.parse_args()
connection = Connection(args.server, args.port)
db = getattr(connection, args.database)
TABLES = {
"ocd-jurisdiction": db.jurisdictions,
"ocd-bill": db.bills,
"ocd-organization": db.organizations,
"ocd-person": db.people,
"ocd-vote": db.votes,
}
@contextmanager
def cd(path):
pop = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(pop)
def insert(obj):
id_ = obj['_id']
etype, _ = id_.split("/", 1)
sys.stdout.write(etype.split("-")[1][0].lower())
sys.stdout.flush()
return TABLES[etype].save(obj)
with cd(args.root):
# OK. Let's load stuff up.
for path, dirs, nodes in os.walk("."):
for entry in (os.path.join(path, x) for x in nodes):
data = json.load(open(entry, 'r'))
insert(data)
|
9663799d57a2790417e7d2fb9b1672de4d3a0059 | search.py | search.py | import io
import getopt
import sys
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
| import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
| Implement loading of dictionary and postings list | Implement loading of dictionary and postings list
| Python | mit | ikaruswill/vector-space-model,ikaruswill/boolean-retrieval | import io
import getopt
import sys
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
Implement loading of dictionary and postings list | import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
| <commit_before>import io
import getopt
import sys
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
<commit_msg>Implement loading of dictionary and postings list<commit_after> | import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
| import io
import getopt
import sys
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
Implement loading of dictionary and postings listimport io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
| <commit_before>import io
import getopt
import sys
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
<commit_msg>Implement loading of dictionary and postings list<commit_after>import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
|
231902d06b1f7fe3bcd7318f933427cdd3c17d6e | trace_viewer/trace_viewer_project.py | trace_viewer/trace_viewer_project.py | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self):
super(TraceViewerProject, self).__init__(
[self.src_path, self.jszip_path])
| # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self, other_paths=None):
paths = [self.src_path, self.jszip_path]
if other_paths:
paths.extend(other_paths)
super(TraceViewerProject, self).__init__(
paths)
| Allow other_paths to be passed into TraceViewerProject | Allow other_paths to be passed into TraceViewerProject
This allows external embedders to subclass TraceViewerProject and thus
use trace viewer.
git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@1198 0e6d7f2b-9903-5b78-7403-59d27f066143
| Python | bsd-3-clause | bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self):
super(TraceViewerProject, self).__init__(
[self.src_path, self.jszip_path])
Allow other_paths to be passed into TraceViewerProject
This allows external embedders to subclass TraceViewerProject and thus
use trace viewer.
git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@1198 0e6d7f2b-9903-5b78-7403-59d27f066143 | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self, other_paths=None):
paths = [self.src_path, self.jszip_path]
if other_paths:
paths.extend(other_paths)
super(TraceViewerProject, self).__init__(
paths)
| <commit_before># Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self):
super(TraceViewerProject, self).__init__(
[self.src_path, self.jszip_path])
<commit_msg>Allow other_paths to be passed into TraceViewerProject
This allows external embedders to subclass TraceViewerProject and thus
use trace viewer.
git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@1198 0e6d7f2b-9903-5b78-7403-59d27f066143<commit_after> | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self, other_paths=None):
paths = [self.src_path, self.jszip_path]
if other_paths:
paths.extend(other_paths)
super(TraceViewerProject, self).__init__(
paths)
| # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self):
super(TraceViewerProject, self).__init__(
[self.src_path, self.jszip_path])
Allow other_paths to be passed into TraceViewerProject
This allows external embedders to subclass TraceViewerProject and thus
use trace viewer.
git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@1198 0e6d7f2b-9903-5b78-7403-59d27f066143# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self, other_paths=None):
paths = [self.src_path, self.jszip_path]
if other_paths:
paths.extend(other_paths)
super(TraceViewerProject, self).__init__(
paths)
| <commit_before># Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self):
super(TraceViewerProject, self).__init__(
[self.src_path, self.jszip_path])
<commit_msg>Allow other_paths to be passed into TraceViewerProject
This allows external embedders to subclass TraceViewerProject and thus
use trace viewer.
git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@1198 0e6d7f2b-9903-5b78-7403-59d27f066143<commit_after># Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import os
from tvcm import project as project_module
class TraceViewerProject(project_module.Project):
trace_viewer_path = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))
src_path = os.path.abspath(os.path.join(
trace_viewer_path, 'trace_viewer'))
trace_viewer_third_party_path = os.path.abspath(os.path.join(
trace_viewer_path, 'third_party'))
jszip_path = os.path.abspath(os.path.join(
trace_viewer_third_party_path, 'jszip'))
test_data_path = os.path.join(trace_viewer_path, 'test_data')
skp_data_path = os.path.join(trace_viewer_path, 'skp_data')
def __init__(self, other_paths=None):
paths = [self.src_path, self.jszip_path]
if other_paths:
paths.extend(other_paths)
super(TraceViewerProject, self).__init__(
paths)
|
d924576329c4a1d7814be2ed7da3ddd96a108c47 | TotalFile.py | TotalFile.py | # -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(ur"£\s*([0-9\.,]{1,9})\s(.*)", line)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
except ValueError:
cleaned.append(line)
total = sum(numbers)
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
| # -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(u"£\s*([0-9\.,]{1,9})\s*(.*)", line, re.U)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
else:
cleaned.append(line)
except ValueError:
cleaned.append(line)
total = sum(numbers)
if (len(cleaned) > 0):
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
| Handle non-matching lines which don't cause match errors and don't clean the empty lines if there are no cleaned lines | Handle non-matching lines which don't cause match errors and don't clean the empty lines if there are no cleaned lines
| Python | mit | RichardHyde/SublimeText.Packages | # -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(ur"£\s*([0-9\.,]{1,9})\s(.*)", line)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
except ValueError:
cleaned.append(line)
total = sum(numbers)
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
Handle non-matching lines which don't cause match errors and don't clean the empty lines if there are no cleaned lines | # -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(u"£\s*([0-9\.,]{1,9})\s*(.*)", line, re.U)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
else:
cleaned.append(line)
except ValueError:
cleaned.append(line)
total = sum(numbers)
if (len(cleaned) > 0):
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
| <commit_before># -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(ur"£\s*([0-9\.,]{1,9})\s(.*)", line)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
except ValueError:
cleaned.append(line)
total = sum(numbers)
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
<commit_msg>Handle non-matching lines which don't cause match errors and don't clean the empty lines if there are no cleaned lines<commit_after> | # -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(u"£\s*([0-9\.,]{1,9})\s*(.*)", line, re.U)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
else:
cleaned.append(line)
except ValueError:
cleaned.append(line)
total = sum(numbers)
if (len(cleaned) > 0):
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
| # -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(ur"£\s*([0-9\.,]{1,9})\s(.*)", line)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
except ValueError:
cleaned.append(line)
total = sum(numbers)
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
Handle non-matching lines which don't cause match errors and don't clean the empty lines if there are no cleaned lines# -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(u"£\s*([0-9\.,]{1,9})\s*(.*)", line, re.U)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
else:
cleaned.append(line)
except ValueError:
cleaned.append(line)
total = sum(numbers)
if (len(cleaned) > 0):
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
| <commit_before># -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(ur"£\s*([0-9\.,]{1,9})\s(.*)", line)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
except ValueError:
cleaned.append(line)
total = sum(numbers)
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
<commit_msg>Handle non-matching lines which don't cause match errors and don't clean the empty lines if there are no cleaned lines<commit_after># -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class TotalFileCommand(sublime_plugin.TextCommand):
def run(self, edit):
cleaned = []
numbers = []
region = sublime.Region(0, self.view.size());
for lineRegion in self.view.lines(region):
line = self.view.substr(lineRegion)
if (line == ""):
break
try:
m = re.match(u"£\s*([0-9\.,]{1,9})\s*(.*)", line, re.U)
if (m):
cost = float(m.group(1).strip(' '))
numbers.append(cost)
desc = m.group(2)
cleaned.append(u"£{0:>9.2f} {1}".format(cost, desc))
else:
cleaned.append(line)
except ValueError:
cleaned.append(line)
total = sum(numbers)
if (len(cleaned) > 0):
while cleaned[-1].strip() == '':
del cleaned[-1]
cleaned.append("")
cleaned.append(u"£{0:>9.2f} Total".format(total))
cleaned = '\n'.join(cleaned)
#edit = self.view.begin_edit("")
self.view.erase(edit, region)
self.view.insert(edit, 0, cleaned)
#self.view.end_edit(edit)
|
02b87b94e07626a5db5ef548b234c270e5fb05e0 | kboard/board/urls.py | kboard/board/urls.py | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
| # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
| Delete board_slug parameter on 'delete_post' url | Delete board_slug parameter on 'delete_post' url
| Python | mit | guswnsxodlf/k-board,cjh5414/kboard,hyesun03/k-board,hyesun03/k-board,cjh5414/kboard,hyesun03/k-board,kboard/kboard,guswnsxodlf/k-board,kboard/kboard,cjh5414/kboard,darjeeling/k-board,kboard/kboard,guswnsxodlf/k-board | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
Delete board_slug parameter on 'delete_post' url | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
| <commit_before># Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
<commit_msg>Delete board_slug parameter on 'delete_post' url<commit_after> | # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
| # Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
Delete board_slug parameter on 'delete_post' url# Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
| <commit_before># Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
<commit_msg>Delete board_slug parameter on 'delete_post' url<commit_after># Created by JHJ on 2016. 10. 5.
from django.conf.urls import url
from . import views
app_name = 'board'
urlpatterns = [
url(r'^$', views.board_list, name='board_list'),
url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'),
url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'),
url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'),
url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'),
url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'),
]
|
f0a20db6da65b82ddafd22effbc0d5a7bb17f9e6 | Roman-Numerals/Roman.py | Roman-Numerals/Roman.py | class Roman(object):
def __init__(self, number):
self.number = number
self.modern_convert()
convert_table = {}
def modern_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(15)
| class Roman(object):
def __init__(self, number):
self.number = int(number)
choice = raw_input("Type Y or N for modern Roman Numeral Convert: ").lower()
while True:
if choice == "y":
print "You made it"
elif choice == "n":
self.old_roman_convert()
break
else:
print "Please Type Y or N!"
(self, self.number)
play_again = raw_input("Do you want to enter another number? Please type yes or no: ").lower()
if play_again == "no":
print "Thanks for Playing!"
else:
Roman(raw_input("Enter another number! "))
def old_roman_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(raw_input("Enter a number to be converted into Roman Numberal Form: "))
| Add loops in __init__ for continuous convert | Add loops in __init__ for continuous convert
| Python | mit | Bigless27/Python-Projects | class Roman(object):
def __init__(self, number):
self.number = number
self.modern_convert()
convert_table = {}
def modern_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(15)
Add loops in __init__ for continuous convert | class Roman(object):
def __init__(self, number):
self.number = int(number)
choice = raw_input("Type Y or N for modern Roman Numeral Convert: ").lower()
while True:
if choice == "y":
print "You made it"
elif choice == "n":
self.old_roman_convert()
break
else:
print "Please Type Y or N!"
(self, self.number)
play_again = raw_input("Do you want to enter another number? Please type yes or no: ").lower()
if play_again == "no":
print "Thanks for Playing!"
else:
Roman(raw_input("Enter another number! "))
def old_roman_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(raw_input("Enter a number to be converted into Roman Numberal Form: "))
| <commit_before>class Roman(object):
def __init__(self, number):
self.number = number
self.modern_convert()
convert_table = {}
def modern_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(15)
<commit_msg>Add loops in __init__ for continuous convert<commit_after> | class Roman(object):
def __init__(self, number):
self.number = int(number)
choice = raw_input("Type Y or N for modern Roman Numeral Convert: ").lower()
while True:
if choice == "y":
print "You made it"
elif choice == "n":
self.old_roman_convert()
break
else:
print "Please Type Y or N!"
(self, self.number)
play_again = raw_input("Do you want to enter another number? Please type yes or no: ").lower()
if play_again == "no":
print "Thanks for Playing!"
else:
Roman(raw_input("Enter another number! "))
def old_roman_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(raw_input("Enter a number to be converted into Roman Numberal Form: "))
| class Roman(object):
def __init__(self, number):
self.number = number
self.modern_convert()
convert_table = {}
def modern_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(15)
Add loops in __init__ for continuous convertclass Roman(object):
def __init__(self, number):
self.number = int(number)
choice = raw_input("Type Y or N for modern Roman Numeral Convert: ").lower()
while True:
if choice == "y":
print "You made it"
elif choice == "n":
self.old_roman_convert()
break
else:
print "Please Type Y or N!"
(self, self.number)
play_again = raw_input("Do you want to enter another number? Please type yes or no: ").lower()
if play_again == "no":
print "Thanks for Playing!"
else:
Roman(raw_input("Enter another number! "))
def old_roman_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(raw_input("Enter a number to be converted into Roman Numberal Form: "))
| <commit_before>class Roman(object):
def __init__(self, number):
self.number = number
self.modern_convert()
convert_table = {}
def modern_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(15)
<commit_msg>Add loops in __init__ for continuous convert<commit_after>class Roman(object):
def __init__(self, number):
self.number = int(number)
choice = raw_input("Type Y or N for modern Roman Numeral Convert: ").lower()
while True:
if choice == "y":
print "You made it"
elif choice == "n":
self.old_roman_convert()
break
else:
print "Please Type Y or N!"
(self, self.number)
play_again = raw_input("Do you want to enter another number? Please type yes or no: ").lower()
if play_again == "no":
print "Thanks for Playing!"
else:
Roman(raw_input("Enter another number! "))
def old_roman_convert(self):
number = self.number
solution = []
while True:
if number >= 1000:
solution.append("M")
number -= 1000
elif number >= 500:
solution.append("D")
number -= 500
elif number >= 100:
solution.append("C")
number -= 100
elif number >=50:
solution.append("L")
number -= 50
elif number >= 10:
solution.append("X")
number -= 10
elif number >= 5:
solution.append("V")
number -= 5
elif number >= 1:
soution.append("I")
number -= 1
else:
break
print "".join(solution)
return
number = Roman(raw_input("Enter a number to be converted into Roman Numberal Form: "))
|
cb774e9950510b559bdccc25d368eccc7b42cb06 | server.py | server.py | import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({results:results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({'results':results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| Change the key to be string | Change the key to be string
| Python | mit | noppanit/street-parking-nyc | import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({results:results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
Change the key to be string | import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({'results':results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| <commit_before>import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({results:results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
<commit_msg>Change the key to be string<commit_after> | import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({'results':results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({results:results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
Change the key to be stringimport os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({'results':results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| <commit_before>import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({results:results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
<commit_msg>Change the key to be string<commit_after>import os
from flask import Flask, request
import psycopg2
import json
app = Flask(__name__)
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL)
@app.route('/find')
def find():
lat = request.args.get('lat')
lng = request.args.get('lng')
radius = request.args.get('radius')
cursor = conn.cursor()
query = 'SELECT * from signs WHERE earth_box(ll_to_earth(%s, %s), %s) @> ll_to_earth(latitude, longtitude);'
cursor.execute(query, (lat, lng, radius))
columns = ['longtitude', 'latitude', 'object_id', 'sg_key_bor', 'sg_order_n', 'sg_seqno_n', 'sg_mutcd_c', 'sr_dist', 'sg_sign_fc', 'sg_arrow_d', 'x', 'y', 'signdesc']
results = []
for row in cursor.fetchall():
results.append(dict(zip(columns, row)))
return json.dumps({'results':results})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
|
2ac185e96c4a6af91ab3df9d53f4436cd257a5fc | test/scripts/test_entanglement.py | test/scripts/test_entanglement.py | #!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
| #!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
#ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
| Disable viewing the plasm in test. | Disable viewing the plasm in test.
| Python | bsd-3-clause | stonier/ecto,v4hn/ecto,stonier/ecto,drmateo/ecto,drmateo/ecto,drmateo/ecto,stonier/ecto,v4hn/ecto,v4hn/ecto,drmateo/ecto,stonier/ecto,v4hn/ecto,drmateo/ecto | #!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
Disable viewing the plasm in test. | #!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
#ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
| <commit_before>#!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
<commit_msg>Disable viewing the plasm in test.<commit_after> | #!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
#ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
| #!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
Disable viewing the plasm in test.#!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
#ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
| <commit_before>#!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
<commit_msg>Disable viewing the plasm in test.<commit_after>#!/usr/bin/env python
import ecto
import ecto_test
def test_feedback():
plasm = ecto.Plasm()
g = ecto_test.Generate("Generator", step=1.0, start=1.0)
add = ecto_test.Add()
source,sink = ecto.EntangledPair()
plasm.connect(source[:] >> add['left'],
g[:] >> add['right'],
add[:] >> sink[:]
)
#ecto.view_plasm(plasm)
plasm.execute(niter=1)
assert add.outputs.out == 1 # 0 + 1 = 1
plasm.execute(niter=1)
assert add.outputs.out == 3 # 1 + 2 = 3
plasm.execute(niter=1)
assert add.outputs.out == 6 # 3 + 3 = 6
plasm.execute(niter=1)
assert add.outputs.out == 10 # 6 + 4 = 10
if __name__ == '__main__':
test_feedback()
|
9e4ca0829bcd7b3d5181bb452c80fb99c41f9820 | source/tyr/tyr/rabbit_mq_handler.py | source/tyr/tyr/rabbit_mq_handler.py | # encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
self._connection.release()
| # encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
| Fix error message 'ChannelError: channel disconnected' | Fix error message 'ChannelError: channel disconnected'
| Python | agpl-3.0 | patochectp/navitia,ballouche/navitia,ballouche/navitia,CanalTP/navitia,patochectp/navitia,kinnou02/navitia,antoine-de/navitia,antoine-de/navitia,patochectp/navitia,pbougue/navitia,xlqian/navitia,pbougue/navitia,xlqian/navitia,Tisseo/navitia,CanalTP/navitia,CanalTP/navitia,ballouche/navitia,Tisseo/navitia,ballouche/navitia,kinnou02/navitia,xlqian/navitia,kadhikari/navitia,antoine-de/navitia,Tisseo/navitia,kadhikari/navitia,pbougue/navitia,patochectp/navitia,xlqian/navitia,pbougue/navitia,Tisseo/navitia,CanalTP/navitia,kinnou02/navitia,kadhikari/navitia,Tisseo/navitia,kadhikari/navitia,xlqian/navitia,kinnou02/navitia,antoine-de/navitia,CanalTP/navitia | # encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
self._connection.release()
Fix error message 'ChannelError: channel disconnected' | # encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
| <commit_before># encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
self._connection.release()
<commit_msg>Fix error message 'ChannelError: channel disconnected'<commit_after> | # encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
| # encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
self._connection.release()
Fix error message 'ChannelError: channel disconnected'# encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
| <commit_before># encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
self._connection.release()
<commit_msg>Fix error message 'ChannelError: channel disconnected'<commit_after># encoding=utf-8
from kombu import Exchange, Connection, Producer
import logging
class RabbitMqHandler(object):
def __init__(self, connection, exchange_name, type='direct', durable=True):
self._logger = logging.getLogger(__name__)
try:
self._connection = Connection(connection)
self._producer = Producer(self._connection)
self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable)
except Exception:
self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer')
raise
def errback(exc, interval):
self._logger.info('Error: %r', exc, exc_info=1)
self._logger.info('Retry in %s seconds.', interval)
def publish(self, payload, routing_key=None, serializer=None):
publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3)
publish(payload,
serializer=serializer,
exchange=self._task_exchange,
declare=[self._task_exchange],
routing_key=routing_key)
|
daea13213632d5aa35e0bd3567e255903a857660 | apps/accounts/middleware.py | apps/accounts/middleware.py | """
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user.
:param request: The incoming request
:return: None
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
| """
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user if logged-in.
:param request: The current request instance.
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
# FIXME This generate two SQL requests per view. Maybe use update_or_create instead?
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
| Update docstring and add fixme for future revision | Update docstring and add fixme for future revision
| Python | agpl-3.0 | TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker | """
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user.
:param request: The incoming request
:return: None
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
Update docstring and add fixme for future revision | """
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user if logged-in.
:param request: The current request instance.
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
# FIXME This generate two SQL requests per view. Maybe use update_or_create instead?
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
| <commit_before>"""
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user.
:param request: The incoming request
:return: None
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
<commit_msg>Update docstring and add fixme for future revision<commit_after> | """
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user if logged-in.
:param request: The current request instance.
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
# FIXME This generate two SQL requests per view. Maybe use update_or_create instead?
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
| """
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user.
:param request: The incoming request
:return: None
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
Update docstring and add fixme for future revision"""
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user if logged-in.
:param request: The current request instance.
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
# FIXME This generate two SQL requests per view. Maybe use update_or_create instead?
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
| <commit_before>"""
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user.
:param request: The incoming request
:return: None
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
<commit_msg>Update docstring and add fixme for future revision<commit_after>"""
Middleware for the user accounts app.
"""
from django.utils import timezone
class LastActivityDateUpdateMiddleware(object):
"""
Middleware for updating the "last activity date" of authenticated users.
"""
def process_request(self, request):
"""
Process the request, update the last activity date of current user if logged-in.
:param request: The current request instance.
"""
# Only handle authenticated users
current_user = request.user
if current_user.is_authenticated():
# Update last login IP address
# FIXME This generate two SQL requests per view. Maybe use update_or_create instead?
user_profile = current_user.user_profile
user_profile.last_activity_date = timezone.now()
user_profile.save_no_rendering(update_fields=('last_activity_date',))
|
76c4a59070ef1e8562cc30bd28ac88ff82636d9c | cscslackbot/logconfig/__init__.py | cscslackbot/logconfig/__init__.py | import logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
fmtstyle = config.get('fmtstyle', '%')
if six.PY2:
formatter = logging.Formatter(format, datefmt)
else:
formatter = logging.Formatter(format, datefmt, fmtstyle)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
| import logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
formatter = logging.Formatter(format, datefmt)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
| Remove support for logging format style - doesn't work in Python 2 at all | Remove support for logging format style - doesn't work in Python 2 at all
| Python | mit | rollforbugs/cscslackbot,rollforbugs/cscslackbot | import logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
fmtstyle = config.get('fmtstyle', '%')
if six.PY2:
formatter = logging.Formatter(format, datefmt)
else:
formatter = logging.Formatter(format, datefmt, fmtstyle)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
Remove support for logging format style - doesn't work in Python 2 at all | import logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
formatter = logging.Formatter(format, datefmt)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
| <commit_before>import logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
fmtstyle = config.get('fmtstyle', '%')
if six.PY2:
formatter = logging.Formatter(format, datefmt)
else:
formatter = logging.Formatter(format, datefmt, fmtstyle)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
<commit_msg>Remove support for logging format style - doesn't work in Python 2 at all<commit_after> | import logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
formatter = logging.Formatter(format, datefmt)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
| import logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
fmtstyle = config.get('fmtstyle', '%')
if six.PY2:
formatter = logging.Formatter(format, datefmt)
else:
formatter = logging.Formatter(format, datefmt, fmtstyle)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
Remove support for logging format style - doesn't work in Python 2 at allimport logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
formatter = logging.Formatter(format, datefmt)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
| <commit_before>import logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
fmtstyle = config.get('fmtstyle', '%')
if six.PY2:
formatter = logging.Formatter(format, datefmt)
else:
formatter = logging.Formatter(format, datefmt, fmtstyle)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
<commit_msg>Remove support for logging format style - doesn't work in Python 2 at all<commit_after>import logging
import logging.config
import logging.handlers
import six
import sys
from ..utils import from_human_readable
def configure(config):
format = config.get('format', None)
datefmt = config.get('datefmt', None)
formatter = logging.Formatter(format, datefmt)
handlers = []
# Console handler
h = logging.StreamHandler(sys.stdout)
h.setLevel(config['console']['level'])
h.setFormatter(formatter)
handlers.append(h)
# File handlers
for f in config['files']:
file_config = config['files'][f]
maxsize = file_config.get('maxsize', '1M')
maxsize = from_human_readable(str(maxsize))
count = file_config.get('count', 1)
h = logging.handlers.RotatingFileHandler(f, maxBytes=maxsize, backupCount=count)
h.setLevel(file_config['level'])
h.setFormatter(formatter)
handlers.append(h)
logging.getLogger().setLevel(logging.DEBUG)
for h in handlers:
logging.getLogger().addHandler(h)
print(h)
|
220013558f83523113ca58381a6b6d283178e3be | flask-app/setup.py | flask-app/setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests',]
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests', 'ldap3']
)
| Add ldap3 to required modules | Add ldap3 to required modules
| Python | mit | cthit/nickIT,cthit/nickIT,cthit/nickIT | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests',]
)
Add ldap3 to required modules | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests', 'ldap3']
)
| <commit_before># -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests',]
)
<commit_msg>Add ldap3 to required modules<commit_after> | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests', 'ldap3']
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests',]
)
Add ldap3 to required modules# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests', 'ldap3']
)
| <commit_before># -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests',]
)
<commit_msg>Add ldap3 to required modules<commit_after># -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='nickITAPI',
version='0.1.1',
description='',
long_description=readme,
author='digIT',
# author_email='',
# url='',
license=license,
packages=find_packages(exclude=('tests', 'docs')),
install_requires=['flask', 'requests', 'ldap3']
)
|
4f7a64f3060c196a434e504847efc511e34537f6 | asyncssh/crypto/__init__.py | asyncssh/crypto/__init__.py | # Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
from .curve25519 import Curve25519DH
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
| # Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
try:
from .curve25519 import Curve25519DH
except ImportError:
pass
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
| Allow Curve25519DH import to fail in crypto package | Allow Curve25519DH import to fail in crypto package
With the refactoring to avoid pylint warnings, a problem was introduced
in importing the crypto module when the curve25519 dependencies were
unavailable. This commit fixes that problem.
| Python | epl-1.0 | jonathanslenders/asyncssh | # Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
from .curve25519 import Curve25519DH
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
Allow Curve25519DH import to fail in crypto package
With the refactoring to avoid pylint warnings, a problem was introduced
in importing the crypto module when the curve25519 dependencies were
unavailable. This commit fixes that problem. | # Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
try:
from .curve25519 import Curve25519DH
except ImportError:
pass
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
| <commit_before># Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
from .curve25519 import Curve25519DH
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
<commit_msg>Allow Curve25519DH import to fail in crypto package
With the refactoring to avoid pylint warnings, a problem was introduced
in importing the crypto module when the curve25519 dependencies were
unavailable. This commit fixes that problem.<commit_after> | # Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
try:
from .curve25519 import Curve25519DH
except ImportError:
pass
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
| # Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
from .curve25519 import Curve25519DH
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
Allow Curve25519DH import to fail in crypto package
With the refactoring to avoid pylint warnings, a problem was introduced
in importing the crypto module when the curve25519 dependencies were
unavailable. This commit fixes that problem.# Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
try:
from .curve25519 import Curve25519DH
except ImportError:
pass
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
| <commit_before># Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
from .curve25519 import Curve25519DH
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
<commit_msg>Allow Curve25519DH import to fail in crypto package
With the refactoring to avoid pylint warnings, a problem was introduced
in importing the crypto module when the curve25519 dependencies were
unavailable. This commit fixes that problem.<commit_after># Copyright (c) 2014-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""A shim for accessing cryptographic primitives needed by asyncssh"""
import importlib
from .cipher import register_cipher, lookup_cipher
try:
from .curve25519 import Curve25519DH
except ImportError:
pass
from . import chacha
pyca_available = importlib.find_loader('cryptography')
pycrypto_available = importlib.find_loader('Crypto')
if pyca_available:
from . import pyca
if pycrypto_available:
from . import pycrypto
if pyca_available:
from .pyca.dsa import DSAPrivateKey, DSAPublicKey
from .pyca.rsa import RSAPrivateKey, RSAPublicKey
elif pycrypto_available:
from .pycrypto.dsa import DSAPrivateKey, DSAPublicKey
from .pycrypto.rsa import RSAPrivateKey, RSAPublicKey
else:
raise ImportError('No suitable crypto library found.')
|
d85b58a0edce8321312eff66f16fc72439e4426a | app/sense.py | app/sense.py | #!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
DEVICE = "PiSense"
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
| #!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
import time
DEVICE = "PiSense"
DELAY = 0.0
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
time.sleep(DELAY)
| Add ability to control read rate | Add ability to control read rate
| Python | mit | thelonious/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x | #!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
DEVICE = "PiSense"
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
Add ability to control read rate | #!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
import time
DEVICE = "PiSense"
DELAY = 0.0
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
time.sleep(DELAY)
| <commit_before>#!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
DEVICE = "PiSense"
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
<commit_msg>Add ability to control read rate<commit_after> | #!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
import time
DEVICE = "PiSense"
DELAY = 0.0
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
time.sleep(DELAY)
| #!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
DEVICE = "PiSense"
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
Add ability to control read rate#!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
import time
DEVICE = "PiSense"
DELAY = 0.0
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
time.sleep(DELAY)
| <commit_before>#!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
DEVICE = "PiSense"
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
<commit_msg>Add ability to control read rate<commit_after>#!/usr/bin/env python3
from Sensor import SenseController
from KeyDispatcher import KeyDispatcher
from Display import Display
from DataLogger import SQLiteLogger
import time
DEVICE = "PiSense"
DELAY = 0.0
class Handler:
def __init__(self, display, logger, sensor):
self.display = display
self.logger = logger
self.sensor = sensor
self.logger.log(DEVICE, "running", 1)
def read(self):
values = {}
for reading in self.sensor.get_data():
values[reading[1]] = reading[2]
self.logger.log(DEVICE, reading[1], reading[2], reading[0])
display.show_properties(values, self.sensor.get_properties())
return True
def quit(self):
self.logger.log(DEVICE, "running", 0)
return False
with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger:
# setup display
display = Display("PiSense")
# setup key handlers
handler = Handler(display, logger, sensor)
dispatcher.add("q", handler, "quit")
# start processing key presses
while True:
if dispatcher.can_process_key():
if not dispatcher.process_key():
break
else:
handler.read()
time.sleep(DELAY)
|
4a476e31d16273afc99abed408efba37936af620 | virtool/hmm/utils.py | virtool/hmm/utils.py | import semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(release)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(release["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
| import semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(updated)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(formatted["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
| Fix HMM release formatting bug | Fix HMM release formatting bug
| Python | mit | virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool | import semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(release)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(release["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
Fix HMM release formatting bug | import semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(updated)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(formatted["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
| <commit_before>import semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(release)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(release["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
<commit_msg>Fix HMM release formatting bug<commit_after> | import semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(updated)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(formatted["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
| import semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(release)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(release["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
Fix HMM release formatting bugimport semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(updated)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(formatted["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
| <commit_before>import semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(release)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(release["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
<commit_msg>Fix HMM release formatting bug<commit_after>import semver
import virtool.github
def format_hmm_release(updated, release, installed):
# The release dict will only be replaced if there is a 200 response from GitHub. A 304 indicates the release
# has not changed and `None` is returned from `get_release()`.
if updated is None:
return None
formatted = virtool.github.format_release(updated)
formatted["newer"] = bool(
release is None or installed is None or (
installed and
semver.compare(formatted["name"].lstrip("v"), installed["name"].lstrip("v")) == 1
)
)
return formatted
|
93873f19a651b786f2413b073a9372dae7bb67a9 | codecademy/Car.py | codecademy/Car.py | class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.display_car()
| class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
def drive_car(self):
self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
super(ElectricCar, self).__init__(model, color, mpg)
self.battery_type = battery_type
my_car = ElectricCar("molten salt", "Benz", "Black", 120)
| Add a sub class for car | Add a sub class for car
| Python | apache-2.0 | haozai309/hello_python | class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.display_car()
Add a sub class for car | class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
def drive_car(self):
self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
super(ElectricCar, self).__init__(model, color, mpg)
self.battery_type = battery_type
my_car = ElectricCar("molten salt", "Benz", "Black", 120)
| <commit_before>class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.display_car()
<commit_msg>Add a sub class for car<commit_after> | class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
def drive_car(self):
self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
super(ElectricCar, self).__init__(model, color, mpg)
self.battery_type = battery_type
my_car = ElectricCar("molten salt", "Benz", "Black", 120)
| class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.display_car()
Add a sub class for carclass Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
def drive_car(self):
self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
super(ElectricCar, self).__init__(model, color, mpg)
self.battery_type = battery_type
my_car = ElectricCar("molten salt", "Benz", "Black", 120)
| <commit_before>class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.display_car()
<commit_msg>Add a sub class for car<commit_after>class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))
def drive_car(self):
self.condition = "used"
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
my_car.drive_car()
print my_car.condition
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
super(ElectricCar, self).__init__(model, color, mpg)
self.battery_type = battery_type
my_car = ElectricCar("molten salt", "Benz", "Black", 120)
|
9171777c3945b3a1324d9b20ff607fd340747b58 | cinder/version.py | cinder/version.py | # Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from pbr import version as pbr_version
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
version_info = pbr_version.VersionInfo('cinder')
version_string = version_info.version_string
| # Copyright 2011 OpenStack Foundation
#
# 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.
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo:
version = "REDHATCINDERVERSION"
release = "REDHATCINDERRELEASE"
def release_string(self):
return '%s-%s' % (self.version, self.release)
def version_string(self):
return self.version
version_info = VersionInfo()
version_string = version_info.version_string
| Remove runtime dep on python-pbr, python-d2to1 | Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION.
| Python | apache-2.0 | redhat-openstack/cinder,redhat-openstack/cinder | # Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from pbr import version as pbr_version
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
version_info = pbr_version.VersionInfo('cinder')
version_string = version_info.version_string
Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION. | # Copyright 2011 OpenStack Foundation
#
# 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.
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo:
version = "REDHATCINDERVERSION"
release = "REDHATCINDERRELEASE"
def release_string(self):
return '%s-%s' % (self.version, self.release)
def version_string(self):
return self.version
version_info = VersionInfo()
version_string = version_info.version_string
| <commit_before># Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from pbr import version as pbr_version
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
version_info = pbr_version.VersionInfo('cinder')
version_string = version_info.version_string
<commit_msg>Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION.<commit_after> | # Copyright 2011 OpenStack Foundation
#
# 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.
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo:
version = "REDHATCINDERVERSION"
release = "REDHATCINDERRELEASE"
def release_string(self):
return '%s-%s' % (self.version, self.release)
def version_string(self):
return self.version
version_info = VersionInfo()
version_string = version_info.version_string
| # Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from pbr import version as pbr_version
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
version_info = pbr_version.VersionInfo('cinder')
version_string = version_info.version_string
Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION.# Copyright 2011 OpenStack Foundation
#
# 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.
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo:
version = "REDHATCINDERVERSION"
release = "REDHATCINDERRELEASE"
def release_string(self):
return '%s-%s' % (self.version, self.release)
def version_string(self):
return self.version
version_info = VersionInfo()
version_string = version_info.version_string
| <commit_before># Copyright 2011 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from pbr import version as pbr_version
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
version_info = pbr_version.VersionInfo('cinder')
version_string = version_info.version_string
<commit_msg>Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION.<commit_after># Copyright 2011 OpenStack Foundation
#
# 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.
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo:
version = "REDHATCINDERVERSION"
release = "REDHATCINDERRELEASE"
def release_string(self):
return '%s-%s' % (self.version, self.release)
def version_string(self):
return self.version
version_info = VersionInfo()
version_string = version_info.version_string
|
2a4891506f02e20d6a6f0e10a346b8fb30d54767 | mozaik_membership_payment/models/account_payment.py | mozaik_membership_payment/models/account_payment.py | # Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
else:
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
return res
| # Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
from odoo.fields import first
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
membership_related = (
ap.payment_transaction_id.membership_ids
or ap.payment_transaction_id.membership_request_ids
)
if not membership_related:
continue
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
continue
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
continue
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
ap.destination_account_id = first(subscription_accounts)
return res
def _seek_for_lines(self):
self.ensure_one()
liquidity_lines, counterpart_lines, writeoff_lines = super(
AccountPayment, self
)._seek_for_lines()
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
for line in self.move_id.line_ids:
if line.account_id in subscription_accounts:
counterpart_lines += line
return liquidity_lines, counterpart_lines, writeoff_lines
| Fix the account for memberships payements | Fix the account for memberships payements
| Python | agpl-3.0 | mozaik-association/mozaik,mozaik-association/mozaik | # Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
else:
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
return res
Fix the account for memberships payements | # Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
from odoo.fields import first
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
membership_related = (
ap.payment_transaction_id.membership_ids
or ap.payment_transaction_id.membership_request_ids
)
if not membership_related:
continue
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
continue
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
continue
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
ap.destination_account_id = first(subscription_accounts)
return res
def _seek_for_lines(self):
self.ensure_one()
liquidity_lines, counterpart_lines, writeoff_lines = super(
AccountPayment, self
)._seek_for_lines()
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
for line in self.move_id.line_ids:
if line.account_id in subscription_accounts:
counterpart_lines += line
return liquidity_lines, counterpart_lines, writeoff_lines
| <commit_before># Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
else:
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
return res
<commit_msg>Fix the account for memberships payements<commit_after> | # Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
from odoo.fields import first
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
membership_related = (
ap.payment_transaction_id.membership_ids
or ap.payment_transaction_id.membership_request_ids
)
if not membership_related:
continue
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
continue
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
continue
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
ap.destination_account_id = first(subscription_accounts)
return res
def _seek_for_lines(self):
self.ensure_one()
liquidity_lines, counterpart_lines, writeoff_lines = super(
AccountPayment, self
)._seek_for_lines()
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
for line in self.move_id.line_ids:
if line.account_id in subscription_accounts:
counterpart_lines += line
return liquidity_lines, counterpart_lines, writeoff_lines
| # Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
else:
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
return res
Fix the account for memberships payements# Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
from odoo.fields import first
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
membership_related = (
ap.payment_transaction_id.membership_ids
or ap.payment_transaction_id.membership_request_ids
)
if not membership_related:
continue
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
continue
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
continue
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
ap.destination_account_id = first(subscription_accounts)
return res
def _seek_for_lines(self):
self.ensure_one()
liquidity_lines, counterpart_lines, writeoff_lines = super(
AccountPayment, self
)._seek_for_lines()
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
for line in self.move_id.line_ids:
if line.account_id in subscription_accounts:
counterpart_lines += line
return liquidity_lines, counterpart_lines, writeoff_lines
| <commit_before># Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
else:
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
return res
<commit_msg>Fix the account for memberships payements<commit_after># Copyright 2018 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
from odoo.fields import first
class AccountPayment(models.Model):
_inherit = "account.payment"
@api.depends("journal_id", "partner_id", "partner_type", "is_internal_transfer")
def _compute_destination_account_id(self):
res = super(AccountPayment, self)._compute_destination_account_id()
for ap in self:
membership_related = (
ap.payment_transaction_id.membership_ids
or ap.payment_transaction_id.membership_request_ids
)
if not membership_related:
continue
sa = ap.payment_transaction_id.membership_ids.mapped(
"product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_ids and sa:
ap.destination_account_id = sa
continue
sa = ap.payment_transaction_id.membership_request_ids.mapped(
"partner_id.subscription_product_id.property_subscription_account"
)
if ap.payment_transaction_id.membership_request_ids and sa:
ap.destination_account_id = sa
continue
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
ap.destination_account_id = first(subscription_accounts)
return res
def _seek_for_lines(self):
self.ensure_one()
liquidity_lines, counterpart_lines, writeoff_lines = super(
AccountPayment, self
)._seek_for_lines()
subscription_accounts = (
self.env["product.product"]
.search([("membership", "=", True)])
.mapped("property_subscription_account")
)
for line in self.move_id.line_ids:
if line.account_id in subscription_accounts:
counterpart_lines += line
return liquidity_lines, counterpart_lines, writeoff_lines
|
2b0a11a1adf4167fb55f9b90fc87a8b8518a24a7 | atmo/apps.py | atmo/apps.py | from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if getattr(settings, 'REDIS_URL'):
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
| from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if settings.REDIS_URL.hostname:
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
| Fix rq jobs registration check | Fix rq jobs registration check
| Python | mpl-2.0 | mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service,mozilla/telemetry-analysis-service | from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if getattr(settings, 'REDIS_URL'):
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
Fix rq jobs registration check | from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if settings.REDIS_URL.hostname:
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
| <commit_before>from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if getattr(settings, 'REDIS_URL'):
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
<commit_msg>Fix rq jobs registration check<commit_after> | from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if settings.REDIS_URL.hostname:
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
| from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if getattr(settings, 'REDIS_URL'):
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
Fix rq jobs registration checkfrom django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if settings.REDIS_URL.hostname:
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
| <commit_before>from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if getattr(settings, 'REDIS_URL'):
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
<commit_msg>Fix rq jobs registration check<commit_after>from django.apps import AppConfig
from django.conf import settings
import session_csrf
class AtmoAppConfig(AppConfig):
name = 'atmo'
def ready(self):
# The app is now ready. Include any monkey patches here.
# Monkey patch CSRF to switch to session based CSRF. Session
# based CSRF will prevent attacks from apps under the same
# domain. If you're planning to host your app under it's own
# domain you can remove session_csrf and use Django's CSRF
# library. See also
# https://github.com/mozilla/sugardough/issues/38
session_csrf.monkeypatch()
# Under some circumstances (e.g. when calling collectstatic)
# REDIS_URL is not available and we can skip the job schedule registration.
if settings.REDIS_URL.hostname:
# This module contains references to some orm models, so it's
# safer to import it here.
from .schedule import register_job_schedule
# Register rq scheduled jobs
register_job_schedule()
|
57773d37b20285eba15cc78f4de4e3e344097624 | game-log.py | game-log.py | from bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
| from bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
self.column_names = self.get_headers()
def get_headers(self):
names = []
table = self.soup.find("table", attrs={"summary": "Player "})
headers = table.find('thead').find_all('tr')[1]
for header in headers:
if isinstance(header, Tag):
names.append(header.text)
return names
def columns(self):
return self.column_names
game_log = YahooGameLog('4750')
print(game_log.columns())
| Add yahoo game log header parsing | Add yahoo game log header parsing
| Python | mit | arosenberg01/asdata | from bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
Add yahoo game log header parsing | from bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
self.column_names = self.get_headers()
def get_headers(self):
names = []
table = self.soup.find("table", attrs={"summary": "Player "})
headers = table.find('thead').find_all('tr')[1]
for header in headers:
if isinstance(header, Tag):
names.append(header.text)
return names
def columns(self):
return self.column_names
game_log = YahooGameLog('4750')
print(game_log.columns())
| <commit_before>from bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
<commit_msg>Add yahoo game log header parsing<commit_after> | from bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
self.column_names = self.get_headers()
def get_headers(self):
names = []
table = self.soup.find("table", attrs={"summary": "Player "})
headers = table.find('thead').find_all('tr')[1]
for header in headers:
if isinstance(header, Tag):
names.append(header.text)
return names
def columns(self):
return self.column_names
game_log = YahooGameLog('4750')
print(game_log.columns())
| from bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
Add yahoo game log header parsingfrom bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
self.column_names = self.get_headers()
def get_headers(self):
names = []
table = self.soup.find("table", attrs={"summary": "Player "})
headers = table.find('thead').find_all('tr')[1]
for header in headers:
if isinstance(header, Tag):
names.append(header.text)
return names
def columns(self):
return self.column_names
game_log = YahooGameLog('4750')
print(game_log.columns())
| <commit_before>from bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
<commit_msg>Add yahoo game log header parsing<commit_after>from bs4 import BeautifulSoup, Tag
import requests
class YahooGameLog:
def __init__(self, player_id):
page = requests.get('http://sports.yahoo.com/nba/players/' + player_id + '/gamelog/')
self.soup = BeautifulSoup(page.text, 'lxml')
self.column_names = self.get_headers()
def get_headers(self):
names = []
table = self.soup.find("table", attrs={"summary": "Player "})
headers = table.find('thead').find_all('tr')[1]
for header in headers:
if isinstance(header, Tag):
names.append(header.text)
return names
def columns(self):
return self.column_names
game_log = YahooGameLog('4750')
print(game_log.columns())
|
f4f4d799409e4869276b84f032e60cdf516fcaf6 | src/subcmds/init.py | src/subcmds/init.py | #! /usr/bin/env python
import os
import subprocess
import config
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
| #! /usr/bin/env python
import config
import os
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
| Remove no longer needed import | Remove no longer needed import
| Python | apache-2.0 | lorneliechty/ghi,lorneliechty/ghi | #! /usr/bin/env python
import os
import subprocess
import config
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
Remove no longer needed import | #! /usr/bin/env python
import config
import os
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
| <commit_before>#! /usr/bin/env python
import os
import subprocess
import config
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
<commit_msg>Remove no longer needed import<commit_after> | #! /usr/bin/env python
import config
import os
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
| #! /usr/bin/env python
import os
import subprocess
import config
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
Remove no longer needed import#! /usr/bin/env python
import config
import os
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
| <commit_before>#! /usr/bin/env python
import os
import subprocess
import config
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
<commit_msg>Remove no longer needed import<commit_after>#! /usr/bin/env python
import config
import os
NAME="init"
HELP="give git issues"
def execute(args):
# Check to see if the .ghi directories have already been created
# If it doesn't exist, create it.
if os.path.isdir(config.GHI_DIR) == False:
os.makedirs(config.GHI_DIR)
os.makedirs(config.ISSUES_DIR)
elif os.path.isdir(config.ISSUES_DIR) == False:
os.makedirs(config.ISSUES_DIR)
else:
print "This git already has issues."
|
eb72c1fbd0b6764853d63ecc6f73e4281b34d411 | alembic/versions/13f089849099_insert_school_data.py | alembic/versions/13f089849099_insert_school_data.py | """Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.remove())
| """Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.delete())
| Fix a bug in alembic downgrading script | Fix a bug in alembic downgrading script
| Python | apache-2.0 | teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr | """Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.remove())
Fix a bug in alembic downgrading script | """Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.delete())
| <commit_before>"""Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.remove())
<commit_msg>Fix a bug in alembic downgrading script<commit_after> | """Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.delete())
| """Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.remove())
Fix a bug in alembic downgrading script"""Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.delete())
| <commit_before>"""Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.remove())
<commit_msg>Fix a bug in alembic downgrading script<commit_after>"""Insert school data
Revision ID: 13f089849099
Revises: 3cea1b2cfa
Create Date: 2013-05-05 22:58:35.938292
"""
# revision identifiers, used by Alembic.
revision = '13f089849099'
down_revision = '3cea1b2cfa'
from os.path import abspath, dirname, join
from alembic import op
import sqlalchemy as sa
proj_dir = dirname(dirname(dirname(abspath(__file__))))
schools_path = join(proj_dir, 'data/schools.csv')
school_t = sa.sql.table(
'school',
sa.sql.column('id', sa.String(length=20)),
sa.sql.column('name', sa.Unicode(length=100))
)
def upgrade():
for line in list(open(schools_path, 'r'))[1:]:
code, ko = map(str.strip, line.split(','))
op.execute(school_t.insert().values({
'id': code,
'name': ko
}))
def downgrade():
op.execute(school_t.delete())
|
37defc61f5722a8e988386cb4eed883f2205feb5 | luminoso_api/save_token.py | luminoso_api/save_token.py | import argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def main():
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args()
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
| import argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def _main(argv):
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args(argv)
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
def main():
"""
The setuptools entry point.
"""
_main(sys.argv[1:])
| Move main() into _main() to make testing easier | Move main() into _main() to make testing easier
| Python | mit | LuminosoInsight/luminoso-api-client-python | import argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def main():
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args()
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
Move main() into _main() to make testing easier | import argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def _main(argv):
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args(argv)
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
def main():
"""
The setuptools entry point.
"""
_main(sys.argv[1:])
| <commit_before>import argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def main():
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args()
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
<commit_msg>Move main() into _main() to make testing easier<commit_after> | import argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def _main(argv):
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args(argv)
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
def main():
"""
The setuptools entry point.
"""
_main(sys.argv[1:])
| import argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def main():
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args()
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
Move main() into _main() to make testing easierimport argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def _main(argv):
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args(argv)
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
def main():
"""
The setuptools entry point.
"""
_main(sys.argv[1:])
| <commit_before>import argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def main():
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args()
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
<commit_msg>Move main() into _main() to make testing easier<commit_after>import argparse
import os
import sys
from urllib.parse import urlparse
from .v5_client import LuminosoClient, get_token_filename
from .v5_constants import URL_BASE
def _main(argv):
default_domain_base = urlparse(URL_BASE).netloc
default_token_filename = get_token_filename()
parser = argparse.ArgumentParser(
description='Save a token for the Luminoso Daylight API.',
)
parser.add_argument('token',
help='API token (see "Settings - Tokens" in the UI)')
parser.add_argument('domain', default=default_domain_base,
help=f'API domain, default {default_domain_base}',
nargs='?')
parser.add_argument('-f', '--token_file', default=default_token_filename,
help=(f'File in which to store the token, default'
f' {default_token_filename}'))
args = parser.parse_args(argv)
# Make this as friendly as possible: turn any of "daylight.luminoso.com",
# "daylight.luminoso.com/api/v5", or "http://daylight.luminoso.com/", into
# just the domain
domain = args.domain
if '://' in domain:
domain = urlparse(domain).netloc
else:
domain = domain.split('/')[0]
LuminosoClient.save_token(args.token, domain=domain,
token_file=args.token_file)
def main():
"""
The setuptools entry point.
"""
_main(sys.argv[1:])
|
128a0ae97e86d6dec6c149a7d3f8bccd7f8c499d | agents/DiffAgentBase.py | agents/DiffAgentBase.py | class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = None | class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
else:
break
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = None | Break when done copying the working behaviour | Break when done copying the working behaviour
| Python | apache-2.0 | sergiuionescu/gym-agents | class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = NoneBreak when done copying the working behaviour | class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
else:
break
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = None | <commit_before>class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = None<commit_msg>Break when done copying the working behaviour<commit_after> | class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
else:
break
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = None | class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = NoneBreak when done copying the working behaviourclass DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
else:
break
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = None | <commit_before>class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = None<commit_msg>Break when done copying the working behaviour<commit_after>class DiffAgentBase(object):
diff = []
noise_reduction = []
latest_observation = 0
current_prediction = []
name = ''
behaviour = None
working_behaviour_size = 2
def __init__(self, experience, knowledge, space):
self.space = space
self.experience = experience
self.knowledge = knowledge
self.prediction()
def reset_behaviour(self):
total_score = 0
count = 0
if len(self.knowledge.behaviour) > 0:
for b, score in self.knowledge.behaviour.iteritems():
total_score += score
average_score = total_score / len(self.knowledge.behaviour)
new_behaviour = {}
for b, score in self.knowledge.behaviour.iteritems():
count += 1;
if score >= average_score or count <= self.working_behaviour_size:
new_behaviour[b] = score
else:
break
self.behaviour = new_behaviour.iteritems()
# self.behaviour = self.knowledge.behaviour.iteritems()
def sleep(self):
self.behaviour = None |
cdefb1fdb304939b35f8c881662fa220a57573dc | members/urls.py | members/urls.py | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
| from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
| Add url for user's profile | Add url for user's profile
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
Add url for user's profile | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
| <commit_before>from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
<commit_msg>Add url for user's profile<commit_after> | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
| from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
Add url for user's profilefrom django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
| <commit_before>from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
)
<commit_msg>Add url for user's profile<commit_after>from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('members.views',
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', name='logout'),
url(r'^search/(?P<name>.*)/$', 'search', name='search'),
url(r'^archive/$', 'archive_student_council', name='archive_student_council'),
url(r'^profile/$', 'user_projects', name='user-projects'),
)
|
6d5a37ef127f2b1822645fcad6636880e92d5489 | helusers/models.py | helusers/models.py | import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
primary_sid = models.CharField(max_length=100, unique=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
| import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
| Remove primary_sid from common fields | Remove primary_sid from common fields
| Python | bsd-2-clause | City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers | import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
primary_sid = models.CharField(max_length=100, unique=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
Remove primary_sid from common fields | import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
| <commit_before>import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
primary_sid = models.CharField(max_length=100, unique=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
<commit_msg>Remove primary_sid from common fields<commit_after> | import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
| import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
primary_sid = models.CharField(max_length=100, unique=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
Remove primary_sid from common fieldsimport uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
| <commit_before>import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
primary_sid = models.CharField(max_length=100, unique=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
<commit_msg>Remove primary_sid from common fields<commit_after>import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True, blank=True)
def save(self, *args, **kwargs):
if self.uuid is None:
self.uuid = uuid.uuid1()
if not self.primary_sid:
self.primary_sid = uuid.uuid4()
return super(AbstractUser, self).save(*args, **kwargs)
class Meta:
abstract = True
|
8382ee65c87c5eee976d4488ef91bdd5f801c06b | apitestcase/testcase.py | apitestcase/testcase.py | import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
return self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
return self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
return self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
return self.assertRequest("DELETE", *args, **kwargs)
| import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
self.assertRequest("DELETE", *args, **kwargs)
| Remove return statements from assert methods | Remove return statements from assert methods
| Python | mit | bramwelt/apitestcase | import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
return self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
return self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
return self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
return self.assertRequest("DELETE", *args, **kwargs)
Remove return statements from assert methods | import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
self.assertRequest("DELETE", *args, **kwargs)
| <commit_before>import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
return self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
return self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
return self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
return self.assertRequest("DELETE", *args, **kwargs)
<commit_msg>Remove return statements from assert methods<commit_after> | import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
self.assertRequest("DELETE", *args, **kwargs)
| import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
return self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
return self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
return self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
return self.assertRequest("DELETE", *args, **kwargs)
Remove return statements from assert methodsimport requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
self.assertRequest("DELETE", *args, **kwargs)
| <commit_before>import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
return self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
return self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
return self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
return self.assertRequest("DELETE", *args, **kwargs)
<commit_msg>Remove return statements from assert methods<commit_after>import requests
class TestCase(object):
"""
Add assetion methods for HTTP Requests to TestCase
"""
def assertRequest(self, method="GET", url="", status_code=200,
contains=None, **kwargs):
"""
Asserts requests on a given endpoint
"""
if contains is None:
cotains = []
if method is "GET":
request = requests.get
elif method is "POST":
request = requests.post
elif method is "PUT":
request = requests.put
elif method is "DELETE":
request = requests.delete
response = request(url, **kwargs)
self.assertEqual(response.status_code, status_code)
if contains:
for item in contains:
self.assertIn(item, response.content)
def assertGet(self, *args, **kwargs):
"""
Asserts GET requests on a URL
"""
self.assertRequest("GET", *args, **kwargs)
def assertPost(self, *args, **kwargs):
"""
Asserts POST requests on a URL
"""
self.assertRequest("POST", *args, **kwargs)
def assertPut(self, *args, **kwargs):
"""
Asserts PUT requests on a URL
"""
self.assertRequest("PUT", *args, **kwargs)
def assertDelete(self, *args, **kwargs):
"""
Asserts DELETE requests on a URL
"""
self.assertRequest("DELETE", *args, **kwargs)
|
44c8098906375020b6d6b894601c356bd0fbd586 | confluent/main.py | confluent/main.py | # Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
| # Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
import eventlet.backdoor as backdoor
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
#TODO: eventlet has a bug about unix domain sockets, this code works with bugs fixed
#dbgsock = eventlet.listen("/var/run/confluent/dbg.sock", family=socket.AF_UNIX)
#eventlet.spawn_n(backdoor.backdoor_server, dbgsock)
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
| Add commented code to allow easily getting at the debug socket, needs eventlet fix to work | Add commented code to allow easily getting at the debug socket, needs eventlet fix to work
| Python | apache-2.0 | xcat2/confluent,michaelfardu/thinkconfluent,xcat2/confluent,michaelfardu/thinkconfluent,jjohnson42/confluent,jufm/confluent,xcat2/confluent,chenglch/confluent,xcat2/confluent,chenglch/confluent,whowutwut/confluent,jufm/confluent,jjohnson42/confluent,jufm/confluent,chenglch/confluent,jufm/confluent,whowutwut/confluent,xcat2/confluent,jufm/confluent,chenglch/confluent,whowutwut/confluent,jjohnson42/confluent,michaelfardu/thinkconfluent,chenglch/confluent,jjohnson42/confluent,jjohnson42/confluent,michaelfardu/thinkconfluent,michaelfardu/thinkconfluent,whowutwut/confluent | # Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
Add commented code to allow easily getting at the debug socket, needs eventlet fix to work | # Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
import eventlet.backdoor as backdoor
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
#TODO: eventlet has a bug about unix domain sockets, this code works with bugs fixed
#dbgsock = eventlet.listen("/var/run/confluent/dbg.sock", family=socket.AF_UNIX)
#eventlet.spawn_n(backdoor.backdoor_server, dbgsock)
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
| <commit_before># Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
<commit_msg>Add commented code to allow easily getting at the debug socket, needs eventlet fix to work<commit_after> | # Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
import eventlet.backdoor as backdoor
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
#TODO: eventlet has a bug about unix domain sockets, this code works with bugs fixed
#dbgsock = eventlet.listen("/var/run/confluent/dbg.sock", family=socket.AF_UNIX)
#eventlet.spawn_n(backdoor.backdoor_server, dbgsock)
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
| # Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
Add commented code to allow easily getting at the debug socket, needs eventlet fix to work# Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
import eventlet.backdoor as backdoor
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
#TODO: eventlet has a bug about unix domain sockets, this code works with bugs fixed
#dbgsock = eventlet.listen("/var/run/confluent/dbg.sock", family=socket.AF_UNIX)
#eventlet.spawn_n(backdoor.backdoor_server, dbgsock)
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
| <commit_before># Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
<commit_msg>Add commented code to allow easily getting at the debug socket, needs eventlet fix to work<commit_after># Copyright 2013 IBM Corporation
# All rights reserved
# This is the main application.
# It should check for existing UDP socket to negotiate socket listen takeover
# It will have three paths into it:
# -Unix domain socket
# -TLS socket
# -WSGI
# Additionally, it will be able to receive particular UDP packets to facilitate
# Things like heartbeating and discovery
# It also will optionally snoop SLP DA requests
import confluent.pluginapi as pluginapi
import confluent.httpapi as httpapi
import confluent.sockapi as sockapi
import eventlet
import eventlet.backdoor as backdoor
from eventlet.green import socket
from eventlet import wsgi
import multiprocessing
import sys
import os
def run():
pluginapi.load_plugins()
#TODO: eventlet has a bug about unix domain sockets, this code works with bugs fixed
#dbgsock = eventlet.listen("/var/run/confluent/dbg.sock", family=socket.AF_UNIX)
#eventlet.spawn_n(backdoor.backdoor_server, dbgsock)
webservice = httpapi.HttpApi()
webservice.start()
sockservice = sockapi.SockApi()
sockservice.start()
while (1):
eventlet.sleep(100)
|
25cf672fa4a743b3c4cb198e5fdf19bd40991f35 | life/__init__.py | life/__init__.py | RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 8
DENSITY = .5
| RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 16
DENSITY = .2
| Make the default cell size larger. | Make the default cell size larger.
| Python | bsd-2-clause | lig/life | RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 8
DENSITY = .5
Make the default cell size larger. | RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 16
DENSITY = .2
| <commit_before>RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 8
DENSITY = .5
<commit_msg>Make the default cell size larger.<commit_after> | RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 16
DENSITY = .2
| RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 8
DENSITY = .5
Make the default cell size larger.RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 16
DENSITY = .2
| <commit_before>RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 8
DENSITY = .5
<commit_msg>Make the default cell size larger.<commit_after>RULES = 'B3/S23'
WIDTH = 1280
HEIGHT = 720
CELL_SIZE = 16
DENSITY = .2
|
6e61c41a24e35e66d941b67945f135392b27397d | list_ami_datasets.py | list_ami_datasets.py | """
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import ami
import json
ami_rootdir = '/opt/ami'
r = ami.Reduce(ami_rootdir)
named_groups = r.group_pointings()
json.dump(named_groups, open('groups.json', 'w'),
sort_keys=True, indent=4)
| #!/usr/bin/python
"""
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import json
import optparse
import sys
import ami
def main():
options, outputfilename = handle_args(sys.argv[1:])
r = ami.Reduce(options.amidir)
named_groups = r.group_pointings()
json.dump(named_groups, open(outputfilename, 'w'),
sort_keys=True, indent=4)
return 0
def handle_args(argv):
"""
Returns tuple (options_object, outputfilename)
"""
default_ami_dir = "/opt/ami"
default_array = 'LA'
usage = """usage: %prog [options] outputfile\n"""\
"""Outputs a file in JSON format listing AMI files, grouped by pointing."""
parser = optparse.OptionParser(usage)
parser.add_option("--amidir", default=default_ami_dir,
help="Path to AMI directory, default: " + default_ami_dir)
parser.add_option("--array", default=default_array,
help="Array data to work with (SA/LA), defaults to: "
+ default_array)
options, args = parser.parse_args(argv)
if len(args)!=1:
parser.print_help()
sys.exit(1)
print "Will output listings to file:", args[0]
return options, args[0]
if __name__ == "__main__":
sys.exit(main())
| Make listings script executable, add argument handling. | Make listings script executable, add argument handling.
| Python | bsd-3-clause | timstaley/drive-ami | """
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import ami
import json
ami_rootdir = '/opt/ami'
r = ami.Reduce(ami_rootdir)
named_groups = r.group_pointings()
json.dump(named_groups, open('groups.json', 'w'),
sort_keys=True, indent=4)
Make listings script executable, add argument handling. | #!/usr/bin/python
"""
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import json
import optparse
import sys
import ami
def main():
options, outputfilename = handle_args(sys.argv[1:])
r = ami.Reduce(options.amidir)
named_groups = r.group_pointings()
json.dump(named_groups, open(outputfilename, 'w'),
sort_keys=True, indent=4)
return 0
def handle_args(argv):
"""
Returns tuple (options_object, outputfilename)
"""
default_ami_dir = "/opt/ami"
default_array = 'LA'
usage = """usage: %prog [options] outputfile\n"""\
"""Outputs a file in JSON format listing AMI files, grouped by pointing."""
parser = optparse.OptionParser(usage)
parser.add_option("--amidir", default=default_ami_dir,
help="Path to AMI directory, default: " + default_ami_dir)
parser.add_option("--array", default=default_array,
help="Array data to work with (SA/LA), defaults to: "
+ default_array)
options, args = parser.parse_args(argv)
if len(args)!=1:
parser.print_help()
sys.exit(1)
print "Will output listings to file:", args[0]
return options, args[0]
if __name__ == "__main__":
sys.exit(main())
| <commit_before>"""
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import ami
import json
ami_rootdir = '/opt/ami'
r = ami.Reduce(ami_rootdir)
named_groups = r.group_pointings()
json.dump(named_groups, open('groups.json', 'w'),
sort_keys=True, indent=4)
<commit_msg>Make listings script executable, add argument handling.<commit_after> | #!/usr/bin/python
"""
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import json
import optparse
import sys
import ami
def main():
options, outputfilename = handle_args(sys.argv[1:])
r = ami.Reduce(options.amidir)
named_groups = r.group_pointings()
json.dump(named_groups, open(outputfilename, 'w'),
sort_keys=True, indent=4)
return 0
def handle_args(argv):
"""
Returns tuple (options_object, outputfilename)
"""
default_ami_dir = "/opt/ami"
default_array = 'LA'
usage = """usage: %prog [options] outputfile\n"""\
"""Outputs a file in JSON format listing AMI files, grouped by pointing."""
parser = optparse.OptionParser(usage)
parser.add_option("--amidir", default=default_ami_dir,
help="Path to AMI directory, default: " + default_ami_dir)
parser.add_option("--array", default=default_array,
help="Array data to work with (SA/LA), defaults to: "
+ default_array)
options, args = parser.parse_args(argv)
if len(args)!=1:
parser.print_help()
sys.exit(1)
print "Will output listings to file:", args[0]
return options, args[0]
if __name__ == "__main__":
sys.exit(main())
| """
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import ami
import json
ami_rootdir = '/opt/ami'
r = ami.Reduce(ami_rootdir)
named_groups = r.group_pointings()
json.dump(named_groups, open('groups.json', 'w'),
sort_keys=True, indent=4)
Make listings script executable, add argument handling.#!/usr/bin/python
"""
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import json
import optparse
import sys
import ami
def main():
options, outputfilename = handle_args(sys.argv[1:])
r = ami.Reduce(options.amidir)
named_groups = r.group_pointings()
json.dump(named_groups, open(outputfilename, 'w'),
sort_keys=True, indent=4)
return 0
def handle_args(argv):
"""
Returns tuple (options_object, outputfilename)
"""
default_ami_dir = "/opt/ami"
default_array = 'LA'
usage = """usage: %prog [options] outputfile\n"""\
"""Outputs a file in JSON format listing AMI files, grouped by pointing."""
parser = optparse.OptionParser(usage)
parser.add_option("--amidir", default=default_ami_dir,
help="Path to AMI directory, default: " + default_ami_dir)
parser.add_option("--array", default=default_array,
help="Array data to work with (SA/LA), defaults to: "
+ default_array)
options, args = parser.parse_args(argv)
if len(args)!=1:
parser.print_help()
sys.exit(1)
print "Will output listings to file:", args[0]
return options, args[0]
if __name__ == "__main__":
sys.exit(main())
| <commit_before>"""
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import ami
import json
ami_rootdir = '/opt/ami'
r = ami.Reduce(ami_rootdir)
named_groups = r.group_pointings()
json.dump(named_groups, open('groups.json', 'w'),
sort_keys=True, indent=4)
<commit_msg>Make listings script executable, add argument handling.<commit_after>#!/usr/bin/python
"""
Groups AMI datasets by pointing direction,
then dumps them in JSON format.
"""
import json
import optparse
import sys
import ami
def main():
options, outputfilename = handle_args(sys.argv[1:])
r = ami.Reduce(options.amidir)
named_groups = r.group_pointings()
json.dump(named_groups, open(outputfilename, 'w'),
sort_keys=True, indent=4)
return 0
def handle_args(argv):
"""
Returns tuple (options_object, outputfilename)
"""
default_ami_dir = "/opt/ami"
default_array = 'LA'
usage = """usage: %prog [options] outputfile\n"""\
"""Outputs a file in JSON format listing AMI files, grouped by pointing."""
parser = optparse.OptionParser(usage)
parser.add_option("--amidir", default=default_ami_dir,
help="Path to AMI directory, default: " + default_ami_dir)
parser.add_option("--array", default=default_array,
help="Array data to work with (SA/LA), defaults to: "
+ default_array)
options, args = parser.parse_args(argv)
if len(args)!=1:
parser.print_help()
sys.exit(1)
print "Will output listings to file:", args[0]
return options, args[0]
if __name__ == "__main__":
sys.exit(main())
|
31c360fbdb3aa1393715e53ec4dfd86e59d68249 | staticgen_demo/staticgen_views.py | staticgen_demo/staticgen_views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils import translation
from cms.models import Title
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.dispatch import receiver
from django.utils import translation
from cms.models import Title
from cms.signals import page_moved, post_publish, post_unpublish
from staticgen.models import Page
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
@receiver((page_moved, post_publish, post_unpublish, ))
def mark_cms_page_as_changed(sender, **kwargs):
page = kwargs['instance']
language = kwargs['language']
public_url = page.get_public_url(language=language)
try:
page = Page.objects.get(path=public_url)
except Page.DoesNotExist:
pass
else:
page.publisher_state = Page.PUBLISHER_STATE_CHANGED
page.save()
| Mark CMS pages as changed .. using CMS publisher signals. | Mark CMS pages as changed .. using CMS publisher signals.
| Python | bsd-3-clause | mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils import translation
from cms.models import Title
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
Mark CMS pages as changed .. using CMS publisher signals. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.dispatch import receiver
from django.utils import translation
from cms.models import Title
from cms.signals import page_moved, post_publish, post_unpublish
from staticgen.models import Page
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
@receiver((page_moved, post_publish, post_unpublish, ))
def mark_cms_page_as_changed(sender, **kwargs):
page = kwargs['instance']
language = kwargs['language']
public_url = page.get_public_url(language=language)
try:
page = Page.objects.get(path=public_url)
except Page.DoesNotExist:
pass
else:
page.publisher_state = Page.PUBLISHER_STATE_CHANGED
page.save()
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils import translation
from cms.models import Title
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
<commit_msg>Mark CMS pages as changed .. using CMS publisher signals.<commit_after> | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.dispatch import receiver
from django.utils import translation
from cms.models import Title
from cms.signals import page_moved, post_publish, post_unpublish
from staticgen.models import Page
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
@receiver((page_moved, post_publish, post_unpublish, ))
def mark_cms_page_as_changed(sender, **kwargs):
page = kwargs['instance']
language = kwargs['language']
public_url = page.get_public_url(language=language)
try:
page = Page.objects.get(path=public_url)
except Page.DoesNotExist:
pass
else:
page.publisher_state = Page.PUBLISHER_STATE_CHANGED
page.save()
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils import translation
from cms.models import Title
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
Mark CMS pages as changed .. using CMS publisher signals.# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.dispatch import receiver
from django.utils import translation
from cms.models import Title
from cms.signals import page_moved, post_publish, post_unpublish
from staticgen.models import Page
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
@receiver((page_moved, post_publish, post_unpublish, ))
def mark_cms_page_as_changed(sender, **kwargs):
page = kwargs['instance']
language = kwargs['language']
public_url = page.get_public_url(language=language)
try:
page = Page.objects.get(path=public_url)
except Page.DoesNotExist:
pass
else:
page.publisher_state = Page.PUBLISHER_STATE_CHANGED
page.save()
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.utils import translation
from cms.models import Title
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
<commit_msg>Mark CMS pages as changed .. using CMS publisher signals.<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.dispatch import receiver
from django.utils import translation
from cms.models import Title
from cms.signals import page_moved, post_publish, post_unpublish
from staticgen.models import Page
from staticgen.staticgen_pool import staticgen_pool
from staticgen.staticgen_views import StaticgenView
class StaicgenDemoStaticViews(StaticgenView):
def items(self):
return (
'django.contrib.sitemaps.views.sitemap',
'robots.txt',
'page_not_found',
'application_error',
)
staticgen_pool.register(StaicgenDemoStaticViews)
class StaticgenCMSView(StaticgenView):
def items(self):
items = Title.objects.public().filter(
page__login_required=False,
page__site_id=settings.SITE_ID,
).order_by('page__path')
return items
def url(self, obj):
translation.activate(obj.language)
url = obj.page.get_absolute_url(obj.language)
translation.deactivate()
return url
staticgen_pool.register(StaticgenCMSView)
@receiver((page_moved, post_publish, post_unpublish, ))
def mark_cms_page_as_changed(sender, **kwargs):
page = kwargs['instance']
language = kwargs['language']
public_url = page.get_public_url(language=language)
try:
page = Page.objects.get(path=public_url)
except Page.DoesNotExist:
pass
else:
page.publisher_state = Page.PUBLISHER_STATE_CHANGED
page.save()
|
50d447a546cd939594aeb8fda84167cef27f0d5e | msmbuilder/scripts/msmb.py | msmbuilder/scripts/msmb.py | """Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
class MSMBuilderApp(App):
def _subcommands(self):
cmds = super(MSMBuilderApp, self)._subcommands()
# sort the commands in some arbitrary order.
return sorted(cmds, key=lambda e: ''.join(x.__name__ for x in e.mro()))
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
| """Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
# Load external commands which register themselves
# with entry point msmbuilder.commands
from pkg_resources import iter_entry_points
for ep in iter_entry_points("msmbuilder.commands"):
external_command = ep.load()
# Some groups start with numbers for ordering
# Some start with descriptions e.g. "MSM"
# Let's set the group to start with ZZZ to put plugins last.
external_command._group = "ZZZ-External_" + external_command._group
class MSMBuilderApp(App):
pass
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
| Load plugins from entry point | Load plugins from entry point
| Python | lgpl-2.1 | brookehus/msmbuilder,stephenliu1989/msmbuilder,peastman/msmbuilder,brookehus/msmbuilder,dr-nate/msmbuilder,dotsdl/msmbuilder,peastman/msmbuilder,msultan/msmbuilder,mpharrigan/mixtape,stephenliu1989/msmbuilder,cxhernandez/msmbuilder,rmcgibbo/msmbuilder,cxhernandez/msmbuilder,msultan/msmbuilder,brookehus/msmbuilder,stephenliu1989/msmbuilder,msmbuilder/msmbuilder,msultan/msmbuilder,peastman/msmbuilder,dr-nate/msmbuilder,Eigenstate/msmbuilder,brookehus/msmbuilder,dr-nate/msmbuilder,dotsdl/msmbuilder,brookehus/msmbuilder,peastman/msmbuilder,mpharrigan/mixtape,Eigenstate/msmbuilder,msmbuilder/msmbuilder,dotsdl/msmbuilder,rmcgibbo/msmbuilder,rafwiewiora/msmbuilder,mpharrigan/mixtape,rmcgibbo/msmbuilder,dotsdl/msmbuilder,stephenliu1989/msmbuilder,rmcgibbo/msmbuilder,mpharrigan/mixtape,msmbuilder/msmbuilder,msultan/msmbuilder,dr-nate/msmbuilder,dr-nate/msmbuilder,Eigenstate/msmbuilder,cxhernandez/msmbuilder,rafwiewiora/msmbuilder,rafwiewiora/msmbuilder,peastman/msmbuilder,msmbuilder/msmbuilder,cxhernandez/msmbuilder,rafwiewiora/msmbuilder,rafwiewiora/msmbuilder,Eigenstate/msmbuilder,msmbuilder/msmbuilder,msultan/msmbuilder,cxhernandez/msmbuilder,mpharrigan/mixtape,Eigenstate/msmbuilder | """Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
class MSMBuilderApp(App):
def _subcommands(self):
cmds = super(MSMBuilderApp, self)._subcommands()
# sort the commands in some arbitrary order.
return sorted(cmds, key=lambda e: ''.join(x.__name__ for x in e.mro()))
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
Load plugins from entry point | """Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
# Load external commands which register themselves
# with entry point msmbuilder.commands
from pkg_resources import iter_entry_points
for ep in iter_entry_points("msmbuilder.commands"):
external_command = ep.load()
# Some groups start with numbers for ordering
# Some start with descriptions e.g. "MSM"
# Let's set the group to start with ZZZ to put plugins last.
external_command._group = "ZZZ-External_" + external_command._group
class MSMBuilderApp(App):
pass
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
| <commit_before>"""Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
class MSMBuilderApp(App):
def _subcommands(self):
cmds = super(MSMBuilderApp, self)._subcommands()
# sort the commands in some arbitrary order.
return sorted(cmds, key=lambda e: ''.join(x.__name__ for x in e.mro()))
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
<commit_msg>Load plugins from entry point<commit_after> | """Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
# Load external commands which register themselves
# with entry point msmbuilder.commands
from pkg_resources import iter_entry_points
for ep in iter_entry_points("msmbuilder.commands"):
external_command = ep.load()
# Some groups start with numbers for ordering
# Some start with descriptions e.g. "MSM"
# Let's set the group to start with ZZZ to put plugins last.
external_command._group = "ZZZ-External_" + external_command._group
class MSMBuilderApp(App):
pass
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
| """Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
class MSMBuilderApp(App):
def _subcommands(self):
cmds = super(MSMBuilderApp, self)._subcommands()
# sort the commands in some arbitrary order.
return sorted(cmds, key=lambda e: ''.join(x.__name__ for x in e.mro()))
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
Load plugins from entry point"""Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
# Load external commands which register themselves
# with entry point msmbuilder.commands
from pkg_resources import iter_entry_points
for ep in iter_entry_points("msmbuilder.commands"):
external_command = ep.load()
# Some groups start with numbers for ordering
# Some start with descriptions e.g. "MSM"
# Let's set the group to start with ZZZ to put plugins last.
external_command._group = "ZZZ-External_" + external_command._group
class MSMBuilderApp(App):
pass
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
| <commit_before>"""Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
class MSMBuilderApp(App):
def _subcommands(self):
cmds = super(MSMBuilderApp, self)._subcommands()
# sort the commands in some arbitrary order.
return sorted(cmds, key=lambda e: ''.join(x.__name__ for x in e.mro()))
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
<commit_msg>Load plugins from entry point<commit_after>"""Statistical models for biomolecular dynamics"""
from __future__ import print_function, absolute_import, division
import sys
from ..cmdline import App
from ..commands import *
from ..version import version
# the commands register themselves when they're imported
# Load external commands which register themselves
# with entry point msmbuilder.commands
from pkg_resources import iter_entry_points
for ep in iter_entry_points("msmbuilder.commands"):
external_command = ep.load()
# Some groups start with numbers for ordering
# Some start with descriptions e.g. "MSM"
# Let's set the group to start with ZZZ to put plugins last.
external_command._group = "ZZZ-External_" + external_command._group
class MSMBuilderApp(App):
pass
def main():
try:
app = MSMBuilderApp(name='MSMBuilder', description=__doc__)
app.start()
except RuntimeError as e:
sys.exit("Error: %s" % e)
except Exception as e:
message = """\
An unexpected error has occurred with MSMBuilder (version %s), please
consider sending the following traceback to MSMBuilder GitHub issue tracker at:
https://github.com/msmbuilder/msmbuilder/issues
"""
print(message % version, file=sys.stderr)
raise # as if we did not catch it
if __name__ == '__main__':
main()
|
f9d63b418f69c77b01f9bed1d05fecdf8c028e7e | mvw/generator.py | mvw/generator.py | import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
relpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
print(os.path.join(relpath, f))
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(relpath, d))
| import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
src = os.path.join(root, f)
base, ext = os.path.splitext(f)
if ext in ['.md', '.markdown']:
dest = os.path.join(destpath, "%s%s" % (base, '.html'))
self.parse(src, dest)
else:
dest = os.path.join(destpath, f)
self.copy(src, dest)
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(destpath, d))
def parse(self, source, destination):
print("Parse Source: %s Destination: %s" % (source, destination))
def copy(self, source, destination):
print("Copy Source: %s Destination: %s" % (source, destination))
| Call parse with markdown files, copy otherwise | Call parse with markdown files, copy otherwise
| Python | mit | kevinbeaty/mvw | import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
relpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
print(os.path.join(relpath, f))
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(relpath, d))
Call parse with markdown files, copy otherwise | import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
src = os.path.join(root, f)
base, ext = os.path.splitext(f)
if ext in ['.md', '.markdown']:
dest = os.path.join(destpath, "%s%s" % (base, '.html'))
self.parse(src, dest)
else:
dest = os.path.join(destpath, f)
self.copy(src, dest)
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(destpath, d))
def parse(self, source, destination):
print("Parse Source: %s Destination: %s" % (source, destination))
def copy(self, source, destination):
print("Copy Source: %s Destination: %s" % (source, destination))
| <commit_before>import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
relpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
print(os.path.join(relpath, f))
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(relpath, d))
<commit_msg>Call parse with markdown files, copy otherwise<commit_after> | import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
src = os.path.join(root, f)
base, ext = os.path.splitext(f)
if ext in ['.md', '.markdown']:
dest = os.path.join(destpath, "%s%s" % (base, '.html'))
self.parse(src, dest)
else:
dest = os.path.join(destpath, f)
self.copy(src, dest)
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(destpath, d))
def parse(self, source, destination):
print("Parse Source: %s Destination: %s" % (source, destination))
def copy(self, source, destination):
print("Copy Source: %s Destination: %s" % (source, destination))
| import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
relpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
print(os.path.join(relpath, f))
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(relpath, d))
Call parse with markdown files, copy otherwiseimport os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
src = os.path.join(root, f)
base, ext = os.path.splitext(f)
if ext in ['.md', '.markdown']:
dest = os.path.join(destpath, "%s%s" % (base, '.html'))
self.parse(src, dest)
else:
dest = os.path.join(destpath, f)
self.copy(src, dest)
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(destpath, d))
def parse(self, source, destination):
print("Parse Source: %s Destination: %s" % (source, destination))
def copy(self, source, destination):
print("Copy Source: %s Destination: %s" % (source, destination))
| <commit_before>import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
relpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
print(os.path.join(relpath, f))
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(relpath, d))
<commit_msg>Call parse with markdown files, copy otherwise<commit_after>import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(outputdir, root[prefix:])
print()
print('-'*25)
print('Pages')
for f in files:
src = os.path.join(root, f)
base, ext = os.path.splitext(f)
if ext in ['.md', '.markdown']:
dest = os.path.join(destpath, "%s%s" % (base, '.html'))
self.parse(src, dest)
else:
dest = os.path.join(destpath, f)
self.copy(src, dest)
print('-'*25)
print('Dirs')
for d in dirs:
print(os.path.join(destpath, d))
def parse(self, source, destination):
print("Parse Source: %s Destination: %s" % (source, destination))
def copy(self, source, destination):
print("Copy Source: %s Destination: %s" % (source, destination))
|
931024e081d380a5f754920c7992b359ce2cd2de | celery_progress/__init__.py | celery_progress/__init__.py | from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings, 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
| from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings.configure(), 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
| Call configure() on settings to ensure that the CELERY_PROGRESS_BACKEND variable can be picked up | Call configure() on settings to ensure that the CELERY_PROGRESS_BACKEND variable can be picked up
| Python | bsd-3-clause | annaisystems/django-celery-progress,annaisystems/django-celery-progress,annaisystems/django-celery-progress | from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings, 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
Call configure() on settings to ensure that the CELERY_PROGRESS_BACKEND variable can be picked up | from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings.configure(), 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
| <commit_before>from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings, 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
<commit_msg>Call configure() on settings to ensure that the CELERY_PROGRESS_BACKEND variable can be picked up<commit_after> | from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings.configure(), 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
| from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings, 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
Call configure() on settings to ensure that the CELERY_PROGRESS_BACKEND variable can be picked upfrom django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings.configure(), 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
| <commit_before>from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings, 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
<commit_msg>Call configure() on settings to ensure that the CELERY_PROGRESS_BACKEND variable can be picked up<commit_after>from django.conf import settings
from django.utils.module_loading import import_by_path
BACKEND = getattr(settings.configure(), 'CELERY_PROGRESS_BACKEND',
'celery_progress.backends.CeleryBackend')
def get_backend():
return import_by_path(BACKEND)
backend = get_backend()()
|
b982fcd13400e6e05c4b711f034f360bdbdbe07d | test/test_logger.py | test/test_logger.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="1.1.0")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="0.12.3")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
| Modify an importer skip minversion | Modify an importer skip minversion
| Python | mit | thombashi/pytablewriter | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="1.1.0")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
Modify an importer skip minversion | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="0.12.3")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
| <commit_before># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="1.1.0")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
<commit_msg>Modify an importer skip minversion<commit_after> | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="0.12.3")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="1.1.0")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
Modify an importer skip minversion# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="0.12.3")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
| <commit_before># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="1.1.0")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
<commit_msg>Modify an importer skip minversion<commit_after># encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function, unicode_literals
import pytest
from pytablewriter import set_log_level, set_logger
logbook = pytest.importorskip("logbook", minversion="0.12.3")
import logbook # isort:skip
class Test_set_logger(object):
@pytest.mark.parametrize(["value"], [[True], [False]])
def test_smoke(self, value):
set_logger(value)
class Test_set_log_level(object):
@pytest.mark.parametrize(
["value"],
[
[logbook.CRITICAL],
[logbook.ERROR],
[logbook.WARNING],
[logbook.NOTICE],
[logbook.INFO],
[logbook.DEBUG],
[logbook.TRACE],
[logbook.NOTSET],
],
)
def test_smoke(self, value):
set_log_level(value)
@pytest.mark.parametrize(
["value", "expected"], [[None, LookupError], ["unexpected", LookupError]]
)
def test_exception(self, value, expected):
with pytest.raises(expected):
set_log_level(value)
|
18cbf5c9b357dc2941fd268b87a65649a086ab01 | IPython/html/widgets/widget_output.py | IPython/html/widgets/widget_output.py | """Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
class Output(DOMWidget):
"""Displays multiple widgets in a group."""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
| """Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
from IPython.testing.skipdoctest import skip_doctest
@skip_doctest
class Output(DOMWidget):
"""Widget used as a context manager to display output.
This widget can capture and display stdout, stderr, and rich output. To use
it, create an instance of it and display it. Then use it as a context
manager. Any output produced while in it's context will be captured and
displayed in it instead of the standard output area.
Example
from IPython.html import widgets
from IPython.display import display
out = widgets.Output()
display(out)
print('prints to output area')
with out:
print('prints to output widget')"""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
| Add doc string to Output widget | Add doc string to Output widget
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | """Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
class Output(DOMWidget):
"""Displays multiple widgets in a group."""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
Add doc string to Output widget | """Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
from IPython.testing.skipdoctest import skip_doctest
@skip_doctest
class Output(DOMWidget):
"""Widget used as a context manager to display output.
This widget can capture and display stdout, stderr, and rich output. To use
it, create an instance of it and display it. Then use it as a context
manager. Any output produced while in it's context will be captured and
displayed in it instead of the standard output area.
Example
from IPython.html import widgets
from IPython.display import display
out = widgets.Output()
display(out)
print('prints to output area')
with out:
print('prints to output widget')"""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
| <commit_before>"""Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
class Output(DOMWidget):
"""Displays multiple widgets in a group."""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
<commit_msg>Add doc string to Output widget<commit_after> | """Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
from IPython.testing.skipdoctest import skip_doctest
@skip_doctest
class Output(DOMWidget):
"""Widget used as a context manager to display output.
This widget can capture and display stdout, stderr, and rich output. To use
it, create an instance of it and display it. Then use it as a context
manager. Any output produced while in it's context will be captured and
displayed in it instead of the standard output area.
Example
from IPython.html import widgets
from IPython.display import display
out = widgets.Output()
display(out)
print('prints to output area')
with out:
print('prints to output widget')"""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
| """Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
class Output(DOMWidget):
"""Displays multiple widgets in a group."""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
Add doc string to Output widget"""Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
from IPython.testing.skipdoctest import skip_doctest
@skip_doctest
class Output(DOMWidget):
"""Widget used as a context manager to display output.
This widget can capture and display stdout, stderr, and rich output. To use
it, create an instance of it and display it. Then use it as a context
manager. Any output produced while in it's context will be captured and
displayed in it instead of the standard output area.
Example
from IPython.html import widgets
from IPython.display import display
out = widgets.Output()
display(out)
print('prints to output area')
with out:
print('prints to output widget')"""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
| <commit_before>"""Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
class Output(DOMWidget):
"""Displays multiple widgets in a group."""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
<commit_msg>Add doc string to Output widget<commit_after>"""Output class.
Represents a widget that can be used to display output within the widget area.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
import sys
from IPython.utils.traitlets import Unicode, List
from IPython.display import clear_output
from IPython.testing.skipdoctest import skip_doctest
@skip_doctest
class Output(DOMWidget):
"""Widget used as a context manager to display output.
This widget can capture and display stdout, stderr, and rich output. To use
it, create an instance of it and display it. Then use it as a context
manager. Any output produced while in it's context will be captured and
displayed in it instead of the standard output area.
Example
from IPython.html import widgets
from IPython.display import display
out = widgets.Output()
display(out)
print('prints to output area')
with out:
print('prints to output widget')"""
_view_name = Unicode('OutputView', sync=True)
def clear_output(self, *pargs, **kwargs):
with self:
clear_output(*pargs, **kwargs)
def __enter__(self):
self._flush()
self.send({'method': 'push'})
def __exit__(self, exception_type, exception_value, traceback):
self._flush()
self.send({'method': 'pop'})
def _flush(self):
sys.stdout.flush()
sys.stderr.flush()
|
b6b9c6f3f8faaade428d044f93acd25edade075d | tools/pdtools/pdtools/__main__.py | tools/pdtools/pdtools/__main__.py | """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
@click.group()
@click.pass_context
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
# Options can be parsed from PDTOOLS_* environment variables.
ctx.auto_envvar_prefix = 'PDTOOLS'
# Respond to both -h and --help for all commands.
ctx.help_option_names = ['-h', '--help']
ctx.obj = {
'pdserver_url': PDSERVER_URL
}
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
| """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
CONTEXT_SETTINGS = dict(
# Options can be parsed from PDTOOLS_* environment variables.
auto_envvar_prefix = 'PDTOOLS',
# Respond to both -h and --help for all commands.
help_option_names = ['-h', '--help'],
obj = {
'pdserver_url': PDSERVER_URL
}
)
@click.group(context_settings=CONTEXT_SETTINGS)
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
pass
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
| Enable '-h' help option from the pdtools root level. | Enable '-h' help option from the pdtools root level.
| Python | apache-2.0 | ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop | """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
@click.group()
@click.pass_context
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
# Options can be parsed from PDTOOLS_* environment variables.
ctx.auto_envvar_prefix = 'PDTOOLS'
# Respond to both -h and --help for all commands.
ctx.help_option_names = ['-h', '--help']
ctx.obj = {
'pdserver_url': PDSERVER_URL
}
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
Enable '-h' help option from the pdtools root level. | """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
CONTEXT_SETTINGS = dict(
# Options can be parsed from PDTOOLS_* environment variables.
auto_envvar_prefix = 'PDTOOLS',
# Respond to both -h and --help for all commands.
help_option_names = ['-h', '--help'],
obj = {
'pdserver_url': PDSERVER_URL
}
)
@click.group(context_settings=CONTEXT_SETTINGS)
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
pass
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
| <commit_before>"""
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
@click.group()
@click.pass_context
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
# Options can be parsed from PDTOOLS_* environment variables.
ctx.auto_envvar_prefix = 'PDTOOLS'
# Respond to both -h and --help for all commands.
ctx.help_option_names = ['-h', '--help']
ctx.obj = {
'pdserver_url': PDSERVER_URL
}
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
<commit_msg>Enable '-h' help option from the pdtools root level.<commit_after> | """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
CONTEXT_SETTINGS = dict(
# Options can be parsed from PDTOOLS_* environment variables.
auto_envvar_prefix = 'PDTOOLS',
# Respond to both -h and --help for all commands.
help_option_names = ['-h', '--help'],
obj = {
'pdserver_url': PDSERVER_URL
}
)
@click.group(context_settings=CONTEXT_SETTINGS)
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
pass
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
| """
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
@click.group()
@click.pass_context
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
# Options can be parsed from PDTOOLS_* environment variables.
ctx.auto_envvar_prefix = 'PDTOOLS'
# Respond to both -h and --help for all commands.
ctx.help_option_names = ['-h', '--help']
ctx.obj = {
'pdserver_url': PDSERVER_URL
}
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
Enable '-h' help option from the pdtools root level."""
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
CONTEXT_SETTINGS = dict(
# Options can be parsed from PDTOOLS_* environment variables.
auto_envvar_prefix = 'PDTOOLS',
# Respond to both -h and --help for all commands.
help_option_names = ['-h', '--help'],
obj = {
'pdserver_url': PDSERVER_URL
}
)
@click.group(context_settings=CONTEXT_SETTINGS)
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
pass
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
| <commit_before>"""
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
@click.group()
@click.pass_context
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
# Options can be parsed from PDTOOLS_* environment variables.
ctx.auto_envvar_prefix = 'PDTOOLS'
# Respond to both -h and --help for all commands.
ctx.help_option_names = ['-h', '--help']
ctx.obj = {
'pdserver_url': PDSERVER_URL
}
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
<commit_msg>Enable '-h' help option from the pdtools root level.<commit_after>"""
Paradrop command line utility.
Environment Variables:
PDSERVER_URL Paradrop controller URL [default: https://paradrop.org].
"""
import os
import click
from . import chute
from . import device
from . import routers
from . import store
PDSERVER_URL = os.environ.get("PDSERVER_URL", "https://paradrop.org")
CONTEXT_SETTINGS = dict(
# Options can be parsed from PDTOOLS_* environment variables.
auto_envvar_prefix = 'PDTOOLS',
# Respond to both -h and --help for all commands.
help_option_names = ['-h', '--help'],
obj = {
'pdserver_url': PDSERVER_URL
}
)
@click.group(context_settings=CONTEXT_SETTINGS)
def root(ctx):
"""
Paradrop command line utility.
Environment Variables
PDSERVER_URL ParaDrop controller URL [default: https://paradrop.org]
"""
pass
root.add_command(chute.chute)
root.add_command(device.device)
root.add_command(routers.routers)
root.add_command(store.store)
def main():
"""
Entry point for the pdtools Python package.
"""
root()
if __name__ == "__main__":
main()
|
d546d6901859a5fee8a16ffea6df560ecbb1e280 | tests/unit_tests.py | tests/unit_tests.py | #!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
float_list = self.of.get_oxy_floats()
print len(float_list)
self.assertNotEqual(len(float_list), 0)
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
self.oga_floats = self.of.get_oxy_floats()
self.assertNotEqual(len(self.oga_floats), 0)
def _get_dac_urls(self):
# Testing with a float that has data
oga_floats = ['1900650']
for dac_url in self.of.get_dac_urls(oga_floats):
self.dac_url = dac_url
self.assertTrue(self.dac_url.startswith('http'))
break
def _get_profile_opendap_urls(self):
for profile_url in self.of.get_profile_opendap_urls(self.dac_url):
self.profile_url = profile_url
break
def _get_profile_data(self):
d = self.of.get_profile_data(self.profile_url)
self.assertNotEqual(len(d), 0)
def test_read_data(self):
# Methods need to be called in order
self._get_dac_urls()
self._get_profile_opendap_urls()
self._get_profile_data()
if __name__ == '__main__':
unittest.main()
| Add tests for reading profile data | Add tests for reading profile data
| Python | mit | biofloat/biofloat,MBARIMike/biofloat,biofloat/biofloat,MBARIMike/biofloat,MBARIMike/oxyfloat,MBARIMike/oxyfloat | #!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
float_list = self.of.get_oxy_floats()
print len(float_list)
self.assertNotEqual(len(float_list), 0)
if __name__ == '__main__':
unittest.main()
Add tests for reading profile data | #!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
self.oga_floats = self.of.get_oxy_floats()
self.assertNotEqual(len(self.oga_floats), 0)
def _get_dac_urls(self):
# Testing with a float that has data
oga_floats = ['1900650']
for dac_url in self.of.get_dac_urls(oga_floats):
self.dac_url = dac_url
self.assertTrue(self.dac_url.startswith('http'))
break
def _get_profile_opendap_urls(self):
for profile_url in self.of.get_profile_opendap_urls(self.dac_url):
self.profile_url = profile_url
break
def _get_profile_data(self):
d = self.of.get_profile_data(self.profile_url)
self.assertNotEqual(len(d), 0)
def test_read_data(self):
# Methods need to be called in order
self._get_dac_urls()
self._get_profile_opendap_urls()
self._get_profile_data()
if __name__ == '__main__':
unittest.main()
| <commit_before>#!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
float_list = self.of.get_oxy_floats()
print len(float_list)
self.assertNotEqual(len(float_list), 0)
if __name__ == '__main__':
unittest.main()
<commit_msg>Add tests for reading profile data<commit_after> | #!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
self.oga_floats = self.of.get_oxy_floats()
self.assertNotEqual(len(self.oga_floats), 0)
def _get_dac_urls(self):
# Testing with a float that has data
oga_floats = ['1900650']
for dac_url in self.of.get_dac_urls(oga_floats):
self.dac_url = dac_url
self.assertTrue(self.dac_url.startswith('http'))
break
def _get_profile_opendap_urls(self):
for profile_url in self.of.get_profile_opendap_urls(self.dac_url):
self.profile_url = profile_url
break
def _get_profile_data(self):
d = self.of.get_profile_data(self.profile_url)
self.assertNotEqual(len(d), 0)
def test_read_data(self):
# Methods need to be called in order
self._get_dac_urls()
self._get_profile_opendap_urls()
self._get_profile_data()
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
float_list = self.of.get_oxy_floats()
print len(float_list)
self.assertNotEqual(len(float_list), 0)
if __name__ == '__main__':
unittest.main()
Add tests for reading profile data#!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
self.oga_floats = self.of.get_oxy_floats()
self.assertNotEqual(len(self.oga_floats), 0)
def _get_dac_urls(self):
# Testing with a float that has data
oga_floats = ['1900650']
for dac_url in self.of.get_dac_urls(oga_floats):
self.dac_url = dac_url
self.assertTrue(self.dac_url.startswith('http'))
break
def _get_profile_opendap_urls(self):
for profile_url in self.of.get_profile_opendap_urls(self.dac_url):
self.profile_url = profile_url
break
def _get_profile_data(self):
d = self.of.get_profile_data(self.profile_url)
self.assertNotEqual(len(d), 0)
def test_read_data(self):
# Methods need to be called in order
self._get_dac_urls()
self._get_profile_opendap_urls()
self._get_profile_data()
if __name__ == '__main__':
unittest.main()
| <commit_before>#!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
float_list = self.of.get_oxy_floats()
print len(float_list)
self.assertNotEqual(len(float_list), 0)
if __name__ == '__main__':
unittest.main()
<commit_msg>Add tests for reading profile data<commit_after>#!/usr/bin/env python
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
self.oga_floats = self.of.get_oxy_floats()
self.assertNotEqual(len(self.oga_floats), 0)
def _get_dac_urls(self):
# Testing with a float that has data
oga_floats = ['1900650']
for dac_url in self.of.get_dac_urls(oga_floats):
self.dac_url = dac_url
self.assertTrue(self.dac_url.startswith('http'))
break
def _get_profile_opendap_urls(self):
for profile_url in self.of.get_profile_opendap_urls(self.dac_url):
self.profile_url = profile_url
break
def _get_profile_data(self):
d = self.of.get_profile_data(self.profile_url)
self.assertNotEqual(len(d), 0)
def test_read_data(self):
# Methods need to be called in order
self._get_dac_urls()
self._get_profile_opendap_urls()
self._get_profile_data()
if __name__ == '__main__':
unittest.main()
|
39f44c926eb16f2cd57fa344318bce652b158a3a | tests/shape/test_basic.py | tests/shape/test_basic.py | import pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
| import pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
@pytest.mark.shape
class TestTriangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Triangle` shape."""
def setUp(self):
self.shape = Triangle((1,.5),(.2,1),(.4,.5))
| Add Triangle to shape tests | Add Triangle to shape tests
| Python | mit | alcarney/stylo,alcarney/stylo | import pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
Add Triangle to shape tests | import pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
@pytest.mark.shape
class TestTriangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Triangle` shape."""
def setUp(self):
self.shape = Triangle((1,.5),(.2,1),(.4,.5))
| <commit_before>import pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
<commit_msg>Add Triangle to shape tests<commit_after> | import pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
@pytest.mark.shape
class TestTriangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Triangle` shape."""
def setUp(self):
self.shape = Triangle((1,.5),(.2,1),(.4,.5))
| import pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
Add Triangle to shape testsimport pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
@pytest.mark.shape
class TestTriangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Triangle` shape."""
def setUp(self):
self.shape = Triangle((1,.5),(.2,1),(.4,.5))
| <commit_before>import pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
<commit_msg>Add Triangle to shape tests<commit_after>import pytest
from unittest import TestCase
from stylo.shape import Ellipse, Circle, Rectangle, Square, Triangle
from stylo.testing.shape import BaseShapeTest
@pytest.mark.shape
class TestEllipse(TestCase, BaseShapeTest):
"""Tests for the :code:`Ellipse` shape."""
def setUp(self):
self.shape = Ellipse(0, 0, 1 / 2, 1 / 3, 0.6)
@pytest.mark.shape
class TestCircle(TestCase, BaseShapeTest):
"""Tests for the :code:`Circle` shape."""
def setUp(self):
self.shape = Circle(0, 0, 0.5)
@pytest.mark.shape
class TestRectangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Rectangle` shape."""
def setUp(self):
self.shape = Rectangle(0, 0, 0.6, 0.3)
@pytest.mark.shape
class TestSquare(TestCase, BaseShapeTest):
"""Tests for the :code:`Square` shape."""
def setUp(self):
self.shape = Square(0, 0, 0.75)
@pytest.mark.shape
class TestTriangle(TestCase, BaseShapeTest):
"""Tests for the :code:`Triangle` shape."""
def setUp(self):
self.shape = Triangle((1,.5),(.2,1),(.4,.5))
|
ca641bb6bfc65d82564cee684bc3192986806b71 | vdb/flu_download.py | vdb/flu_download.py | import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'source', 'locus', 'authors']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__) | import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'passage_category', 'submitting_lab']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__) | Revise flu fasta fields to interface with nextflu. | Revise flu fasta fields to interface with nextflu.
| Python | agpl-3.0 | blab/nextstrain-db,nextstrain/fauna,nextstrain/fauna,blab/nextstrain-db | import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'source', 'locus', 'authors']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__)Revise flu fasta fields to interface with nextflu. | import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'passage_category', 'submitting_lab']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__) | <commit_before>import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'source', 'locus', 'authors']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__)<commit_msg>Revise flu fasta fields to interface with nextflu.<commit_after> | import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'passage_category', 'submitting_lab']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__) | import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'source', 'locus', 'authors']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__)Revise flu fasta fields to interface with nextflu.import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'passage_category', 'submitting_lab']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__) | <commit_before>import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'source', 'locus', 'authors']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__)<commit_msg>Revise flu fasta fields to interface with nextflu.<commit_after>import os,datetime
from download import download
from download import get_parser
class flu_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
if __name__=="__main__":
parser = get_parser()
args = parser.parse_args()
fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'passage_category', 'submitting_lab']
args.fasta_fields = fasta_fields
current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d'))
if args.fstem is None:
args.fstem = args.virus + '_' + current_date
if not os.path.isdir(args.path):
os.makedirs(args.path)
connfluVDB = flu_download(**args.__dict__)
connfluVDB.download(**args.__dict__) |
215401f586a6960c4165debf698f3a95c75a178b | comrade/views/simple.py | comrade/views/simple.py | from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, status=None,
mimetype=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
| from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, mimetype=None,
status=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status argument.
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
| Make status the last optional arg. | Make status the last optional arg.
| Python | mit | bueda/django-comrade | from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, status=None,
mimetype=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
Make status the last optional arg. | from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, mimetype=None,
status=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status argument.
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
| <commit_before>from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, status=None,
mimetype=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
<commit_msg>Make status the last optional arg.<commit_after> | from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, mimetype=None,
status=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status argument.
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
| from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, status=None,
mimetype=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
Make status the last optional arg.from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, mimetype=None,
status=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status argument.
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
| <commit_before>from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, status=None,
mimetype=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
<commit_msg>Make status the last optional arg.<commit_after>from django.http import HttpResponse, HttpResponseServerError
from django.template import RequestContext, loader
from django.conf import settings
from maintenancemode.http import HttpResponseTemporaryUnavailable
import logging
logger = logging.getLogger('comrade.views.simple')
def status(request):
logger.info("Responding to status check")
return HttpResponse()
def server_error(request, template_name='500.html'):
t = loader.get_template(template_name)
return HttpResponseServerError(t.render(RequestContext(request)))
def maintenance_mode(request, template_name='503.html'):
t = loader.get_template(template_name)
return HttpResponseTemporaryUnavailable(t.render(RequestContext(request)))
def direct_to_template(request, template, extra_context=None, mimetype=None,
status=None, **kwargs):
'''
Duplicates behavior of django.views.generic.simple.direct_to_template
but accepts a status argument.
'''
if extra_context is None:
extra_context = {}
dictionary = {'params': kwargs}
for key, value in extra_context.items():
if callable(value):
dictionary[key] = value()
else:
dictionary[key] = value
c = RequestContext(request, dictionary)
t = loader.get_template(template)
return HttpResponse(t.render(c), status=status,
mimetype=mimetype)
|
80347266377f01932fe8277c7a12ce87663b9018 | comtypes/messageloop.py | comtypes/messageloop.py | import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
for filter in self._filters:
if filter(lpmsg):
return True
return False
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
| import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
return any(filter(lpmsg) for filter in self._filters)
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
| Use any for concise code | Use any for concise code
| Python | mit | denfromufa/comtypes,denfromufa/comtypes,denfromufa/comtypes,denfromufa/comtypes,denfromufa/comtypes | import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
for filter in self._filters:
if filter(lpmsg):
return True
return False
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
Use any for concise code | import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
return any(filter(lpmsg) for filter in self._filters)
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
| <commit_before>import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
for filter in self._filters:
if filter(lpmsg):
return True
return False
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
<commit_msg>Use any for concise code<commit_after> | import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
return any(filter(lpmsg) for filter in self._filters)
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
| import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
for filter in self._filters:
if filter(lpmsg):
return True
return False
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
Use any for concise codeimport ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
return any(filter(lpmsg) for filter in self._filters)
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
| <commit_before>import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
for filter in self._filters:
if filter(lpmsg):
return True
return False
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
<commit_msg>Use any for concise code<commit_after>import ctypes
from ctypes import WinDLL, byref, WinError
from ctypes.wintypes import MSG
_user32 = WinDLL("user32")
GetMessage = _user32.GetMessageA
GetMessage.argtypes = [
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_uint,
ctypes.c_uint,
]
TranslateMessage = _user32.TranslateMessage
DispatchMessage = _user32.DispatchMessageA
class _MessageLoop(object):
def __init__(self):
self._filters = []
def insert_filter(self, obj, index=-1):
self._filters.insert(index, obj)
def remove_filter(self, obj):
self._filters.remove(obj)
def run(self):
msg = MSG()
lpmsg = byref(msg)
while 1:
ret = GetMessage(lpmsg, 0, 0, 0)
if ret == -1:
raise WinError()
elif ret == 0:
return # got WM_QUIT
if not self.filter_message(lpmsg):
TranslateMessage(lpmsg)
DispatchMessage(lpmsg)
def filter_message(self, lpmsg):
return any(filter(lpmsg) for filter in self._filters)
_messageloop = _MessageLoop()
run = _messageloop.run
insert_filter = _messageloop.insert_filter
remove_filter = _messageloop.remove_filter
__all__ = ["run", "insert_filter", "remove_filter"]
|
f768173dab101e8333766cd11f33599397c682d0 | dasem/__init__.py | dasem/__init__.py | """dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ['Word2Vec']
| """dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ('Word2Vec',)
| Change for style checking warning | Change for style checking warning
| Python | apache-2.0 | fnielsen/dasem,fnielsen/dasem | """dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ['Word2Vec']
Change for style checking warning | """dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ('Word2Vec',)
| <commit_before>"""dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ['Word2Vec']
<commit_msg>Change for style checking warning<commit_after> | """dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ('Word2Vec',)
| """dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ['Word2Vec']
Change for style checking warning"""dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ('Word2Vec',)
| <commit_before>"""dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ['Word2Vec']
<commit_msg>Change for style checking warning<commit_after>"""dasem."""
from __future__ import absolute_import
from .fullmonty import Word2Vec
__all__ = ('Word2Vec',)
|
58d739f8c229967b53655376a01c1e3af6034ae1 | cyder/base/constants.py | cyder/base/constants.py | ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'ipv4',
IP_TYPE_6: 'ipv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
| ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'IPv4',
IP_TYPE_6: 'IPv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
| Fix spelling of 'IPv4' and 'IPv6' (cosmetic) | Fix spelling of 'IPv4' and 'IPv6' (cosmetic)
| Python | bsd-3-clause | drkitty/cyder,akeym/cyder,OSU-Net/cyder,zeeman/cyder,zeeman/cyder,murrown/cyder,akeym/cyder,zeeman/cyder,OSU-Net/cyder,OSU-Net/cyder,drkitty/cyder,murrown/cyder,zeeman/cyder,murrown/cyder,akeym/cyder,OSU-Net/cyder,drkitty/cyder,murrown/cyder,akeym/cyder,drkitty/cyder | ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'ipv4',
IP_TYPE_6: 'ipv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
Fix spelling of 'IPv4' and 'IPv6' (cosmetic) | ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'IPv4',
IP_TYPE_6: 'IPv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
| <commit_before>ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'ipv4',
IP_TYPE_6: 'ipv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
<commit_msg>Fix spelling of 'IPv4' and 'IPv6' (cosmetic)<commit_after> | ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'IPv4',
IP_TYPE_6: 'IPv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
| ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'ipv4',
IP_TYPE_6: 'ipv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
Fix spelling of 'IPv4' and 'IPv6' (cosmetic)ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'IPv4',
IP_TYPE_6: 'IPv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
| <commit_before>ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'ipv4',
IP_TYPE_6: 'ipv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
<commit_msg>Fix spelling of 'IPv4' and 'IPv6' (cosmetic)<commit_after>ACTION_CREATE = 0
ACTION_VIEW = 1
ACTION_UPDATE = 2
ACTION_DELETE = 3
ACTIONS = {
ACTION_CREATE: 'Create',
ACTION_VIEW: 'View',
ACTION_UPDATE: 'Update',
ACTION_DELETE: 'Delete',
}
LEVEL_GUEST = 0
LEVEL_USER = 1
LEVEL_ADMIN = 2
LEVELS = {
LEVEL_GUEST: 'Guest',
LEVEL_USER: 'User',
LEVEL_ADMIN: 'Admin',
}
IP_TYPE_4 = '4'
IP_TYPE_6 = '6'
IP_TYPES = {
IP_TYPE_4: 'IPv4',
IP_TYPE_6: 'IPv6'
}
DHCP_OBJECTS = ("workgroup", "vrf", "vlan", "site", "range", "network",
"static_interface", "dynamic_interface", "workgroup_kv",
"vrf_kv", "vlan_kv", "site_kv", "range_kv", "network_kv",
"static_interface_kv", "dynamic_interface_kv",)
DNS_OBJECTS = ("address_record", "cname", "domain", "mx", "nameserver", "ptr",
"soa", "srv", "sshfp", "txt", "view",)
CORE_OBJECTS = ("ctnr_users", "ctnr", "user", "system")
|
c326becad43949999d151cd1e10fcb75f9d2b148 | lib/constants.py | lib/constants.py |
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
JSON_PUBSUB_PORT = 15596
|
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
HTTPS_PORT = 443
JSON_PUBSUB_PORT = 15596
| Add missing constant for ssl listener. | Add missing constant for ssl listener.
| Python | apache-2.0 | MediaMath/qasino,MediaMath/qasino |
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
JSON_PUBSUB_PORT = 15596
Add missing constant for ssl listener. |
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
HTTPS_PORT = 443
JSON_PUBSUB_PORT = 15596
| <commit_before>
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
JSON_PUBSUB_PORT = 15596
<commit_msg>Add missing constant for ssl listener.<commit_after> |
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
HTTPS_PORT = 443
JSON_PUBSUB_PORT = 15596
|
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
JSON_PUBSUB_PORT = 15596
Add missing constant for ssl listener.
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
HTTPS_PORT = 443
JSON_PUBSUB_PORT = 15596
| <commit_before>
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
JSON_PUBSUB_PORT = 15596
<commit_msg>Add missing constant for ssl listener.<commit_after>
SQL_PORT = 15000
JSON_RPC_PORT = 15598
HTTP_PORT = 15597
HTTPS_PORT = 443
JSON_PUBSUB_PORT = 15596
|
25628ca0b7065e8682f45b8e03e5f80a569c520d | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.9'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.10.dev0'
| Update dsub version to 0.3.10.dev0 | Update dsub version to 0.3.10.dev0
PiperOrigin-RevId: 319887839
| Python | apache-2.0 | DataBiosphere/dsub,DataBiosphere/dsub | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.9'
Update dsub version to 0.3.10.dev0
PiperOrigin-RevId: 319887839 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.10.dev0'
| <commit_before># Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.9'
<commit_msg>Update dsub version to 0.3.10.dev0
PiperOrigin-RevId: 319887839<commit_after> | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.10.dev0'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.9'
Update dsub version to 0.3.10.dev0
PiperOrigin-RevId: 319887839# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.10.dev0'
| <commit_before># Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.9'
<commit_msg>Update dsub version to 0.3.10.dev0
PiperOrigin-RevId: 319887839<commit_after># Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.10.dev0'
|
cd6752a2866631eeea0dcbcf37f24d825f5e4a50 | vpc/vpc_content/search_indexes.py | vpc/vpc_content/search_indexes.py | import datetime
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(SearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(SearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
| import datetime
from haystack.indexes import SearchIndex, RealTimeSearchIndex
from haystack.indexes import CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(RealTimeSearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(RealTimeSearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
| Make indexing on real time | Make indexing on real time
| Python | agpl-3.0 | voer-platform/vp.repo,voer-platform/vp.repo,voer-platform/vp.repo,voer-platform/vp.repo | import datetime
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(SearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(SearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
Make indexing on real time | import datetime
from haystack.indexes import SearchIndex, RealTimeSearchIndex
from haystack.indexes import CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(RealTimeSearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(RealTimeSearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
| <commit_before>import datetime
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(SearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(SearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
<commit_msg>Make indexing on real time<commit_after> | import datetime
from haystack.indexes import SearchIndex, RealTimeSearchIndex
from haystack.indexes import CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(RealTimeSearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(RealTimeSearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
| import datetime
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(SearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(SearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
Make indexing on real timeimport datetime
from haystack.indexes import SearchIndex, RealTimeSearchIndex
from haystack.indexes import CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(RealTimeSearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(RealTimeSearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
| <commit_before>import datetime
from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(SearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(SearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
<commit_msg>Make indexing on real time<commit_after>import datetime
from haystack.indexes import SearchIndex, RealTimeSearchIndex
from haystack.indexes import CharField, DateTimeField
from haystack import site
from models import Author, Material
class AuthorIndex(RealTimeSearchIndex):
# the used template contains fullname and author bio
# Zniper thinks this line below also is OK:
# text = CharField(document=True, model_attr='text')
fullname = CharField(model_attr='fullname')
text = CharField(document=True, use_template=True)
def index_queryset(self):
"""Used when entire index for model is updated"""
return Author.objects.all()
class MaterialIndex(RealTimeSearchIndex):
# "text" combines normal body, title, description and keywords
text = CharField(document=True, use_template=True)
material_id = CharField(model_attr='material_id')
title = CharField(model_attr='title')
description = CharField(model_attr='description')
modified = DateTimeField(model_attr='modified')
material_type = DateTimeField(model_attr='modified')
def index_queryset(self):
"""When entired index for model is updated"""
return Material.objects.all()
site.register(Author, AuthorIndex)
site.register(Material, MaterialIndex)
|
618909832a9df101d240c737786e28c761c76912 | json2csv.py | json2csv.py | import json
def main():
input_json = json.load(open("photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
| import json
def main():
input_json = json.load(open("photos/photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
| Change location of photos json file | Change location of photos json file | Python | mit | aysent/yelp-photo-explorer | import json
def main():
input_json = json.load(open("photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
Change location of photos json file | import json
def main():
input_json = json.load(open("photos/photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
| <commit_before>import json
def main():
input_json = json.load(open("photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
<commit_msg>Change location of photos json file<commit_after> | import json
def main():
input_json = json.load(open("photos/photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
| import json
def main():
input_json = json.load(open("photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
Change location of photos json fileimport json
def main():
input_json = json.load(open("photos/photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
| <commit_before>import json
def main():
input_json = json.load(open("photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
<commit_msg>Change location of photos json file<commit_after>import json
def main():
input_json = json.load(open("photos/photo_id_to_business_id.json"))
# print the header of output csv file
print 'photo_id,business_id,label'
# for each entry in input json file print one csv row
for i in xrange(len(input_json)):
photo_id = input_json[i]['photo_id']
business_id = input_json[i]['business_id']
label = input_json[i]['label']
print photo_id + ',' + business_id + ',' + label
if __name__ == "__main__":
main()
|
611165bccb307611945f7a44ecb8f66cf4381da6 | dbconnect.py | dbconnect.py | import MySQLdb
def connection():
conn = MySQLdb.connect(host="localhost",
user="root",
passwd="gichin124",
db="tripmeal")
c = conn.cursor()
return c, conn
| import MySQLdb
import urlparse
import os
urlparse.uses_netloc.append('mysql')
try:
if 'DATABASES' not in locals():
DATABASES = {}
if 'DATABASE_URL' in os.environ:
url = urlparse.urlparse(os.environ['DATABASE_URL'])
# Ensure default database exists.
DATABASES['default'] = DATABASES.get('default', {})
# Update with environment configuration.
DATABASES['default'].update({
'NAME': url.path[1:],
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': url.port,
})
if url.scheme == 'mysql':
DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
except Exception:
print 'Unexpected error:', sys.exc_info()
def connection():
conn = MySQLdb.connect(host=DATABASES['HOST'],
user=DATABASES['USER'],
passwd=DATABASES['PASSWORD'],
db=DATABASES['NAME']
)
# conn = MySQLdb.connect(host="localhost",
# user="root",
# passwd="gichin124",
# db="tripmeal")
c = conn.cursor()
return c, conn
| Add the new settings for the database | Add the new settings for the database
| Python | mit | DanielAndreasen/TripMeal,DanielAndreasen/TripMeal | import MySQLdb
def connection():
conn = MySQLdb.connect(host="localhost",
user="root",
passwd="gichin124",
db="tripmeal")
c = conn.cursor()
return c, conn
Add the new settings for the database | import MySQLdb
import urlparse
import os
urlparse.uses_netloc.append('mysql')
try:
if 'DATABASES' not in locals():
DATABASES = {}
if 'DATABASE_URL' in os.environ:
url = urlparse.urlparse(os.environ['DATABASE_URL'])
# Ensure default database exists.
DATABASES['default'] = DATABASES.get('default', {})
# Update with environment configuration.
DATABASES['default'].update({
'NAME': url.path[1:],
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': url.port,
})
if url.scheme == 'mysql':
DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
except Exception:
print 'Unexpected error:', sys.exc_info()
def connection():
conn = MySQLdb.connect(host=DATABASES['HOST'],
user=DATABASES['USER'],
passwd=DATABASES['PASSWORD'],
db=DATABASES['NAME']
)
# conn = MySQLdb.connect(host="localhost",
# user="root",
# passwd="gichin124",
# db="tripmeal")
c = conn.cursor()
return c, conn
| <commit_before>import MySQLdb
def connection():
conn = MySQLdb.connect(host="localhost",
user="root",
passwd="gichin124",
db="tripmeal")
c = conn.cursor()
return c, conn
<commit_msg>Add the new settings for the database<commit_after> | import MySQLdb
import urlparse
import os
urlparse.uses_netloc.append('mysql')
try:
if 'DATABASES' not in locals():
DATABASES = {}
if 'DATABASE_URL' in os.environ:
url = urlparse.urlparse(os.environ['DATABASE_URL'])
# Ensure default database exists.
DATABASES['default'] = DATABASES.get('default', {})
# Update with environment configuration.
DATABASES['default'].update({
'NAME': url.path[1:],
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': url.port,
})
if url.scheme == 'mysql':
DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
except Exception:
print 'Unexpected error:', sys.exc_info()
def connection():
conn = MySQLdb.connect(host=DATABASES['HOST'],
user=DATABASES['USER'],
passwd=DATABASES['PASSWORD'],
db=DATABASES['NAME']
)
# conn = MySQLdb.connect(host="localhost",
# user="root",
# passwd="gichin124",
# db="tripmeal")
c = conn.cursor()
return c, conn
| import MySQLdb
def connection():
conn = MySQLdb.connect(host="localhost",
user="root",
passwd="gichin124",
db="tripmeal")
c = conn.cursor()
return c, conn
Add the new settings for the databaseimport MySQLdb
import urlparse
import os
urlparse.uses_netloc.append('mysql')
try:
if 'DATABASES' not in locals():
DATABASES = {}
if 'DATABASE_URL' in os.environ:
url = urlparse.urlparse(os.environ['DATABASE_URL'])
# Ensure default database exists.
DATABASES['default'] = DATABASES.get('default', {})
# Update with environment configuration.
DATABASES['default'].update({
'NAME': url.path[1:],
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': url.port,
})
if url.scheme == 'mysql':
DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
except Exception:
print 'Unexpected error:', sys.exc_info()
def connection():
conn = MySQLdb.connect(host=DATABASES['HOST'],
user=DATABASES['USER'],
passwd=DATABASES['PASSWORD'],
db=DATABASES['NAME']
)
# conn = MySQLdb.connect(host="localhost",
# user="root",
# passwd="gichin124",
# db="tripmeal")
c = conn.cursor()
return c, conn
| <commit_before>import MySQLdb
def connection():
conn = MySQLdb.connect(host="localhost",
user="root",
passwd="gichin124",
db="tripmeal")
c = conn.cursor()
return c, conn
<commit_msg>Add the new settings for the database<commit_after>import MySQLdb
import urlparse
import os
urlparse.uses_netloc.append('mysql')
try:
if 'DATABASES' not in locals():
DATABASES = {}
if 'DATABASE_URL' in os.environ:
url = urlparse.urlparse(os.environ['DATABASE_URL'])
# Ensure default database exists.
DATABASES['default'] = DATABASES.get('default', {})
# Update with environment configuration.
DATABASES['default'].update({
'NAME': url.path[1:],
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': url.port,
})
if url.scheme == 'mysql':
DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
except Exception:
print 'Unexpected error:', sys.exc_info()
def connection():
conn = MySQLdb.connect(host=DATABASES['HOST'],
user=DATABASES['USER'],
passwd=DATABASES['PASSWORD'],
db=DATABASES['NAME']
)
# conn = MySQLdb.connect(host="localhost",
# user="root",
# passwd="gichin124",
# db="tripmeal")
c = conn.cursor()
return c, conn
|
d0c8968766a06e8c426e75edddb9c6ce88d080a0 | fsspec/implementations/tests/test_common.py | fsspec/implementations/tests/test_common.py | import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert modified > created
assert isinstance(created, datetime.datetime)
finally:
fs.rm(TEST_FILE)
| import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert isinstance(modified, datetime.datetime)
assert modified > created
finally:
fs.rm(TEST_FILE)
| Fix typo in test assertion | Fix typo in test assertion
| Python | bsd-3-clause | fsspec/filesystem_spec,intake/filesystem_spec,fsspec/filesystem_spec | import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert modified > created
assert isinstance(created, datetime.datetime)
finally:
fs.rm(TEST_FILE)
Fix typo in test assertion | import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert isinstance(modified, datetime.datetime)
assert modified > created
finally:
fs.rm(TEST_FILE)
| <commit_before>import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert modified > created
assert isinstance(created, datetime.datetime)
finally:
fs.rm(TEST_FILE)
<commit_msg>Fix typo in test assertion<commit_after> | import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert isinstance(modified, datetime.datetime)
assert modified > created
finally:
fs.rm(TEST_FILE)
| import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert modified > created
assert isinstance(created, datetime.datetime)
finally:
fs.rm(TEST_FILE)
Fix typo in test assertionimport datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert isinstance(modified, datetime.datetime)
assert modified > created
finally:
fs.rm(TEST_FILE)
| <commit_before>import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert modified > created
assert isinstance(created, datetime.datetime)
finally:
fs.rm(TEST_FILE)
<commit_msg>Fix typo in test assertion<commit_after>import datetime
import pytest
from fsspec import AbstractFileSystem
from fsspec.implementations.tests.conftest import READ_ONLY_FILESYSTEMS
TEST_FILE = 'file'
@pytest.mark.parametrize("fs", ['local'], indirect=["fs"])
def test_created(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
assert isinstance(created, datetime.datetime)
finally:
if not isinstance(fs, tuple(READ_ONLY_FILESYSTEMS)):
fs.rm(TEST_FILE)
@pytest.mark.parametrize("fs", ["local"], indirect=["fs"])
def test_modified(fs: AbstractFileSystem):
try:
fs.touch(TEST_FILE)
created = fs.created(path=TEST_FILE)
fs.touch(TEST_FILE)
modified = fs.modified(path=TEST_FILE)
assert isinstance(modified, datetime.datetime)
assert modified > created
finally:
fs.rm(TEST_FILE)
|
80e5af1599303cd012a348c7d5503bdfca433ce2 | tests/test_manager.py | tests/test_manager.py | def test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
rank=0,
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.rank == 0
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
rank=1,
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.rank == 1
assert authority2.cardinality == 2345
| def test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.cardinality == 2345
| Fix the one measly test | Fix the one measly test
| Python | mit | scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash | def test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
rank=0,
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.rank == 0
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
rank=1,
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.rank == 1
assert authority2.cardinality == 2345
Fix the one measly test | def test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.cardinality == 2345
| <commit_before>def test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
rank=0,
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.rank == 0
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
rank=1,
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.rank == 1
assert authority2.cardinality == 2345
<commit_msg>Fix the one measly test<commit_after> | def test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.cardinality == 2345
| def test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
rank=0,
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.rank == 0
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
rank=1,
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.rank == 1
assert authority2.cardinality == 2345
Fix the one measly testdef test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.cardinality == 2345
| <commit_before>def test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
rank=0,
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.rank == 0
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
rank=1,
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.rank == 1
assert authority2.cardinality == 2345
<commit_msg>Fix the one measly test<commit_after>def test_ensure_authority(manager_transaction):
authority1 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=1234
)
assert authority1.name == 'Test Authority'
assert authority1.cardinality == 1234
authority2 = manager_transaction.ensure_authority(
name='Test Authority',
cardinality=2345
)
assert authority1 is authority2
assert authority2.name == 'Test Authority'
assert authority2.cardinality == 2345
|
4a838a3e1df1f832a013b3e8a18e5474b06d0f9a | easy_bake.py | easy_bake.py | import RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
gpio.setup(40, gpio.OUT)
gpio.setup(38, gpio.OUT)
#true and 1 are the same
gpio.output(40, True)
gpio.output(38, 1)
while True:
gpio.output(40, True)
gpio.output(38, False)
time.sleep(4)
gpio.output(40, 0)
gpio.output(38, 1)
| import RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
output_pins = [40, 38]
gpio.setup(output_pins, gpio.OUT)
#true and 1 are the same
# gpio.output(40, True)
# gpio.output(38, 1)
while True:
gpio.output(output_pins, (True, False))
# gpio.output(40, True)
# gpio.output(38, False)
time.sleep(1)
# gpio.output(40, False)
# gpio.output(38, True)
gpio.output(output_pins, (False, True))
gpio.cleanup()
| Add in array or tuple of pins | Add in array or tuple of pins
| Python | mit | emgreen33/easy_bake,emgreen33/easy_bake | import RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
gpio.setup(40, gpio.OUT)
gpio.setup(38, gpio.OUT)
#true and 1 are the same
gpio.output(40, True)
gpio.output(38, 1)
while True:
gpio.output(40, True)
gpio.output(38, False)
time.sleep(4)
gpio.output(40, 0)
gpio.output(38, 1)
Add in array or tuple of pins | import RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
output_pins = [40, 38]
gpio.setup(output_pins, gpio.OUT)
#true and 1 are the same
# gpio.output(40, True)
# gpio.output(38, 1)
while True:
gpio.output(output_pins, (True, False))
# gpio.output(40, True)
# gpio.output(38, False)
time.sleep(1)
# gpio.output(40, False)
# gpio.output(38, True)
gpio.output(output_pins, (False, True))
gpio.cleanup()
| <commit_before>import RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
gpio.setup(40, gpio.OUT)
gpio.setup(38, gpio.OUT)
#true and 1 are the same
gpio.output(40, True)
gpio.output(38, 1)
while True:
gpio.output(40, True)
gpio.output(38, False)
time.sleep(4)
gpio.output(40, 0)
gpio.output(38, 1)
<commit_msg>Add in array or tuple of pins<commit_after> | import RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
output_pins = [40, 38]
gpio.setup(output_pins, gpio.OUT)
#true and 1 are the same
# gpio.output(40, True)
# gpio.output(38, 1)
while True:
gpio.output(output_pins, (True, False))
# gpio.output(40, True)
# gpio.output(38, False)
time.sleep(1)
# gpio.output(40, False)
# gpio.output(38, True)
gpio.output(output_pins, (False, True))
gpio.cleanup()
| import RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
gpio.setup(40, gpio.OUT)
gpio.setup(38, gpio.OUT)
#true and 1 are the same
gpio.output(40, True)
gpio.output(38, 1)
while True:
gpio.output(40, True)
gpio.output(38, False)
time.sleep(4)
gpio.output(40, 0)
gpio.output(38, 1)
Add in array or tuple of pinsimport RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
output_pins = [40, 38]
gpio.setup(output_pins, gpio.OUT)
#true and 1 are the same
# gpio.output(40, True)
# gpio.output(38, 1)
while True:
gpio.output(output_pins, (True, False))
# gpio.output(40, True)
# gpio.output(38, False)
time.sleep(1)
# gpio.output(40, False)
# gpio.output(38, True)
gpio.output(output_pins, (False, True))
gpio.cleanup()
| <commit_before>import RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
gpio.setup(40, gpio.OUT)
gpio.setup(38, gpio.OUT)
#true and 1 are the same
gpio.output(40, True)
gpio.output(38, 1)
while True:
gpio.output(40, True)
gpio.output(38, False)
time.sleep(4)
gpio.output(40, 0)
gpio.output(38, 1)
<commit_msg>Add in array or tuple of pins<commit_after>import RPi.GPIO as gpio
import time
#use board numbering on the pi
gpio.setmode(gpio.BOARD)
output_pins = [40, 38]
gpio.setup(output_pins, gpio.OUT)
#true and 1 are the same
# gpio.output(40, True)
# gpio.output(38, 1)
while True:
gpio.output(output_pins, (True, False))
# gpio.output(40, True)
# gpio.output(38, False)
time.sleep(1)
# gpio.output(40, False)
# gpio.output(38, True)
gpio.output(output_pins, (False, True))
gpio.cleanup()
|
f542b05f9a344c6a39b6ed3b163deddc3086be26 | pybinding/model.py | pybinding/model.py | import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self):
from .system import System as SystemEx
sys = super().system
sys.__class__ = SystemEx
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self):
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham
@property
def hamiltonian(self) -> _csrmatrix:
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham.matrix.to_scipy_csr()
@property
def solver(self):
from .solver.solver_ex import SolverEx
sol = super().solver
sol.__class__ = SolverEx
sol.system = self.system
return sol
| import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
from .system import System as _System
from .hamiltonian import Hamiltonian as _Hamiltonian
from .solver.solver_ex import SolverEx as _Solver
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self) -> _System:
sys = super().system
sys.__class__ = _System
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self) -> _Hamiltonian:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham
@property
def hamiltonian(self) -> _csrmatrix:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham.matrix.to_scipy_csr()
@property
def solver(self) -> _Solver:
sol = super().solver
sol.__class__ = _Solver
sol.system = self.system
return sol
| Annotate return types of Model properties | Annotate return types of Model properties
| Python | bsd-2-clause | MAndelkovic/pybinding,dean0x7d/pybinding,dean0x7d/pybinding,MAndelkovic/pybinding,MAndelkovic/pybinding,dean0x7d/pybinding | import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self):
from .system import System as SystemEx
sys = super().system
sys.__class__ = SystemEx
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self):
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham
@property
def hamiltonian(self) -> _csrmatrix:
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham.matrix.to_scipy_csr()
@property
def solver(self):
from .solver.solver_ex import SolverEx
sol = super().solver
sol.__class__ = SolverEx
sol.system = self.system
return sol
Annotate return types of Model properties | import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
from .system import System as _System
from .hamiltonian import Hamiltonian as _Hamiltonian
from .solver.solver_ex import SolverEx as _Solver
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self) -> _System:
sys = super().system
sys.__class__ = _System
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self) -> _Hamiltonian:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham
@property
def hamiltonian(self) -> _csrmatrix:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham.matrix.to_scipy_csr()
@property
def solver(self) -> _Solver:
sol = super().solver
sol.__class__ = _Solver
sol.system = self.system
return sol
| <commit_before>import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self):
from .system import System as SystemEx
sys = super().system
sys.__class__ = SystemEx
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self):
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham
@property
def hamiltonian(self) -> _csrmatrix:
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham.matrix.to_scipy_csr()
@property
def solver(self):
from .solver.solver_ex import SolverEx
sol = super().solver
sol.__class__ = SolverEx
sol.system = self.system
return sol
<commit_msg>Annotate return types of Model properties<commit_after> | import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
from .system import System as _System
from .hamiltonian import Hamiltonian as _Hamiltonian
from .solver.solver_ex import SolverEx as _Solver
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self) -> _System:
sys = super().system
sys.__class__ = _System
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self) -> _Hamiltonian:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham
@property
def hamiltonian(self) -> _csrmatrix:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham.matrix.to_scipy_csr()
@property
def solver(self) -> _Solver:
sol = super().solver
sol.__class__ = _Solver
sol.system = self.system
return sol
| import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self):
from .system import System as SystemEx
sys = super().system
sys.__class__ = SystemEx
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self):
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham
@property
def hamiltonian(self) -> _csrmatrix:
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham.matrix.to_scipy_csr()
@property
def solver(self):
from .solver.solver_ex import SolverEx
sol = super().solver
sol.__class__ = SolverEx
sol.system = self.system
return sol
Annotate return types of Model propertiesimport _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
from .system import System as _System
from .hamiltonian import Hamiltonian as _Hamiltonian
from .solver.solver_ex import SolverEx as _Solver
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self) -> _System:
sys = super().system
sys.__class__ = _System
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self) -> _Hamiltonian:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham
@property
def hamiltonian(self) -> _csrmatrix:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham.matrix.to_scipy_csr()
@property
def solver(self) -> _Solver:
sol = super().solver
sol.__class__ = _Solver
sol.system = self.system
return sol
| <commit_before>import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self):
from .system import System as SystemEx
sys = super().system
sys.__class__ = SystemEx
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self):
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham
@property
def hamiltonian(self) -> _csrmatrix:
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham.matrix.to_scipy_csr()
@property
def solver(self):
from .solver.solver_ex import SolverEx
sol = super().solver
sol.__class__ = SolverEx
sol.system = self.system
return sol
<commit_msg>Annotate return types of Model properties<commit_after>import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
from .system import System as _System
from .hamiltonian import Hamiltonian as _Hamiltonian
from .solver.solver_ex import SolverEx as _Solver
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self) -> _System:
sys = super().system
sys.__class__ = _System
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self) -> _Hamiltonian:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham
@property
def hamiltonian(self) -> _csrmatrix:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham.matrix.to_scipy_csr()
@property
def solver(self) -> _Solver:
sol = super().solver
sol.__class__ = _Solver
sol.system = self.system
return sol
|
259a4377b19f1140d46a5c8f7389121806fe7e01 | pombola/south_africa/urls.py | pombola/south_africa/urls.py | from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation'),
)
| from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
from pombola.core.urls import organisation_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
)
| Use a different method to override the url in SA | Use a different method to override the url in SA
This is not an ideal solution, but seems to do the job. The problem with
the way it was previously was that it the /organisation/all route way
getting skipped as the /organisation/:slug route was always matching.
| Python | agpl-3.0 | mysociety/pombola,ken-muturi/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,ken-muturi/pombola,patricmutwiri/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,hzj123/56th,mysociety/pombola,geoffkilpin/pombola,ken-muturi/pombola,geoffkilpin/pombola,geoffkilpin/pombola,ken-muturi/pombola,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,hzj123/56th,patricmutwiri/pombola,geoffkilpin/pombola,geoffkilpin/pombola,hzj123/56th,patricmutwiri/pombola,hzj123/56th,hzj123/56th | from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation'),
)
Use a different method to override the url in SA
This is not an ideal solution, but seems to do the job. The problem with
the way it was previously was that it the /organisation/all route way
getting skipped as the /organisation/:slug route was always matching. | from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
from pombola.core.urls import organisation_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
)
| <commit_before>from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation'),
)
<commit_msg>Use a different method to override the url in SA
This is not an ideal solution, but seems to do the job. The problem with
the way it was previously was that it the /organisation/all route way
getting skipped as the /organisation/:slug route was always matching.<commit_after> | from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
from pombola.core.urls import organisation_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
)
| from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation'),
)
Use a different method to override the url in SA
This is not an ideal solution, but seems to do the job. The problem with
the way it was previously was that it the /organisation/all route way
getting skipped as the /organisation/:slug route was always matching.from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
from pombola.core.urls import organisation_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
)
| <commit_before>from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation'),
)
<commit_msg>Use a different method to override the url in SA
This is not an ideal solution, but seems to do the job. The problem with
the way it was previously was that it the /organisation/all route way
getting skipped as the /organisation/:slug route was always matching.<commit_after>from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, SAOrganisationDetailView
from pombola.core.urls import organisation_patterns
# Override the organisation url so we can vary it depending on the organisation type.
for index, pattern in enumerate(organisation_patterns):
if pattern.name == 'organisation':
organisation_patterns[index] = url(r'^organisation/(?P<slug>[-\w]+)/$', SAOrganisationDetailView.as_view(), name='organisation')
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
)
|
0b1d2a43e4f9858bcb9d9bf9edf3dfae417f133d | satchless/util/__init__.py | satchless/util/__init__.py | from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
def handle_decimal(self, o):
if isinstance(o, Decimal):
return float(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
| from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
class UndercoverDecimal(float):
'''
A horrible hack that lets us encode Decimals as numbers.
Do not do this at home.
'''
def __init__(self, value):
self.value = value
def __repr__(self):
return str(self.value)
def handle_decimal(self, o):
if isinstance(o, Decimal):
return self.UndercoverDecimal(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
| Add a huge hack to treat Decimals like floats | Add a huge hack to treat Decimals like floats
This commit provided to you by highly trained professional stuntmen,
do not try to reproduce any of this at home!
| Python | bsd-3-clause | taedori81/satchless,fusionbox/satchless,fusionbox/satchless,fusionbox/satchless | from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
def handle_decimal(self, o):
if isinstance(o, Decimal):
return float(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
Add a huge hack to treat Decimals like floats
This commit provided to you by highly trained professional stuntmen,
do not try to reproduce any of this at home! | from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
class UndercoverDecimal(float):
'''
A horrible hack that lets us encode Decimals as numbers.
Do not do this at home.
'''
def __init__(self, value):
self.value = value
def __repr__(self):
return str(self.value)
def handle_decimal(self, o):
if isinstance(o, Decimal):
return self.UndercoverDecimal(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
| <commit_before>from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
def handle_decimal(self, o):
if isinstance(o, Decimal):
return float(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
<commit_msg>Add a huge hack to treat Decimals like floats
This commit provided to you by highly trained professional stuntmen,
do not try to reproduce any of this at home!<commit_after> | from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
class UndercoverDecimal(float):
'''
A horrible hack that lets us encode Decimals as numbers.
Do not do this at home.
'''
def __init__(self, value):
self.value = value
def __repr__(self):
return str(self.value)
def handle_decimal(self, o):
if isinstance(o, Decimal):
return self.UndercoverDecimal(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
| from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
def handle_decimal(self, o):
if isinstance(o, Decimal):
return float(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
Add a huge hack to treat Decimals like floats
This commit provided to you by highly trained professional stuntmen,
do not try to reproduce any of this at home!from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
class UndercoverDecimal(float):
'''
A horrible hack that lets us encode Decimals as numbers.
Do not do this at home.
'''
def __init__(self, value):
self.value = value
def __repr__(self):
return str(self.value)
def handle_decimal(self, o):
if isinstance(o, Decimal):
return self.UndercoverDecimal(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
| <commit_before>from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
def handle_decimal(self, o):
if isinstance(o, Decimal):
return float(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
<commit_msg>Add a huge hack to treat Decimals like floats
This commit provided to you by highly trained professional stuntmen,
do not try to reproduce any of this at home!<commit_after>from decimal import Decimal
from django.http import HttpResponse
from django.utils import simplejson
def decimal_format(value, min_decimal_places=0):
decimal_tuple = value.as_tuple()
have_decimal_places = -decimal_tuple.exponent
digits = list(decimal_tuple.digits)
while have_decimal_places < min_decimal_places:
digits.append(0)
have_decimal_places += 1
while have_decimal_places > min_decimal_places and not digits[-1]:
if len(digits) > 1:
digits = digits[:-1]
have_decimal_places -= 1
return Decimal((decimal_tuple.sign, digits, -have_decimal_places))
class JSONResponse(HttpResponse):
class UndercoverDecimal(float):
'''
A horrible hack that lets us encode Decimals as numbers.
Do not do this at home.
'''
def __init__(self, value):
self.value = value
def __repr__(self):
return str(self.value)
def handle_decimal(self, o):
if isinstance(o, Decimal):
return self.UndercoverDecimal(o)
raise TypeError()
def __init__(self, content='', mimetype=None, status=None,
content_type='application/json'):
content = simplejson.dumps(content, default=self.handle_decimal)
return super(JSONResponse, self).__init__(content=content,
mimetype=mimetype,
status=status,
content_type=content_type)
|
17080ab6511d045b0bc27b3c04102fbcefa5c330 | modules/icons.py | modules/icons.py | import sublime
from os import path
_plugin_name = "Git Conflict Resolver"
_icon_folder = path.join(_plugin_name, "gutter")
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = path.join("..", _icon_folder)
else:
base = path.join("Packages", _icon_folder)
extension = ".png"
return path.join(base, _icons[group] + extension)
| import sublime
_plugin_name = "Git Conflict Resolver"
_icon_folder = "/".join([_plugin_name, "gutter"])
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = "/".join(["..", _icon_folder])
else:
base = "/".join(["Packages", _icon_folder])
extension = ".png"
return "/".join([base, _icons[group] + extension])
| Fix sublime icon pathing by using "/" instead of os.path.join | Fix sublime icon pathing by using "/" instead of os.path.join
| Python | mit | Zeeker/sublime-GitConflictResolver,Zeeker/sublime-GitConflictResolver | import sublime
from os import path
_plugin_name = "Git Conflict Resolver"
_icon_folder = path.join(_plugin_name, "gutter")
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = path.join("..", _icon_folder)
else:
base = path.join("Packages", _icon_folder)
extension = ".png"
return path.join(base, _icons[group] + extension)
Fix sublime icon pathing by using "/" instead of os.path.join | import sublime
_plugin_name = "Git Conflict Resolver"
_icon_folder = "/".join([_plugin_name, "gutter"])
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = "/".join(["..", _icon_folder])
else:
base = "/".join(["Packages", _icon_folder])
extension = ".png"
return "/".join([base, _icons[group] + extension])
| <commit_before>import sublime
from os import path
_plugin_name = "Git Conflict Resolver"
_icon_folder = path.join(_plugin_name, "gutter")
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = path.join("..", _icon_folder)
else:
base = path.join("Packages", _icon_folder)
extension = ".png"
return path.join(base, _icons[group] + extension)
<commit_msg>Fix sublime icon pathing by using "/" instead of os.path.join<commit_after> | import sublime
_plugin_name = "Git Conflict Resolver"
_icon_folder = "/".join([_plugin_name, "gutter"])
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = "/".join(["..", _icon_folder])
else:
base = "/".join(["Packages", _icon_folder])
extension = ".png"
return "/".join([base, _icons[group] + extension])
| import sublime
from os import path
_plugin_name = "Git Conflict Resolver"
_icon_folder = path.join(_plugin_name, "gutter")
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = path.join("..", _icon_folder)
else:
base = path.join("Packages", _icon_folder)
extension = ".png"
return path.join(base, _icons[group] + extension)
Fix sublime icon pathing by using "/" instead of os.path.joinimport sublime
_plugin_name = "Git Conflict Resolver"
_icon_folder = "/".join([_plugin_name, "gutter"])
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = "/".join(["..", _icon_folder])
else:
base = "/".join(["Packages", _icon_folder])
extension = ".png"
return "/".join([base, _icons[group] + extension])
| <commit_before>import sublime
from os import path
_plugin_name = "Git Conflict Resolver"
_icon_folder = path.join(_plugin_name, "gutter")
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = path.join("..", _icon_folder)
else:
base = path.join("Packages", _icon_folder)
extension = ".png"
return path.join(base, _icons[group] + extension)
<commit_msg>Fix sublime icon pathing by using "/" instead of os.path.join<commit_after>import sublime
_plugin_name = "Git Conflict Resolver"
_icon_folder = "/".join([_plugin_name, "gutter"])
_icons = {
"ours": "ours",
"ancestor": "ancestor",
"theirs": "theirs"
}
def get(group):
base = ""
extension = ""
if int(sublime.version()) < 3000:
base = "/".join(["..", _icon_folder])
else:
base = "/".join(["Packages", _icon_folder])
extension = ".png"
return "/".join([base, _icons[group] + extension])
|
874816497e7a9bd0e091a62a9e9b33ae832eb130 | pyjsonts/time_series_json.py | pyjsonts/time_series_json.py | import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj, \
sort_keys=True, \
indent=4, \
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
| import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj,
sort_keys=True,
indent=4,
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
| Remove unnecessary backslashes in parse_json_items | Remove unnecessary backslashes in parse_json_items
| Python | apache-2.0 | jeongmincha/pyjsonts | import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj, \
sort_keys=True, \
indent=4, \
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
Remove unnecessary backslashes in parse_json_items | import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj,
sort_keys=True,
indent=4,
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
| <commit_before>import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj, \
sort_keys=True, \
indent=4, \
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
<commit_msg>Remove unnecessary backslashes in parse_json_items<commit_after> | import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj,
sort_keys=True,
indent=4,
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
| import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj, \
sort_keys=True, \
indent=4, \
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
Remove unnecessary backslashes in parse_json_itemsimport json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj,
sort_keys=True,
indent=4,
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
| <commit_before>import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj, \
sort_keys=True, \
indent=4, \
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
<commit_msg>Remove unnecessary backslashes in parse_json_items<commit_after>import json
import ijson
class TimeSeriesJSON:
def __init__(self, f=None, fn=None, tag='item'):
"""
:param f: file object (_io.TextIOWrapper)
:param fn: file name as a string
:param tag: tag for dividing json items
default value is 'item' because this value is default in ijson
"""
if f is not None:
self.__type = 'file'
self.__file = f
elif fn is not None:
self.__type = 'file_name'
self.__file_name = fn
self.__file = open(fn)
self.__items = self.parse_json_items(tag)
def parse_json_items(self, tag, limit=0):
self.__items = []
self.__file.seek(0)
cnt = 0
objs = ijson.items(self.__file, tag)
for obj in objs:
item = json.dumps(obj,
sort_keys=True,
indent=4,
ensure_ascii=True)
self.__items.append(item)
cnt += 1
if limit != 0 and cnt >= limit:
break
return self.__items
|
5cf8f3326b6995a871df7f2b61b25ff529216103 | recordpeeker/command_line.py | recordpeeker/command_line.py | import argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
arglist = " ".join(sys.argv[1:])
sys.argv = [sys.argv[0], '-s "{0}" "{1}"'.format(script, arglist), '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
| import argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
if sys.argv[1:]:
arglist = " ".join(sys.argv[1:])
scriptargs = '-s "{0}" "{1}"'.format(script, arglist)
else:
scriptargs = '-s "{0}"'.format(script)
sys.argv = [sys.argv[0], scriptargs, '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
| Fix bustage for script calls | Fix bustage for script calls
| Python | mit | jonchang/recordpeeker | import argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
arglist = " ".join(sys.argv[1:])
sys.argv = [sys.argv[0], '-s "{0}" "{1}"'.format(script, arglist), '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
Fix bustage for script calls | import argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
if sys.argv[1:]:
arglist = " ".join(sys.argv[1:])
scriptargs = '-s "{0}" "{1}"'.format(script, arglist)
else:
scriptargs = '-s "{0}"'.format(script)
sys.argv = [sys.argv[0], scriptargs, '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
| <commit_before>import argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
arglist = " ".join(sys.argv[1:])
sys.argv = [sys.argv[0], '-s "{0}" "{1}"'.format(script, arglist), '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
<commit_msg>Fix bustage for script calls<commit_after> | import argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
if sys.argv[1:]:
arglist = " ".join(sys.argv[1:])
scriptargs = '-s "{0}" "{1}"'.format(script, arglist)
else:
scriptargs = '-s "{0}"'.format(script)
sys.argv = [sys.argv[0], scriptargs, '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
| import argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
arglist = " ".join(sys.argv[1:])
sys.argv = [sys.argv[0], '-s "{0}" "{1}"'.format(script, arglist), '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
Fix bustage for script callsimport argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
if sys.argv[1:]:
arglist = " ".join(sys.argv[1:])
scriptargs = '-s "{0}" "{1}"'.format(script, arglist)
else:
scriptargs = '-s "{0}"'.format(script)
sys.argv = [sys.argv[0], scriptargs, '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
| <commit_before>import argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
arglist = " ".join(sys.argv[1:])
sys.argv = [sys.argv[0], '-s "{0}" "{1}"'.format(script, arglist), '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
<commit_msg>Fix bustage for script calls<commit_after>import argparse
import os
import json
import sys
def parse_args(argv):
parser = argparse.ArgumentParser("Test")
parser.add_argument("--port", "-p", type=int, default=8080, help="Specify the port recordpeeker runs on")
parser.add_argument("--verbosity", "-v", default=0, type=int, choices=[0,1,2,3], help="Spews more info. 1: prints the path of each request. 2: prints the content of unknown requests. 3: Also print the content of known requests.")
return parser.parse_args(argv[1:])
def launch():
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mitmdump_input.py')
# This is just here so that --help returns the arguments
args = parse_args(sys.argv)
if sys.argv[1:]:
arglist = " ".join(sys.argv[1:])
scriptargs = '-s "{0}" "{1}"'.format(script, arglist)
else:
scriptargs = '-s "{0}"'.format(script)
sys.argv = [sys.argv[0], scriptargs, '-q']
from libmproxy.main import mitmdump
mitmdump()
if __name__ == '__main__':
launch()
|
f3875b1d9aed5f847b11846a27f7652e4c548b6c | modules/karma.py | modules/karma.py | import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
print("karma_action triggered")
msg = "I saw that!" + reaction.message.author.name + reaction.emoji
await client.send_message(reaction.message.channel, msg)
| import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
module_db = 'karma.json'
module_version = '0.1.0'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
target_user = self.module_db.Query()
if self.module_db.get(target_user.userid == reaction.message.author.id) == None:
self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1})
msg = 'New entry for ' + reaction.message.author.id + ' added.'
await client.send_message(reaction.message.channel, msg)
else:
new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1
self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id)
msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma
await client.send_message(reaction.message.channel, msg)
#msg = "I saw that!" + reaction.message.author.name + reaction.emoji
#await client.send_message(reaction.message.channel, msg)
| Add logic and code for database operations (untested) | Add logic and code for database operations (untested)
| Python | mit | suclearnub/scubot | import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
print("karma_action triggered")
msg = "I saw that!" + reaction.message.author.name + reaction.emoji
await client.send_message(reaction.message.channel, msg)
Add logic and code for database operations (untested) | import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
module_db = 'karma.json'
module_version = '0.1.0'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
target_user = self.module_db.Query()
if self.module_db.get(target_user.userid == reaction.message.author.id) == None:
self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1})
msg = 'New entry for ' + reaction.message.author.id + ' added.'
await client.send_message(reaction.message.channel, msg)
else:
new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1
self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id)
msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma
await client.send_message(reaction.message.channel, msg)
#msg = "I saw that!" + reaction.message.author.name + reaction.emoji
#await client.send_message(reaction.message.channel, msg)
| <commit_before>import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
print("karma_action triggered")
msg = "I saw that!" + reaction.message.author.name + reaction.emoji
await client.send_message(reaction.message.channel, msg)
<commit_msg>Add logic and code for database operations (untested)<commit_after> | import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
module_db = 'karma.json'
module_version = '0.1.0'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
target_user = self.module_db.Query()
if self.module_db.get(target_user.userid == reaction.message.author.id) == None:
self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1})
msg = 'New entry for ' + reaction.message.author.id + ' added.'
await client.send_message(reaction.message.channel, msg)
else:
new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1
self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id)
msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma
await client.send_message(reaction.message.channel, msg)
#msg = "I saw that!" + reaction.message.author.name + reaction.emoji
#await client.send_message(reaction.message.channel, msg)
| import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
print("karma_action triggered")
msg = "I saw that!" + reaction.message.author.name + reaction.emoji
await client.send_message(reaction.message.channel, msg)
Add logic and code for database operations (untested)import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
module_db = 'karma.json'
module_version = '0.1.0'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
target_user = self.module_db.Query()
if self.module_db.get(target_user.userid == reaction.message.author.id) == None:
self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1})
msg = 'New entry for ' + reaction.message.author.id + ' added.'
await client.send_message(reaction.message.channel, msg)
else:
new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1
self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id)
msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma
await client.send_message(reaction.message.channel, msg)
#msg = "I saw that!" + reaction.message.author.name + reaction.emoji
#await client.send_message(reaction.message.channel, msg)
| <commit_before>import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
print("karma_action triggered")
msg = "I saw that!" + reaction.message.author.name + reaction.emoji
await client.send_message(reaction.message.channel, msg)
<commit_msg>Add logic and code for database operations (untested)<commit_after>import discord
from modules.botModule import BotModule
class Karma(BotModule):
name = 'karma'
description = 'Monitors messages for reactions and adds karma accordingly.'
help_text = 'This module has no callable functions'
trigger_string = '!reddit'
module_db = 'karma.json'
module_version = '0.1.0'
listen_for_reaction = True
async def parse_command(self, message, client):
pass
async def on_reaction(self, reaction, client):
target_user = self.module_db.Query()
if self.module_db.get(target_user.userid == reaction.message.author.id) == None:
self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1})
msg = 'New entry for ' + reaction.message.author.id + ' added.'
await client.send_message(reaction.message.channel, msg)
else:
new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1
self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id)
msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma
await client.send_message(reaction.message.channel, msg)
#msg = "I saw that!" + reaction.message.author.name + reaction.emoji
#await client.send_message(reaction.message.channel, msg)
|
cd8fe432077bdd65122189dd9191d7a5b8788e48 | reinforcement-learning/play.py | reinforcement-learning/play.py | """This is the agent which currently takes the action with highest immediate reward."""
import env
import time
env.make("pygame")
for episode in range(10):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
max_action = -1
index = -1
for item in env.actions:
print(item)
print(env.reward(item))
if env.reward(item) > max_action:
print("greater")
max_action = env.reward(item)
action = [item, index]
else:
index += 1
print(action[0])
episode_reward += env.reward(action[0])
env.action(action[0])
env.render()
| """This is the agent which currently takes the action with highest immediate reward."""
import time
start = time.time()
import env
import rl
env.make("text")
for episode in range(1000):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
action = rl.choose_action(rl.table[env.object[0]])
rl.q(env.player, action)
print(action)
episode_reward += env.reward(action)
env.action(action)
env.update()
print(rl.table[env.object[0]])
print("Finished after", str(time.time() - start), "seconds")
| Use proper q learning for agent. | Use proper q learning for agent.
| Python | mit | danieloconell/Louis | """This is the agent which currently takes the action with highest immediate reward."""
import env
import time
env.make("pygame")
for episode in range(10):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
max_action = -1
index = -1
for item in env.actions:
print(item)
print(env.reward(item))
if env.reward(item) > max_action:
print("greater")
max_action = env.reward(item)
action = [item, index]
else:
index += 1
print(action[0])
episode_reward += env.reward(action[0])
env.action(action[0])
env.render()
Use proper q learning for agent. | """This is the agent which currently takes the action with highest immediate reward."""
import time
start = time.time()
import env
import rl
env.make("text")
for episode in range(1000):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
action = rl.choose_action(rl.table[env.object[0]])
rl.q(env.player, action)
print(action)
episode_reward += env.reward(action)
env.action(action)
env.update()
print(rl.table[env.object[0]])
print("Finished after", str(time.time() - start), "seconds")
| <commit_before>"""This is the agent which currently takes the action with highest immediate reward."""
import env
import time
env.make("pygame")
for episode in range(10):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
max_action = -1
index = -1
for item in env.actions:
print(item)
print(env.reward(item))
if env.reward(item) > max_action:
print("greater")
max_action = env.reward(item)
action = [item, index]
else:
index += 1
print(action[0])
episode_reward += env.reward(action[0])
env.action(action[0])
env.render()
<commit_msg>Use proper q learning for agent.<commit_after> | """This is the agent which currently takes the action with highest immediate reward."""
import time
start = time.time()
import env
import rl
env.make("text")
for episode in range(1000):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
action = rl.choose_action(rl.table[env.object[0]])
rl.q(env.player, action)
print(action)
episode_reward += env.reward(action)
env.action(action)
env.update()
print(rl.table[env.object[0]])
print("Finished after", str(time.time() - start), "seconds")
| """This is the agent which currently takes the action with highest immediate reward."""
import env
import time
env.make("pygame")
for episode in range(10):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
max_action = -1
index = -1
for item in env.actions:
print(item)
print(env.reward(item))
if env.reward(item) > max_action:
print("greater")
max_action = env.reward(item)
action = [item, index]
else:
index += 1
print(action[0])
episode_reward += env.reward(action[0])
env.action(action[0])
env.render()
Use proper q learning for agent."""This is the agent which currently takes the action with highest immediate reward."""
import time
start = time.time()
import env
import rl
env.make("text")
for episode in range(1000):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
action = rl.choose_action(rl.table[env.object[0]])
rl.q(env.player, action)
print(action)
episode_reward += env.reward(action)
env.action(action)
env.update()
print(rl.table[env.object[0]])
print("Finished after", str(time.time() - start), "seconds")
| <commit_before>"""This is the agent which currently takes the action with highest immediate reward."""
import env
import time
env.make("pygame")
for episode in range(10):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
max_action = -1
index = -1
for item in env.actions:
print(item)
print(env.reward(item))
if env.reward(item) > max_action:
print("greater")
max_action = env.reward(item)
action = [item, index]
else:
index += 1
print(action[0])
episode_reward += env.reward(action[0])
env.action(action[0])
env.render()
<commit_msg>Use proper q learning for agent.<commit_after>"""This is the agent which currently takes the action with highest immediate reward."""
import time
start = time.time()
import env
import rl
env.make("text")
for episode in range(1000):
env.reset()
episode_reward = 0
for t in range(100):
episode_reward += env.actual_reward
if env.done:
print(
"Episode %d finished after %d timesteps, with reward %d"
% ((episode + 1), (t + 1), episode_reward))
break
action = rl.choose_action(rl.table[env.object[0]])
rl.q(env.player, action)
print(action)
episode_reward += env.reward(action)
env.action(action)
env.update()
print(rl.table[env.object[0]])
print("Finished after", str(time.time() - start), "seconds")
|
fd6cc34c682c773273bcdd9d09d2f7f2e4d91700 | ocr/tfhelpers.py | ocr/tfhelpers.py | # -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc):
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.activation = tf.get_collection('activation')[0]
# To launch the graph
def run(self, data):
return self.sess.run(self.activation, feed_dict={"x:0": data}) | # -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc, operation='activation', input_name='x'):
"""
loc: location of file containing saved model
operation: name of operation for running the model
input_name: name of input placeholder
"""
self.input = input_name + ":0"
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.op = self.graph.get_operation_by_name(operation).outputs[0]
def run(self, data):
""" Run the specified operation on given data """
return self.sess.run(self.op, feed_dict={self.input: data}) | Update Graph class for loading saved models Requires renaming operations in models -> re-train them | Update Graph class for loading saved models
Requires renaming operations in models -> re-train them
| Python | mit | Breta01/handwriting-ocr | # -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc):
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.activation = tf.get_collection('activation')[0]
# To launch the graph
def run(self, data):
return self.sess.run(self.activation, feed_dict={"x:0": data})Update Graph class for loading saved models
Requires renaming operations in models -> re-train them | # -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc, operation='activation', input_name='x'):
"""
loc: location of file containing saved model
operation: name of operation for running the model
input_name: name of input placeholder
"""
self.input = input_name + ":0"
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.op = self.graph.get_operation_by_name(operation).outputs[0]
def run(self, data):
""" Run the specified operation on given data """
return self.sess.run(self.op, feed_dict={self.input: data}) | <commit_before># -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc):
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.activation = tf.get_collection('activation')[0]
# To launch the graph
def run(self, data):
return self.sess.run(self.activation, feed_dict={"x:0": data})<commit_msg>Update Graph class for loading saved models
Requires renaming operations in models -> re-train them<commit_after> | # -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc, operation='activation', input_name='x'):
"""
loc: location of file containing saved model
operation: name of operation for running the model
input_name: name of input placeholder
"""
self.input = input_name + ":0"
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.op = self.graph.get_operation_by_name(operation).outputs[0]
def run(self, data):
""" Run the specified operation on given data """
return self.sess.run(self.op, feed_dict={self.input: data}) | # -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc):
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.activation = tf.get_collection('activation')[0]
# To launch the graph
def run(self, data):
return self.sess.run(self.activation, feed_dict={"x:0": data})Update Graph class for loading saved models
Requires renaming operations in models -> re-train them# -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc, operation='activation', input_name='x'):
"""
loc: location of file containing saved model
operation: name of operation for running the model
input_name: name of input placeholder
"""
self.input = input_name + ":0"
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.op = self.graph.get_operation_by_name(operation).outputs[0]
def run(self, data):
""" Run the specified operation on given data """
return self.sess.run(self.op, feed_dict={self.input: data}) | <commit_before># -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc):
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.activation = tf.get_collection('activation')[0]
# To launch the graph
def run(self, data):
return self.sess.run(self.activation, feed_dict={"x:0": data})<commit_msg>Update Graph class for loading saved models
Requires renaming operations in models -> re-train them<commit_after># -*- coding: utf-8 -*-
"""
Loading and using trained models from tensorflow
"""
import tensorflow as tf
class Graph():
""" Loading and running isolated tf graph """
def __init__(self, loc, operation='activation', input_name='x'):
"""
loc: location of file containing saved model
operation: name of operation for running the model
input_name: name of input placeholder
"""
self.input = input_name + ":0"
self.graph = tf.Graph()
self.sess = tf.Session(graph=self.graph)
with self.graph.as_default():
saver = tf.train.import_meta_graph(loc + '.meta', clear_devices=True)
saver.restore(self.sess, loc)
self.op = self.graph.get_operation_by_name(operation).outputs[0]
def run(self, data):
""" Run the specified operation on given data """
return self.sess.run(self.op, feed_dict={self.input: data}) |
bb4c1375082d68a78e194d3d1d3399eadc0d1b12 | dlstats/errors.py | dlstats/errors.py |
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
|
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
self.comments = kwargs.pop("comments", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class InterruptProcessSeriesData(DlstatsException):
pass
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
| Add exception for interrupt data process | Add exception for interrupt data process
| Python | agpl-3.0 | Widukind/dlstats,Widukind/dlstats |
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
Add exception for interrupt data process |
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
self.comments = kwargs.pop("comments", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class InterruptProcessSeriesData(DlstatsException):
pass
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
| <commit_before>
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
<commit_msg>Add exception for interrupt data process<commit_after> |
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
self.comments = kwargs.pop("comments", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class InterruptProcessSeriesData(DlstatsException):
pass
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
|
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
Add exception for interrupt data process
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
self.comments = kwargs.pop("comments", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class InterruptProcessSeriesData(DlstatsException):
pass
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
| <commit_before>
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
<commit_msg>Add exception for interrupt data process<commit_after>
class DlstatsException(Exception):
def __init__(self, *args, **kwargs):
self.provider_name = kwargs.pop("provider_name", None)
self.dataset_code = kwargs.pop("dataset_code", None)
self.comments = kwargs.pop("comments", None)
super().__init__(*args, **kwargs)
class RejectFrequency(DlstatsException):
def __init__(self, *args, **kwargs):
self.frequency = kwargs.pop("frequency", None)
super().__init__(*args, **kwargs)
class InterruptProcessSeriesData(DlstatsException):
pass
class RejectEmptySeries(DlstatsException):
pass
class RejectUpdatedDataset(DlstatsException):
"""Reject if dataset is updated
"""
class RejectUpdatedSeries(DlstatsException):
"""Reject if series is updated
"""
def __init__(self, *args, **kwargs):
self.key = kwargs.pop("key", None)
super().__init__(*args, **kwargs)
class MaxErrors(DlstatsException):
pass
|
aa8117c288fc45743554450448178c47246b088f | devicehive/transport.py | devicehive/transport.py | def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
self.id = response.pop('requestId')
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
| def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
| Remove Request and Response classes | Remove Request and Response classes
| Python | apache-2.0 | devicehive/devicehive-python | def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
self.id = response.pop('requestId')
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
Remove Request and Response classes | def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
| <commit_before>def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
self.id = response.pop('requestId')
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
<commit_msg>Remove Request and Response classes<commit_after> | def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
| def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
self.id = response.pop('requestId')
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
Remove Request and Response classesdef init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
| <commit_before>def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
self.id = response.pop('requestId')
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
<commit_msg>Remove Request and Response classes<commit_after>def init(name, data_format_class, data_format_options, handler_class,
handler_options):
transport_class_name = '%sTransport' % name.title()
transport_module = __import__('devicehive.transports.%s_transport' % name,
fromlist=[transport_class_name])
return getattr(transport_module, transport_class_name)(data_format_class,
data_format_options,
handler_class,
handler_options)
|
145b40c1b855b9f40eddf4682f4361112e459323 | lcddaemon.py | lcddaemon.py | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from server.server import run
from modules.printer.printer import Printer # To remove, has to be done dynamically
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
message_manager = QueueManager(message_queue, Printer, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
| #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
module_class = load_module_from_conf(config)
message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
| Update to load dynamically the module selected by user. | Update to load dynamically the module selected by user.
| Python | mit | juliendelplanque/lcddaemon | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from server.server import run
from modules.printer.printer import Printer # To remove, has to be done dynamically
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
message_manager = QueueManager(message_queue, Printer, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
Update to load dynamically the module selected by user. | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
module_class = load_module_from_conf(config)
message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
| <commit_before>#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from server.server import run
from modules.printer.printer import Printer # To remove, has to be done dynamically
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
message_manager = QueueManager(message_queue, Printer, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
<commit_msg>Update to load dynamically the module selected by user.<commit_after> | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
module_class = load_module_from_conf(config)
message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
| #!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from server.server import run
from modules.printer.printer import Printer # To remove, has to be done dynamically
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
message_manager = QueueManager(message_queue, Printer, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
Update to load dynamically the module selected by user.#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
module_class = load_module_from_conf(config)
message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
| <commit_before>#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from server.server import run
from modules.printer.printer import Printer # To remove, has to be done dynamically
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
message_manager = QueueManager(message_queue, Printer, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
<commit_msg>Update to load dynamically the module selected by user.<commit_after>#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" This script is the launcher of the daemon.
"""
import sys
import threading
from core.daemonargs import parse_arguments
from core.message import set_default_repeat
from core.message import set_default_ttl
from core.message import set_default_duration
from core.queue import MessageQueue
from core.queuemanager import QueueManager
from core.moduleloader import load_module_from_conf
from server.server import run
def main():
config = parse_arguments()
set_default_repeat(config["ttr"])
set_default_ttl(config["ttl"])
set_default_duration(config["ttd"])
message_queue = MessageQueue(config["limit"])
module_class = load_module_from_conf(config)
message_manager = QueueManager(message_queue, module_class, None) # TODO (None)
message_manager_thread = threading.Thread(target=message_manager.manage)
message_manager_thread.daemon = True
message_manager_thread.start()
run(message_queue, config["ptl"])
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("You killed me.")
sys.exit(0)
|
51372716e1fdf6f7ea516b76e37a7600598362db | connector_base_product/__openerp__.py | connector_base_product/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://openerp-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://odoo-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
| Use the new links for websites (with odoo) and for the prestashop connector | Use the new links for websites (with odoo) and for the prestashop
connector
| Python | agpl-3.0 | OCA/connector,OCA/connector | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://openerp-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
Use the new links for websites (with odoo) and for the prestashop
connector | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://odoo-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
| <commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://openerp-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
<commit_msg>Use the new links for websites (with odoo) and for the prestashop
connector<commit_after> | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://odoo-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://openerp-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
Use the new links for websites (with odoo) and for the prestashop
connector# -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://odoo-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
| <commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://openerp-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
<commit_msg>Use the new links for websites (with odoo) and for the prestashop
connector<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
# Author: David BEAL, Copyright Akretion, 2014
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{'name': 'Connector Base Product',
'version': '1.0',
'author': 'Openerp Connector Core Editors',
'website': 'http://odoo-connector.com',
'license': 'AGPL-3',
'category': 'Connector',
'description': """
Connector Base Product
======================
Add 'Connector' tab to product view
""",
'depends': [
'connector',
'product',
],
'data': [
'product_view.xml'
],
'installable': True,
}
|
a626e97bdb8816ed46760c55ad402b64e391538a | revenue/admin.py | revenue/admin.py | from django.contrib import admin
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet, ModelForm
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
return # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
print(self.instance)
class FeeLineForm(ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
| from django.contrib import admin
from django.core.exceptions import ValidationError
from django import forms
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(forms.BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
continue # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
class FeeLineForm(forms.ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
| Fix how we calculate total to really account for deleted objects | Fix how we calculate total to really account for deleted objects
| Python | mpl-2.0 | jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django | from django.contrib import admin
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet, ModelForm
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
return # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
print(self.instance)
class FeeLineForm(ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
Fix how we calculate total to really account for deleted objects | from django.contrib import admin
from django.core.exceptions import ValidationError
from django import forms
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(forms.BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
continue # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
class FeeLineForm(forms.ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
| <commit_before>from django.contrib import admin
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet, ModelForm
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
return # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
print(self.instance)
class FeeLineForm(ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
<commit_msg>Fix how we calculate total to really account for deleted objects<commit_after> | from django.contrib import admin
from django.core.exceptions import ValidationError
from django import forms
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(forms.BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
continue # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
class FeeLineForm(forms.ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
| from django.contrib import admin
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet, ModelForm
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
return # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
print(self.instance)
class FeeLineForm(ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
Fix how we calculate total to really account for deleted objectsfrom django.contrib import admin
from django.core.exceptions import ValidationError
from django import forms
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(forms.BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
continue # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
class FeeLineForm(forms.ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
| <commit_before>from django.contrib import admin
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet, ModelForm
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
return # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
print(self.instance)
class FeeLineForm(ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
<commit_msg>Fix how we calculate total to really account for deleted objects<commit_after>from django.contrib import admin
from django.core.exceptions import ValidationError
from django import forms
from django.utils.translation import ugettext_lazy as _
from revenue.models import Receipt, FeeLine
class FeeLinesInlineFormSet(forms.BaseInlineFormSet):
def clean(self):
super(FeeLinesInlineFormSet, self).clean()
total = 0
for form in self.forms:
if not form.is_valid() or form.cleaned_data.get('DELETE'):
continue # there are other errors in the form or the item was deleted
total += form.cleaned_data.get('amount', 0)
self.instance.total_amount = total
class FeeLineForm(forms.ModelForm):
def clean(self):
if self.cleaned_data['date_start'] > self.cleaned_data['date_end']:
raise ValidationError(_("Date start must be before date end"))
class FeeLinesInline(admin.TabularInline):
form = FeeLineForm
model = FeeLine
formset = FeeLinesInlineFormSet
extra = 1
def get_extra (self, request, obj=None, **kwargs):
# Don't add any extra forms if the related object already exists.
if obj:
return 0
return self.extra
class ReceiptAdmin(admin.ModelAdmin):
readonly_fields = ['total_amount']
inlines = [FeeLinesInline]
admin.site.register(Receipt, ReceiptAdmin)
|
c2a3d8621e01d453da0043f5fe9afeba0a064224 | presets/icons.py | presets/icons.py | import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def load_previews(lib, start=0):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
for i,asset in enumerate(lib.presets):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, start + i))
start += len(enum_items)
for sub_group in lib.sub_groups:
enum_items.extend(load_previews(sub_group, start))
return enum_items if enum_items else [('', '', '')] | import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def get_presets_for_lib(lib):
items = list(lib.presets)
for sub_group in lib.sub_groups:
items.extend(get_presets_for_lib(sub_group))
return items
def load_previews(lib):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
items = get_presets_for_lib(lib)
items = sorted(items, key=lambda item: item.label)
for i, asset in enumerate(items):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, i))
return enum_items if enum_items else [('', '', '')] | Fix order in icon preview. | Fix order in icon preview.
| Python | mit | prman-pixar/RenderManForBlender,adminradio/RenderManForBlender,prman-pixar/RenderManForBlender | import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def load_previews(lib, start=0):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
for i,asset in enumerate(lib.presets):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, start + i))
start += len(enum_items)
for sub_group in lib.sub_groups:
enum_items.extend(load_previews(sub_group, start))
return enum_items if enum_items else [('', '', '')]Fix order in icon preview. | import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def get_presets_for_lib(lib):
items = list(lib.presets)
for sub_group in lib.sub_groups:
items.extend(get_presets_for_lib(sub_group))
return items
def load_previews(lib):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
items = get_presets_for_lib(lib)
items = sorted(items, key=lambda item: item.label)
for i, asset in enumerate(items):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, i))
return enum_items if enum_items else [('', '', '')] | <commit_before>import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def load_previews(lib, start=0):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
for i,asset in enumerate(lib.presets):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, start + i))
start += len(enum_items)
for sub_group in lib.sub_groups:
enum_items.extend(load_previews(sub_group, start))
return enum_items if enum_items else [('', '', '')]<commit_msg>Fix order in icon preview.<commit_after> | import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def get_presets_for_lib(lib):
items = list(lib.presets)
for sub_group in lib.sub_groups:
items.extend(get_presets_for_lib(sub_group))
return items
def load_previews(lib):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
items = get_presets_for_lib(lib)
items = sorted(items, key=lambda item: item.label)
for i, asset in enumerate(items):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, i))
return enum_items if enum_items else [('', '', '')] | import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def load_previews(lib, start=0):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
for i,asset in enumerate(lib.presets):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, start + i))
start += len(enum_items)
for sub_group in lib.sub_groups:
enum_items.extend(load_previews(sub_group, start))
return enum_items if enum_items else [('', '', '')]Fix order in icon preview.import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def get_presets_for_lib(lib):
items = list(lib.presets)
for sub_group in lib.sub_groups:
items.extend(get_presets_for_lib(sub_group))
return items
def load_previews(lib):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
items = get_presets_for_lib(lib)
items = sorted(items, key=lambda item: item.label)
for i, asset in enumerate(items):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, i))
return enum_items if enum_items else [('', '', '')] | <commit_before>import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def load_previews(lib, start=0):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
for i,asset in enumerate(lib.presets):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, start + i))
start += len(enum_items)
for sub_group in lib.sub_groups:
enum_items.extend(load_previews(sub_group, start))
return enum_items if enum_items else [('', '', '')]<commit_msg>Fix order in icon preview.<commit_after>import os
import bpy
import bpy.utils.previews
from .. import util
asset_previews = bpy.utils.previews.new()
def get_presets_for_lib(lib):
items = list(lib.presets)
for sub_group in lib.sub_groups:
items.extend(get_presets_for_lib(sub_group))
return items
def load_previews(lib):
global asset_previews
enum_items = []
lib_dir = presets_library = util.get_addon_prefs().presets_library.path
items = get_presets_for_lib(lib)
items = sorted(items, key=lambda item: item.label)
for i, asset in enumerate(items):
path = asset.path
if path not in asset_previews:
thumb_path = os.path.join(asset.path, 'asset_100.png')
thumb = asset_previews.load(path, thumb_path, 'IMAGE', force_reload=True)
else:
thumb = asset_previews[path]
enum_items.append((asset.path, asset.label, '', thumb.icon_id, i))
return enum_items if enum_items else [('', '', '')] |
c66427aae7e251450ccb241ebbd0663127e1f6c1 | tests/test_application.py | tests/test_application.py | from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 301 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
| from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 308 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
| Update redirect test to status 308 | Update redirect test to status 308
| Python | mit | alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend | from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 301 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
Update redirect test to status 308 | from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 308 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
| <commit_before>from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 301 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
<commit_msg>Update redirect test to status 308<commit_after> | from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 308 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
| from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 301 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
Update redirect test to status 308from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 308 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
| <commit_before>from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 301 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
<commit_msg>Update redirect test to status 308<commit_after>from .helpers import BaseApplicationTest, BaseAPIClientMixin
class DataAPIClientMixin(BaseAPIClientMixin):
data_api_client_patch_path = 'app.main.views.marketplace.data_api_client'
class TestApplication(DataAPIClientMixin, BaseApplicationTest):
def test_index(self):
response = self.client.get('/')
assert 200 == response.status_code
assert len(self.data_api_client.find_frameworks.call_args_list) == 2
def test_404(self):
response = self.client.get('/not-found')
assert 404 == response.status_code
def test_trailing_slashes(self):
response = self.client.get('')
assert 308 == response.status_code
assert "http://localhost/" == response.location
response = self.client.get('/trailing/')
assert 301 == response.status_code
assert "http://localhost/trailing" == response.location
def test_trailing_slashes_with_query_parameters(self):
response = self.client.get('/search/?q=r&s=t')
assert 301 == response.status_code
assert "http://localhost/search?q=r&s=t" == response.location
def test_header_xframeoptions_set_to_deny(self):
res = self.client.get('/')
assert 200 == res.status_code
assert 'DENY', res.headers['X-Frame-Options']
|
0298ace270749a6de89595a5bb566739dc63b16e | jsk_apc2016_common/scripts/install_trained_data.py | jsk_apc2016_common/scripts/install_trained_data.py | #!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
download_data(
pkg_name=PKG,
path='trained_data/vgg16_rotation_translation_brightness_372000.chainermodel',
url='https://drive.google.com/open?id=0B9P1L--7Wd2veHZKRkFwZjRiZDQ',
md5='58a0e819ba141a34b1d68cc5e972615b',
)
if __name__ == '__main__':
main()
| Add vgg16 trained_data to download | Add vgg16 trained_data to download
| Python | bsd-3-clause | pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc,pazeshun/jsk_apc | #!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
if __name__ == '__main__':
main()
Add vgg16 trained_data to download | #!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
download_data(
pkg_name=PKG,
path='trained_data/vgg16_rotation_translation_brightness_372000.chainermodel',
url='https://drive.google.com/open?id=0B9P1L--7Wd2veHZKRkFwZjRiZDQ',
md5='58a0e819ba141a34b1d68cc5e972615b',
)
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
if __name__ == '__main__':
main()
<commit_msg>Add vgg16 trained_data to download<commit_after> | #!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
download_data(
pkg_name=PKG,
path='trained_data/vgg16_rotation_translation_brightness_372000.chainermodel',
url='https://drive.google.com/open?id=0B9P1L--7Wd2veHZKRkFwZjRiZDQ',
md5='58a0e819ba141a34b1d68cc5e972615b',
)
if __name__ == '__main__':
main()
| #!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
if __name__ == '__main__':
main()
Add vgg16 trained_data to download#!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
download_data(
pkg_name=PKG,
path='trained_data/vgg16_rotation_translation_brightness_372000.chainermodel',
url='https://drive.google.com/open?id=0B9P1L--7Wd2veHZKRkFwZjRiZDQ',
md5='58a0e819ba141a34b1d68cc5e972615b',
)
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
if __name__ == '__main__':
main()
<commit_msg>Add vgg16 trained_data to download<commit_after>#!/usr/bin/env python
from jsk_data import download_data
def main():
PKG = 'jsk_apc2016_common'
download_data(
pkg_name=PKG,
path='trained_data/vgg16_96000.chainermodel',
url='https://drive.google.com/uc?id=0B9P1L--7Wd2vOTdzOGlJcGM1N00',
md5='3c993d333cf554684b5162c9f69b20cf',
)
download_data(
pkg_name=PKG,
path='trained_data/vgg16_rotation_translation_brightness_372000.chainermodel',
url='https://drive.google.com/open?id=0B9P1L--7Wd2veHZKRkFwZjRiZDQ',
md5='58a0e819ba141a34b1d68cc5e972615b',
)
if __name__ == '__main__':
main()
|
7bcc78cd428fa6d76c11b2f19886ec5e798411c6 | pavement.py | pavement.py | from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/") | from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")
@task
@consume_args
def git_summary(options):
sh('git log --no-merges --pretty=oneline --abbrev-commit %s..HEAD'%options.args[0])
sh('git shortlog -s -n %s..HEAD'%options.args[0])
| Add pre-release git paver task | Add pre-release git paver task
| Python | bsd-3-clause | h5py/h5py,h5py/h5py,h5py/h5py | from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")Add pre-release git paver task | from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")
@task
@consume_args
def git_summary(options):
sh('git log --no-merges --pretty=oneline --abbrev-commit %s..HEAD'%options.args[0])
sh('git shortlog -s -n %s..HEAD'%options.args[0])
| <commit_before>from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")<commit_msg>Add pre-release git paver task<commit_after> | from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")
@task
@consume_args
def git_summary(options):
sh('git log --no-merges --pretty=oneline --abbrev-commit %s..HEAD'%options.args[0])
sh('git shortlog -s -n %s..HEAD'%options.args[0])
| from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")Add pre-release git paver taskfrom paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")
@task
@consume_args
def git_summary(options):
sh('git log --no-merges --pretty=oneline --abbrev-commit %s..HEAD'%options.args[0])
sh('git shortlog -s -n %s..HEAD'%options.args[0])
| <commit_before>from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")<commit_msg>Add pre-release git paver task<commit_after>from paver.easy import *
@task
def release_unix():
sh('python setup.py clean')
sh('rm -f h5py_config.pickle')
sh('python setup.py build --hdf5-version=1.8.4 --mpi=no')
sh('python setup.py test')
sh('python setup.py sdist')
print("Unix release done. Distribution tar file is in dist/")
@task
def release_windows():
for pyver in (26, 27, 32, 33):
exe = r'C:\Python%d\Python.exe' % pyver
hdf5 = r'c:\hdf5\Python%d' % pyver
sh('%s setup.py clean' % exe)
sh('%s api_gen.py' % exe)
sh('%s setup.py build -f --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py test --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
sh('%s setup.py bdist_wininst --hdf5-version=1.8.4 --hdf5=%s' % (exe, hdf5))
print ("Windows exe release done. Distribution files are in dist/")
@task
@consume_args
def git_summary(options):
sh('git log --no-merges --pretty=oneline --abbrev-commit %s..HEAD'%options.args[0])
sh('git shortlog -s -n %s..HEAD'%options.args[0])
|
3e81a2bfd026475b9ab0548c3127aa102066707d | guest-talks/20170828-oo-intro/exercises/test_square_grid.py | guest-talks/20170828-oo-intro/exercises/test_square_grid.py | import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-n"""
expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m)
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
| import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-in"""
expected_string = "0 0 0\n1 1 1\n2 2 2"
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
| Use literals in tests instead of code ;) | Use literals in tests instead of code ;)
| Python | mit | noisebridge/PythonClass,razzius/PyClassLessons,PyClass/PyClassLessons,PyClass/PyClassLessons,noisebridge/PythonClass,razzius/PyClassLessons,noisebridge/PythonClass,razzius/PyClassLessons,noisebridge/PythonClass,PyClass/PyClassLessons,razzius/PyClassLessons | import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-n"""
expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m)
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
Use literals in tests instead of code ;) | import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-in"""
expected_string = "0 0 0\n1 1 1\n2 2 2"
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
| <commit_before>import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-n"""
expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m)
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
<commit_msg>Use literals in tests instead of code ;)<commit_after> | import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-in"""
expected_string = "0 0 0\n1 1 1\n2 2 2"
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
| import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-n"""
expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m)
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
Use literals in tests instead of code ;)import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-in"""
expected_string = "0 0 0\n1 1 1\n2 2 2"
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
| <commit_before>import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-n"""
expected_string = '\n'.join(' '.join(str(x) for x in row) for row in m)
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
<commit_msg>Use literals in tests instead of code ;)<commit_after>import unittest
from square_grid import SquareGrid
class TestSquareGrid(unittest.TestCase):
def setUp(self):
a = [0] * 3
b = [1] * 3
c = [2] * 3
self.matrix= [a,b,c]
self.good_grid = SquareGrid(self.matrix)
def test_error_on_mixed_dimensions(self):
"""Test object initialization"""
four_by_three = self.matrix + [[3] * 3]
with self.assertRaises(ValueError) as err:
g = SquareGrid(four_by_three)
def test_string_representation(self):
"""Test that the object behaves correctly with the `str()` built-in"""
expected_string = "0 0 0\n1 1 1\n2 2 2"
self.assertEqual(str(self.good_grid), expected_string)
def test_length(self):
"""Test that the object returns a useful length"""
self.assertEqual(len(self.good_grid), 3)
|
b57be89c94d050dd1e5f4279f91170982b00cc2e | polyaxon/clusters/management/commands/clean_experiments.py | polyaxon/clusters/management/commands/clean_experiments.py | from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment)
| from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment, update_status=True)
| Update status when stopping experiments | Update status when stopping experiments
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment)
Update status when stopping experiments | from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment, update_status=True)
| <commit_before>from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment)
<commit_msg>Update status when stopping experiments<commit_after> | from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment, update_status=True)
| from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment)
Update status when stopping experimentsfrom django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment, update_status=True)
| <commit_before>from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment)
<commit_msg>Update status when stopping experiments<commit_after>from django.core.management import BaseCommand
from experiments.models import Experiment
from spawner import scheduler
from spawner.utils.constants import ExperimentLifeCycle
class Command(BaseCommand):
def handle(self, *args, **options):
for experiment in Experiment.objects.filter(
experiment_status__status__in=ExperimentLifeCycle.RUNNING_STATUS):
scheduler.stop_experiment(experiment, update_status=True)
|
48ee32acb12519dc644dce5b4f95d285a3176242 | flocker/restapi/_logging.py | flocker/restapi/_logging.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field.forTypes(
u"method", [unicode, bytes], u"The HTTP method of the request.")
REQUEST_PATH = Field.forTypes(
u"request_path", [unicode, bytes],
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field(u"method", lambda method: method,
u"The HTTP method of the request.")
REQUEST_PATH = Field(
u"request_path", lambda path: path,
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
| Address review comment: Just pass through fields we aren't changing. | Address review comment: Just pass through fields we aren't changing.
| Python | apache-2.0 | Azulinho/flocker,lukemarsden/flocker,mbrukman/flocker,agonzalezro/flocker,achanda/flocker,Azulinho/flocker,1d4Nf6/flocker,runcom/flocker,LaynePeng/flocker,moypray/flocker,lukemarsden/flocker,achanda/flocker,wallnerryan/flocker-profiles,AndyHuu/flocker,Azulinho/flocker,runcom/flocker,1d4Nf6/flocker,adamtheturtle/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,hackday-profilers/flocker,1d4Nf6/flocker,LaynePeng/flocker,w4ngyi/flocker,AndyHuu/flocker,jml/flocker,hackday-profilers/flocker,mbrukman/flocker,hackday-profilers/flocker,jml/flocker,achanda/flocker,jml/flocker,runcom/flocker,lukemarsden/flocker,agonzalezro/flocker,AndyHuu/flocker,adamtheturtle/flocker,agonzalezro/flocker,moypray/flocker,w4ngyi/flocker,moypray/flocker,wallnerryan/flocker-profiles,w4ngyi/flocker,adamtheturtle/flocker,LaynePeng/flocker | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field.forTypes(
u"method", [unicode, bytes], u"The HTTP method of the request.")
REQUEST_PATH = Field.forTypes(
u"request_path", [unicode, bytes],
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
Address review comment: Just pass through fields we aren't changing. | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field(u"method", lambda method: method,
u"The HTTP method of the request.")
REQUEST_PATH = Field(
u"request_path", lambda path: path,
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
| <commit_before># Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field.forTypes(
u"method", [unicode, bytes], u"The HTTP method of the request.")
REQUEST_PATH = Field.forTypes(
u"request_path", [unicode, bytes],
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
<commit_msg>Address review comment: Just pass through fields we aren't changing.<commit_after> | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field(u"method", lambda method: method,
u"The HTTP method of the request.")
REQUEST_PATH = Field(
u"request_path", lambda path: path,
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
| # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field.forTypes(
u"method", [unicode, bytes], u"The HTTP method of the request.")
REQUEST_PATH = Field.forTypes(
u"request_path", [unicode, bytes],
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
Address review comment: Just pass through fields we aren't changing.# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field(u"method", lambda method: method,
u"The HTTP method of the request.")
REQUEST_PATH = Field(
u"request_path", lambda path: path,
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
| <commit_before># Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field.forTypes(
u"method", [unicode, bytes], u"The HTTP method of the request.")
REQUEST_PATH = Field.forTypes(
u"request_path", [unicode, bytes],
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
<commit_msg>Address review comment: Just pass through fields we aren't changing.<commit_after># Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
This module defines the Eliot log events emitted by the API implementation.
"""
__all__ = [
"JSON_REQUEST",
"REQUEST",
]
from eliot import Field, ActionType
LOG_SYSTEM = u"api"
METHOD = Field(u"method", lambda method: method,
u"The HTTP method of the request.")
REQUEST_PATH = Field(
u"request_path", lambda path: path,
u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
u"json", [unicode, bytes, dict, list, None, bool, float],
u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
u"code", [int],
u"The response code for the request.")
REQUEST = ActionType(
LOG_SYSTEM + u":request",
[REQUEST_PATH, METHOD],
[],
u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
LOG_SYSTEM + u":json_request",
[JSON],
[RESPONSE_CODE, JSON],
u"A request containing JSON request and response.")
|
c9ca005e8129c784e108bb77719f201e110433f1 | settings/models.py | settings/models.py | from django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, null = True)
machine_name = models.SlugField(max_length = 50)
simple_name = models.CharField(max_length = 80) | from django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, unique = True, null = True)
machine_name = models.SlugField(max_length = 50, unique = True)
simple_name = models.CharField(max_length = 80) | Fix uniqueness for voting systems | Fix uniqueness for voting systems
| Python | mit | kuboschek/jay,OpenJUB/jay,kuboschek/jay,kuboschek/jay,OpenJUB/jay,OpenJUB/jay | from django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, null = True)
machine_name = models.SlugField(max_length = 50)
simple_name = models.CharField(max_length = 80)Fix uniqueness for voting systems | from django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, unique = True, null = True)
machine_name = models.SlugField(max_length = 50, unique = True)
simple_name = models.CharField(max_length = 80) | <commit_before>from django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, null = True)
machine_name = models.SlugField(max_length = 50)
simple_name = models.CharField(max_length = 80)<commit_msg>Fix uniqueness for voting systems<commit_after> | from django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, unique = True, null = True)
machine_name = models.SlugField(max_length = 50, unique = True)
simple_name = models.CharField(max_length = 80) | from django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, null = True)
machine_name = models.SlugField(max_length = 50)
simple_name = models.CharField(max_length = 80)Fix uniqueness for voting systemsfrom django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, unique = True, null = True)
machine_name = models.SlugField(max_length = 50, unique = True)
simple_name = models.CharField(max_length = 80) | <commit_before>from django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, null = True)
machine_name = models.SlugField(max_length = 50)
simple_name = models.CharField(max_length = 80)<commit_msg>Fix uniqueness for voting systems<commit_after>from django.db import models
# Create your models here.
class GlobalSettings(models.Model):
DOMAIN_NAME = 'FQDN'
FORCE_HTTPS = 'HTTPS'
ADMIN_MAIL = 'ADM_MAIL'
ADMIN_NAME = 'ADM_NAME'
KEY_CHOICES = (
(DOMAIN_NAME, 'Domain Name'),
(FORCE_HTTPS, 'Force HTTPS'),
(ADMIN_MAIL, 'Admin de-mail'),
(ADMIN_NAME, 'Admin name')
)
key = models.CharField(max_length = 8, choices = KEY_CHOICES)
value = models.CharField(max_length = 256)
class VotingSystem(models.Model):
subdomain_name = models.SlugField(max_length = 30, unique = True, null = True)
machine_name = models.SlugField(max_length = 50, unique = True)
simple_name = models.CharField(max_length = 80) |
7938589c950b9b36d215aa85224c931a080c104e | statsd/gauge.py | statsd/gauge.py | import statsd
import decimal
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, (int, long, float, decimal.Decimal))
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
| import statsd
from . import compat
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, compat.NUM_TYPES)
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
| Use compat.NUM_TYPES due to removal of long in py3k | Use compat.NUM_TYPES due to removal of long in py3k
| Python | bsd-3-clause | wolph/python-statsd | import statsd
import decimal
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, (int, long, float, decimal.Decimal))
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
Use compat.NUM_TYPES due to removal of long in py3k | import statsd
from . import compat
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, compat.NUM_TYPES)
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
| <commit_before>import statsd
import decimal
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, (int, long, float, decimal.Decimal))
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
<commit_msg>Use compat.NUM_TYPES due to removal of long in py3k<commit_after> | import statsd
from . import compat
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, compat.NUM_TYPES)
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
| import statsd
import decimal
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, (int, long, float, decimal.Decimal))
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
Use compat.NUM_TYPES due to removal of long in py3kimport statsd
from . import compat
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, compat.NUM_TYPES)
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
| <commit_before>import statsd
import decimal
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, (int, long, float, decimal.Decimal))
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
<commit_msg>Use compat.NUM_TYPES due to removal of long in py3k<commit_after>import statsd
from . import compat
class Gauge(statsd.Client):
'''Class to implement a statsd gauge
'''
def send(self, subname, value):
'''Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The gauge value to send
'''
assert isinstance(value, compat.NUM_TYPES)
name = self._get_name(self.name, subname)
self.logger.info('%s: %s', name, value)
return statsd.Client._send(self, {name: '%s|g' % value})
|
9e62292ed25860a2e376c5d98c8ff7762bc1346b | scripts/slave/chromium/dart_buildbot_run.py | scripts/slave/chromium/dart_buildbot_run.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
| #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
# Temporary until 1.6 ships on stable.
if builder_name.endswith('-be') or builder_name.endswith("-dev"):
script = 'src/dart/tools/dartium/buildbot_annotated_steps.py'
else:
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
| Use the annotated steps from the dart dir | Use the annotated steps from the dart dir
TBR=whesse
Review URL: https://codereview.chromium.org/352223009
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@280292 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
Use the annotated steps from the dart dir
TBR=whesse
Review URL: https://codereview.chromium.org/352223009
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@280292 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
# Temporary until 1.6 ships on stable.
if builder_name.endswith('-be') or builder_name.endswith("-dev"):
script = 'src/dart/tools/dartium/buildbot_annotated_steps.py'
else:
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
| <commit_before>#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
<commit_msg>Use the annotated steps from the dart dir
TBR=whesse
Review URL: https://codereview.chromium.org/352223009
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@280292 0039d316-1c4b-4281-b951-d872f2087c98<commit_after> | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
# Temporary until 1.6 ships on stable.
if builder_name.endswith('-be') or builder_name.endswith("-dev"):
script = 'src/dart/tools/dartium/buildbot_annotated_steps.py'
else:
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
| #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
Use the annotated steps from the dart dir
TBR=whesse
Review URL: https://codereview.chromium.org/352223009
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@280292 0039d316-1c4b-4281-b951-d872f2087c98#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
# Temporary until 1.6 ships on stable.
if builder_name.endswith('-be') or builder_name.endswith("-dev"):
script = 'src/dart/tools/dartium/buildbot_annotated_steps.py'
else:
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
| <commit_before>#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
<commit_msg>Use the annotated steps from the dart dir
TBR=whesse
Review URL: https://codereview.chromium.org/352223009
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@280292 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
# Temporary until 1.6 ships on stable.
if builder_name.endswith('-be') or builder_name.endswith("-dev"):
script = 'src/dart/tools/dartium/buildbot_annotated_steps.py'
else:
script = 'src/dartium_tools/buildbot_annotated_steps.py'
chromium_utils.RunCommand([sys.executable, script])
# BIG HACK
# Normal ninja clobbering does not work due to symlinks/python on windows
# Full clobbering before building does not work since it will destroy
# the ninja build files
# So we basically clobber at the end here
if chromium_utils.IsWindows() and 'full' in builder_name:
chromium_utils.RemoveDirectory('src/out')
return 0
if __name__ == '__main__':
sys.exit(main())
|
10009f8a19b417359d41a5e83ff5083e6862b891 | algorithms/math/sieve_eratosthenes.py | algorithms/math/sieve_eratosthenes.py | """
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Depth First Search Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
| """
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Sieve of Eratosthenes Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
| Fix Sieve of Eratosthenes Overview header | Fix Sieve of Eratosthenes Overview header
| Python | bsd-3-clause | rexshihaoren/algorithms,stphivos/algorithms | """
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Depth First Search Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
Fix Sieve of Eratosthenes Overview header | """
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Sieve of Eratosthenes Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
| <commit_before>"""
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Depth First Search Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
<commit_msg>Fix Sieve of Eratosthenes Overview header<commit_after> | """
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Sieve of Eratosthenes Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
| """
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Depth First Search Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
Fix Sieve of Eratosthenes Overview header"""
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Sieve of Eratosthenes Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
| <commit_before>"""
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Depth First Search Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
<commit_msg>Fix Sieve of Eratosthenes Overview header<commit_after>"""
sieve_eratosthenes.py
Implementation of the Sieve of Eratosthenes algorithm.
Sieve of Eratosthenes Overview:
------------------------
Is a simple, ancient algorithm for finding all prime numbers
up to any given limit. It does so by iteratively marking as composite (i.e. not prime)
the multiples of each prime, starting with the multiples of 2.
The sieve of Eratosthenes is one of the most efficient ways
to find all of the smaller primes (below 10 million or so).
Time Complexity: O(n log log n)
Pseudocode: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
def eratosthenes(end,start=2):
if start < 2:
start = 2
primes = range(start,end)
marker = 2
while marker < end:
for i in xrange(marker, end+1):
if marker*i in primes:
primes.remove(marker*i)
marker += 1
return primes
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.