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
449ec018d9403e1732528c2806ec68e8417e6725
raco/rules.py
raco/rules.py
import algebra import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) import algebra class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
Resolve circular reference during import
Resolve circular reference during import
Python
bsd-3-clause
uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco
import algebra import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__) Resolve circular reference during import
import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) import algebra class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
<commit_before>import algebra import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__) <commit_msg>Resolve circular reference during import<commit_after>
import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) import algebra class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
import algebra import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__) Resolve circular reference during importimport boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) import algebra class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
<commit_before>import algebra import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__) <commit_msg>Resolve circular reference during import<commit_after>import boolean class Rule: """ Argument is an expression tree Returns a possibly modified expression tree """ def __call__(self, expr): return self.fire(expr) import algebra class CrossProduct2Join(Rule): """A rewrite rule for removing Cross Product""" def fire(self, expr): if isinstance(expr, algebra.CrossProduct): return algebra.Join(boolean.EQ(boolean.NumericLiteral(1),boolean.NumericLiteral(1)), expr.left, expr.right) return expr def __str__(self): return "CrossProduct(left, right) => Join(1=1, left, right)" class removeProject(Rule): """A rewrite rule for removing Projections""" def fire(self, expr): if isinstance(expr, algebra.Project): return expr.input return expr def __str__(self): return "Project => ()" class OneToOne(Rule): def __init__(self, opfrom, opto): self.opfrom = opfrom self.opto = opto def fire(self, expr): if isinstance(expr, self.opfrom): newop = self.opto() newop.copy(expr) return newop return expr def __str__(self): return "%s => %s" % (self.opfrom.__name__,self.opto.__name__)
ea73a999ffbc936f7e072a310f05ee2cb26b6c21
openprocurement/tender/limited/adapters.py
openprocurement/tender/limited/adapters.py
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.openua.constants import STATUS4ROLE from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender
Add import and constant in adapter
Add import and constant in adapter
Python
apache-2.0
openprocurement/openprocurement.tender.limited
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender Add import and constant in adapter
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.openua.constants import STATUS4ROLE from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender
<commit_before># -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender <commit_msg>Add import and constant in adapter<commit_after>
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.openua.constants import STATUS4ROLE from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender
# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender Add import and constant in adapter# -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.openua.constants import STATUS4ROLE from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender
<commit_before># -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender <commit_msg>Add import and constant in adapter<commit_after># -*- coding: utf-8 -*- from openprocurement.tender.core.adapters import TenderConfigurator from openprocurement.tender.openua.constants import STATUS4ROLE from openprocurement.tender.limited.models import ( ReportingTender, NegotiationTender, NegotiationQuickTender ) class TenderReportingConfigurator(TenderConfigurator): """ Reporting Tender configuration adapter """ name = "Reporting Tender configurator" model = ReportingTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationConfigurator(TenderConfigurator): """ Negotiation Tender configuration adapter """ name = "Negotiation Tender configurator" model = NegotiationTender # Dictionary with allowed complaint statuses for operations for each role allowed_statuses_for_complaint_operations_for_roles = STATUS4ROLE @property def edit_accreditation(self): raise NotImplemented class TenderNegotiationQuickConfigurator(TenderNegotiationConfigurator): """ Negotiation Quick Tender configuration adapter """ name = "Negotiation Quick Tender configurator" model = NegotiationQuickTender
6ea9d0c4b4e2a117e3e74c34cc77f83d262e62d8
sendgrid_events/models.py
sendgrid_events/models.py
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for line in data.split("\r\n"): if line: d = json.loads(line.strip()) events.append(Event.objects.create( kind=d["event"], email=d["email"], data=d )) batch_processed.send(sender=Event, events=events) return events
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for event in json.loads(data): events.append(Event.objects.create( kind=event["event"], email=event["email"], data=event )) batch_processed.send(sender=Event, events=events) return events
Update for latest Sendgrid webhook format
Update for latest Sendgrid webhook format
Python
bsd-3-clause
digital-eskimo/django-sendgrid-events,kronok/django-sendgrid-events,eldarion/django-sendgrid-events,rorito/django-sendgrid-events
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for line in data.split("\r\n"): if line: d = json.loads(line.strip()) events.append(Event.objects.create( kind=d["event"], email=d["email"], data=d )) batch_processed.send(sender=Event, events=events) return events Update for latest Sendgrid webhook format
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for event in json.loads(data): events.append(Event.objects.create( kind=event["event"], email=event["email"], data=event )) batch_processed.send(sender=Event, events=events) return events
<commit_before>import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for line in data.split("\r\n"): if line: d = json.loads(line.strip()) events.append(Event.objects.create( kind=d["event"], email=d["email"], data=d )) batch_processed.send(sender=Event, events=events) return events <commit_msg>Update for latest Sendgrid webhook format<commit_after>
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for event in json.loads(data): events.append(Event.objects.create( kind=event["event"], email=event["email"], data=event )) batch_processed.send(sender=Event, events=events) return events
import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for line in data.split("\r\n"): if line: d = json.loads(line.strip()) events.append(Event.objects.create( kind=d["event"], email=d["email"], data=d )) batch_processed.send(sender=Event, events=events) return events Update for latest Sendgrid webhook formatimport json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for event in json.loads(data): events.append(Event.objects.create( kind=event["event"], email=event["email"], data=event )) batch_processed.send(sender=Event, events=events) return events
<commit_before>import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for line in data.split("\r\n"): if line: d = json.loads(line.strip()) events.append(Event.objects.create( kind=d["event"], email=d["email"], data=d )) batch_processed.send(sender=Event, events=events) return events <commit_msg>Update for latest Sendgrid webhook format<commit_after>import json from django.db import models from django.utils import timezone from jsonfield import JSONField from sendgrid_events.signals import batch_processed class Event(models.Model): kind = models.CharField(max_length=75) email = models.CharField(max_length=150) data = JSONField(blank=True) created_at = models.DateTimeField(default=timezone.now) @classmethod def process_batch(cls, data): events = [] for event in json.loads(data): events.append(Event.objects.create( kind=event["event"], email=event["email"], data=event )) batch_processed.send(sender=Event, events=events) return events
0434b08717c58d5b8bc4aa037f9811df73e73367
docs/examples/compute/cloudstack/create_node_advanced_zone.py
docs/examples/compute/cloudstack/create_node_advanced_zone.py
from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], network=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips)
from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], networks=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips)
Fix a typo, it should be "networks", not "network".
docs: Fix a typo, it should be "networks", not "network".
Python
apache-2.0
erjohnso/libcloud,pantheon-systems/libcloud,ZuluPro/libcloud,curoverse/libcloud,Verizon/libcloud,jerryblakley/libcloud,wuyuewen/libcloud,ByteInternet/libcloud,sergiorua/libcloud,thesquelched/libcloud,niteoweb/libcloud,thesquelched/libcloud,cloudControl/libcloud,atsaki/libcloud,wrigri/libcloud,aleGpereira/libcloud,schaubl/libcloud,aviweit/libcloud,t-tran/libcloud,briancurtin/libcloud,DimensionDataCBUSydney/libcloud,techhat/libcloud,SecurityCompass/libcloud,MrBasset/libcloud,t-tran/libcloud,MrBasset/libcloud,sahildua2305/libcloud,aleGpereira/libcloud,MrBasset/libcloud,sgammon/libcloud,Cloud-Elasticity-Services/as-libcloud,DimensionDataCBUSydney/libcloud,wido/libcloud,marcinzaremba/libcloud,sfriesel/libcloud,aviweit/libcloud,kater169/libcloud,niteoweb/libcloud,JamesGuthrie/libcloud,marcinzaremba/libcloud,DimensionDataCBUSydney/libcloud,atsaki/libcloud,StackPointCloud/libcloud,mistio/libcloud,sahildua2305/libcloud,ByteInternet/libcloud,mgogoulos/libcloud,ZuluPro/libcloud,curoverse/libcloud,Scalr/libcloud,pantheon-systems/libcloud,mistio/libcloud,mathspace/libcloud,briancurtin/libcloud,apache/libcloud,cloudControl/libcloud,erjohnso/libcloud,atsaki/libcloud,Itxaka/libcloud,cryptickp/libcloud,iPlantCollaborativeOpenSource/libcloud,mtekel/libcloud,watermelo/libcloud,jimbobhickville/libcloud,samuelchong/libcloud,erjohnso/libcloud,wrigri/libcloud,vongazman/libcloud,jerryblakley/libcloud,NexusIS/libcloud,watermelo/libcloud,aviweit/libcloud,supertom/libcloud,StackPointCloud/libcloud,ZuluPro/libcloud,watermelo/libcloud,apache/libcloud,mathspace/libcloud,munkiat/libcloud,Kami/libcloud,wido/libcloud,mathspace/libcloud,Scalr/libcloud,smaffulli/libcloud,lochiiconnectivity/libcloud,lochiiconnectivity/libcloud,vongazman/libcloud,thesquelched/libcloud,supertom/libcloud,mgogoulos/libcloud,wuyuewen/libcloud,carletes/libcloud,sahildua2305/libcloud,sfriesel/libcloud,schaubl/libcloud,Verizon/libcloud,smaffulli/libcloud,cryptickp/libcloud,NexusIS/libcloud,carletes/libcloud,mbrukman/libcloud,pquentin/libcloud,wuyuewen/libcloud,mtekel/libcloud,andrewsomething/libcloud,cryptickp/libcloud,schaubl/libcloud,ClusterHQ/libcloud,Scalr/libcloud,Cloud-Elasticity-Services/as-libcloud,niteoweb/libcloud,smaffulli/libcloud,mistio/libcloud,samuelchong/libcloud,jerryblakley/libcloud,illfelder/libcloud,sergiorua/libcloud,wido/libcloud,marcinzaremba/libcloud,NexusIS/libcloud,cloudControl/libcloud,techhat/libcloud,t-tran/libcloud,pquentin/libcloud,dcorbacho/libcloud,SecurityCompass/libcloud,aleGpereira/libcloud,Kami/libcloud,illfelder/libcloud,SecurityCompass/libcloud,mbrukman/libcloud,mtekel/libcloud,sfriesel/libcloud,andrewsomething/libcloud,iPlantCollaborativeOpenSource/libcloud,lochiiconnectivity/libcloud,pquentin/libcloud,ByteInternet/libcloud,JamesGuthrie/libcloud,samuelchong/libcloud,sgammon/libcloud,Itxaka/libcloud,Kami/libcloud,wrigri/libcloud,supertom/libcloud,mgogoulos/libcloud,Verizon/libcloud,sergiorua/libcloud,munkiat/libcloud,pantheon-systems/libcloud,kater169/libcloud,Cloud-Elasticity-Services/as-libcloud,techhat/libcloud,ClusterHQ/libcloud,curoverse/libcloud,jimbobhickville/libcloud,StackPointCloud/libcloud,dcorbacho/libcloud,Itxaka/libcloud,briancurtin/libcloud,illfelder/libcloud,jimbobhickville/libcloud,vongazman/libcloud,JamesGuthrie/libcloud,andrewsomething/libcloud,kater169/libcloud,munkiat/libcloud,dcorbacho/libcloud,apache/libcloud,iPlantCollaborativeOpenSource/libcloud,mbrukman/libcloud,carletes/libcloud
from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], network=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips) docs: Fix a typo, it should be "networks", not "network".
from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], networks=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips)
<commit_before>from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], network=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips) <commit_msg>docs: Fix a typo, it should be "networks", not "network".<commit_after>
from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], networks=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips)
from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], network=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips) docs: Fix a typo, it should be "networks", not "network".from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], networks=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips)
<commit_before>from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], network=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips) <commit_msg>docs: Fix a typo, it should be "networks", not "network".<commit_after>from pprint import pprint from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver apikey = 'your api key' secretkey = 'your secret key' Driver = get_driver(Provider.IKOULA) driver = Driver(key=apikey, secret=secretkey) # This returns a list of CloudStackNetwork objects nets = driver.ex_list_networks() # List the images/templates available # This returns a list of NodeImage objects images = driver.list_images() # List the instance types # This returns a list of NodeSize objects sizes = driver.list_sizes() # Create the node # This returns a Node object node = driver.create_node(name='libcloud', image=images[0], size=sizes[0], networks=[nets[0]]) # The node has a private IP in the guest network used # No public IPs and no rules pprint(node.extra) pprint(node.private_ips)
6c4b69e071dba6e1a7fddf350a89aa348edb343e
scripts/indent_trace_log.py
scripts/indent_trace_log.py
#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import sys import os import fileinput def read_lines(fp): indent = "" for line in fp: if 'TRACE' in line and 'EXIT' in line: indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if 'TRACE' in line and 'ENTRY' in line: indent += " " def main(): filepath = sys.argv[1] if filepath == '-': read_lines(fileinput.input()) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp) if __name__ == "__main__": main()
#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import argparse, sys, os, fileinput, re def is_entry(line): return 'TRACE' in line and 'ENTRY' in line def is_exit(line): return 'TRACE' in line and 'EXIT' in line def print_indented(line, indent): if is_exit(line): indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if is_entry(line): indent += " " return indent def read_lines(fp, ids): indent = "" if len(ids) == 0: for line in fp: indent = print_indented(line, indent) else: rx = re.compile('.+ (?:actor|ID = )([0-9]+) .+') for line in fp: rx_res = rx.match(line) if rx_res != None and rx_res.group(1) in ids: indent = print_indented(line, indent) def read_ids(ids_file): if os.path.isfile(ids_file): with open(ids_file) as fp: return fp.read().splitlines() return [] def main(): parser = argparse.ArgumentParser(description='Add a new C++ class.') parser.add_argument('-i', dest='ids_file', help='only include actors with IDs from file') parser.add_argument("log", help='path to the log file or "-" for reading from STDIN') args = parser.parse_args() filepath = args.log ids = read_ids(args.ids_file) if filepath == '-': read_lines(fileinput.input(), ids) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp, ids) if __name__ == "__main__": main()
Add filtering option to indentation script
Add filtering option to indentation script
Python
bsd-3-clause
actor-framework/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework
#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import sys import os import fileinput def read_lines(fp): indent = "" for line in fp: if 'TRACE' in line and 'EXIT' in line: indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if 'TRACE' in line and 'ENTRY' in line: indent += " " def main(): filepath = sys.argv[1] if filepath == '-': read_lines(fileinput.input()) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp) if __name__ == "__main__": main() Add filtering option to indentation script
#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import argparse, sys, os, fileinput, re def is_entry(line): return 'TRACE' in line and 'ENTRY' in line def is_exit(line): return 'TRACE' in line and 'EXIT' in line def print_indented(line, indent): if is_exit(line): indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if is_entry(line): indent += " " return indent def read_lines(fp, ids): indent = "" if len(ids) == 0: for line in fp: indent = print_indented(line, indent) else: rx = re.compile('.+ (?:actor|ID = )([0-9]+) .+') for line in fp: rx_res = rx.match(line) if rx_res != None and rx_res.group(1) in ids: indent = print_indented(line, indent) def read_ids(ids_file): if os.path.isfile(ids_file): with open(ids_file) as fp: return fp.read().splitlines() return [] def main(): parser = argparse.ArgumentParser(description='Add a new C++ class.') parser.add_argument('-i', dest='ids_file', help='only include actors with IDs from file') parser.add_argument("log", help='path to the log file or "-" for reading from STDIN') args = parser.parse_args() filepath = args.log ids = read_ids(args.ids_file) if filepath == '-': read_lines(fileinput.input(), ids) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp, ids) if __name__ == "__main__": main()
<commit_before>#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import sys import os import fileinput def read_lines(fp): indent = "" for line in fp: if 'TRACE' in line and 'EXIT' in line: indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if 'TRACE' in line and 'ENTRY' in line: indent += " " def main(): filepath = sys.argv[1] if filepath == '-': read_lines(fileinput.input()) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp) if __name__ == "__main__": main() <commit_msg>Add filtering option to indentation script<commit_after>
#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import argparse, sys, os, fileinput, re def is_entry(line): return 'TRACE' in line and 'ENTRY' in line def is_exit(line): return 'TRACE' in line and 'EXIT' in line def print_indented(line, indent): if is_exit(line): indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if is_entry(line): indent += " " return indent def read_lines(fp, ids): indent = "" if len(ids) == 0: for line in fp: indent = print_indented(line, indent) else: rx = re.compile('.+ (?:actor|ID = )([0-9]+) .+') for line in fp: rx_res = rx.match(line) if rx_res != None and rx_res.group(1) in ids: indent = print_indented(line, indent) def read_ids(ids_file): if os.path.isfile(ids_file): with open(ids_file) as fp: return fp.read().splitlines() return [] def main(): parser = argparse.ArgumentParser(description='Add a new C++ class.') parser.add_argument('-i', dest='ids_file', help='only include actors with IDs from file') parser.add_argument("log", help='path to the log file or "-" for reading from STDIN') args = parser.parse_args() filepath = args.log ids = read_ids(args.ids_file) if filepath == '-': read_lines(fileinput.input(), ids) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp, ids) if __name__ == "__main__": main()
#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import sys import os import fileinput def read_lines(fp): indent = "" for line in fp: if 'TRACE' in line and 'EXIT' in line: indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if 'TRACE' in line and 'ENTRY' in line: indent += " " def main(): filepath = sys.argv[1] if filepath == '-': read_lines(fileinput.input()) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp) if __name__ == "__main__": main() Add filtering option to indentation script#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import argparse, sys, os, fileinput, re def is_entry(line): return 'TRACE' in line and 'ENTRY' in line def is_exit(line): return 'TRACE' in line and 'EXIT' in line def print_indented(line, indent): if is_exit(line): indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if is_entry(line): indent += " " return indent def read_lines(fp, ids): indent = "" if len(ids) == 0: for line in fp: indent = print_indented(line, indent) else: rx = re.compile('.+ (?:actor|ID = )([0-9]+) .+') for line in fp: rx_res = rx.match(line) if rx_res != None and rx_res.group(1) in ids: indent = print_indented(line, indent) def read_ids(ids_file): if os.path.isfile(ids_file): with open(ids_file) as fp: return fp.read().splitlines() return [] def main(): parser = argparse.ArgumentParser(description='Add a new C++ class.') parser.add_argument('-i', dest='ids_file', help='only include actors with IDs from file') parser.add_argument("log", help='path to the log file or "-" for reading from STDIN') args = parser.parse_args() filepath = args.log ids = read_ids(args.ids_file) if filepath == '-': read_lines(fileinput.input(), ids) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp, ids) if __name__ == "__main__": main()
<commit_before>#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import sys import os import fileinput def read_lines(fp): indent = "" for line in fp: if 'TRACE' in line and 'EXIT' in line: indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if 'TRACE' in line and 'ENTRY' in line: indent += " " def main(): filepath = sys.argv[1] if filepath == '-': read_lines(fileinput.input()) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp) if __name__ == "__main__": main() <commit_msg>Add filtering option to indentation script<commit_after>#!/usr/bin/env python # Indents a CAF log with trace verbosity. The script does *not* deal with a log # with multiple threads. # usage (read file): indent_trace_log.py FILENAME # (read stdin): indent_trace_log.py - import argparse, sys, os, fileinput, re def is_entry(line): return 'TRACE' in line and 'ENTRY' in line def is_exit(line): return 'TRACE' in line and 'EXIT' in line def print_indented(line, indent): if is_exit(line): indent = indent[:-2] sys.stdout.write(indent) sys.stdout.write(line) if is_entry(line): indent += " " return indent def read_lines(fp, ids): indent = "" if len(ids) == 0: for line in fp: indent = print_indented(line, indent) else: rx = re.compile('.+ (?:actor|ID = )([0-9]+) .+') for line in fp: rx_res = rx.match(line) if rx_res != None and rx_res.group(1) in ids: indent = print_indented(line, indent) def read_ids(ids_file): if os.path.isfile(ids_file): with open(ids_file) as fp: return fp.read().splitlines() return [] def main(): parser = argparse.ArgumentParser(description='Add a new C++ class.') parser.add_argument('-i', dest='ids_file', help='only include actors with IDs from file') parser.add_argument("log", help='path to the log file or "-" for reading from STDIN') args = parser.parse_args() filepath = args.log ids = read_ids(args.ids_file) if filepath == '-': read_lines(fileinput.input(), ids) else: if not os.path.isfile(filepath): sys.exit() with open(filepath) as fp: read_lines(fp, ids) if __name__ == "__main__": main()
0a0b1087b0067259b774b91809a166d74c8c695c
spacy/lang/id/__init__.py
spacy/lang/id/__init__.py
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP tag_map = TAG_MAP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
Make tag map available in Indonesian defaults
Make tag map available in Indonesian defaults
Python
mit
spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"] Make tag map available in Indonesian defaults
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP tag_map = TAG_MAP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
<commit_before># coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"] <commit_msg>Make tag map available in Indonesian defaults<commit_after>
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP tag_map = TAG_MAP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"] Make tag map available in Indonesian defaults# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP tag_map = TAG_MAP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
<commit_before># coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"] <commit_msg>Make tag map available in Indonesian defaults<commit_after># coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP tag_map = TAG_MAP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
3d3aba1ff780061ced014c4387f1d91b9fb168db
skimage/measure/__init__.py
skimage/measure/__init__.py
from ._find_contours import find_contours from ._marching_cubes import marching_cubes, mesh_surface_area from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'profile_line']
from ._find_contours import find_contours from ._marching_cubes import (marching_cubes, mesh_surface_area, correct_mesh_orientation) from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'correct_mesh_orientation', 'profile_line']
Add correct_mesh_orientation to skimage.measure imports
Add correct_mesh_orientation to skimage.measure imports
Python
bsd-3-clause
rjeli/scikit-image,pratapvardhan/scikit-image,paalge/scikit-image,WarrenWeckesser/scikits-image,blink1073/scikit-image,juliusbierk/scikit-image,robintw/scikit-image,ofgulban/scikit-image,ClinicalGraphics/scikit-image,chintak/scikit-image,bsipocz/scikit-image,jwiggins/scikit-image,SamHames/scikit-image,michaelaye/scikit-image,chriscrosscutler/scikit-image,robintw/scikit-image,newville/scikit-image,emon10005/scikit-image,ajaybhat/scikit-image,bsipocz/scikit-image,keflavich/scikit-image,michaelaye/scikit-image,chintak/scikit-image,Hiyorimi/scikit-image,GaZ3ll3/scikit-image,youprofit/scikit-image,warmspringwinds/scikit-image,SamHames/scikit-image,ClinicalGraphics/scikit-image,michaelpacer/scikit-image,paalge/scikit-image,youprofit/scikit-image,vighneshbirodkar/scikit-image,jwiggins/scikit-image,oew1v07/scikit-image,oew1v07/scikit-image,keflavich/scikit-image,chintak/scikit-image,bennlich/scikit-image,GaZ3ll3/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,vighneshbirodkar/scikit-image,dpshelio/scikit-image,Midafi/scikit-image,emon10005/scikit-image,chintak/scikit-image,newville/scikit-image,rjeli/scikit-image,ajaybhat/scikit-image,pratapvardhan/scikit-image,chriscrosscutler/scikit-image,warmspringwinds/scikit-image,Hiyorimi/scikit-image,ofgulban/scikit-image,Britefury/scikit-image,Britefury/scikit-image,paalge/scikit-image,dpshelio/scikit-image,juliusbierk/scikit-image,Midafi/scikit-image,michaelpacer/scikit-image,bennlich/scikit-image,SamHames/scikit-image,SamHames/scikit-image,blink1073/scikit-image,rjeli/scikit-image,vighneshbirodkar/scikit-image
from ._find_contours import find_contours from ._marching_cubes import marching_cubes, mesh_surface_area from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'profile_line'] Add correct_mesh_orientation to skimage.measure imports
from ._find_contours import find_contours from ._marching_cubes import (marching_cubes, mesh_surface_area, correct_mesh_orientation) from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'correct_mesh_orientation', 'profile_line']
<commit_before>from ._find_contours import find_contours from ._marching_cubes import marching_cubes, mesh_surface_area from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'profile_line'] <commit_msg>Add correct_mesh_orientation to skimage.measure imports<commit_after>
from ._find_contours import find_contours from ._marching_cubes import (marching_cubes, mesh_surface_area, correct_mesh_orientation) from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'correct_mesh_orientation', 'profile_line']
from ._find_contours import find_contours from ._marching_cubes import marching_cubes, mesh_surface_area from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'profile_line'] Add correct_mesh_orientation to skimage.measure importsfrom ._find_contours import find_contours from ._marching_cubes import (marching_cubes, mesh_surface_area, correct_mesh_orientation) from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'correct_mesh_orientation', 'profile_line']
<commit_before>from ._find_contours import find_contours from ._marching_cubes import marching_cubes, mesh_surface_area from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'profile_line'] <commit_msg>Add correct_mesh_orientation to skimage.measure imports<commit_after>from ._find_contours import find_contours from ._marching_cubes import (marching_cubes, mesh_surface_area, correct_mesh_orientation) from ._regionprops import regionprops, perimeter from ._structural_similarity import structural_similarity from ._polygon import approximate_polygon, subdivide_polygon from ._moments import moments, moments_central, moments_normalized, moments_hu from .profile import profile_line from .fit import LineModel, CircleModel, EllipseModel, ransac from .block import block_reduce __all__ = ['find_contours', 'regionprops', 'perimeter', 'structural_similarity', 'approximate_polygon', 'subdivide_polygon', 'LineModel', 'CircleModel', 'EllipseModel', 'ransac', 'block_reduce', 'moments', 'moments_central', 'moments_normalized', 'moments_hu', 'marching_cubes', 'mesh_surface_area', 'correct_mesh_orientation', 'profile_line']
967ed5fa4297bc4091a0474eab95f6b082c4bba2
PythonWhiteLibrary/setup.py
PythonWhiteLibrary/setup.py
import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["../WhiteLibrary/bin/CSWhiteLibrary.dll"]}, )
import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["WhiteLibrary/bin/CSWhiteLibrary.dll"]}, )
Revert "Trying to fix the path"
Revert "Trying to fix the path" This reverts commit f89b139ba7e17af8bc7ca42a8cc9a3f821825454.
Python
apache-2.0
Omenia/robotframework-whitelibrary,Omenia/robotframework-whitelibrary
import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["../WhiteLibrary/bin/CSWhiteLibrary.dll"]}, ) Revert "Trying to fix the path" This reverts commit f89b139ba7e17af8bc7ca42a8cc9a3f821825454.
import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["WhiteLibrary/bin/CSWhiteLibrary.dll"]}, )
<commit_before>import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["../WhiteLibrary/bin/CSWhiteLibrary.dll"]}, ) <commit_msg>Revert "Trying to fix the path" This reverts commit f89b139ba7e17af8bc7ca42a8cc9a3f821825454.<commit_after>
import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["WhiteLibrary/bin/CSWhiteLibrary.dll"]}, )
import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["../WhiteLibrary/bin/CSWhiteLibrary.dll"]}, ) Revert "Trying to fix the path" This reverts commit f89b139ba7e17af8bc7ca42a8cc9a3f821825454.import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["WhiteLibrary/bin/CSWhiteLibrary.dll"]}, )
<commit_before>import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["../WhiteLibrary/bin/CSWhiteLibrary.dll"]}, ) <commit_msg>Revert "Trying to fix the path" This reverts commit f89b139ba7e17af8bc7ca42a8cc9a3f821825454.<commit_after>import distutils.sysconfig from distutils.core import setup setup(name = 'robotframework-whitelibrary', version = '0.0.1', description = 'Windows GUI testing library for Robot Framework', author = 'SALabs', url = 'https://github.com/Omenia/robotframework-whitelibrary', package_dir = {'' : 'src'}, py_modules = ['WhiteLibrary'], package_data = {'robotframework-whitelibrary': ["WhiteLibrary/bin/CSWhiteLibrary.dll"]}, )
8df7c8b048bc7c2883819869027764e030c8a2e6
fabfile.py
fabfile.py
from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd)
from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/nkhumphreys/assets/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd)
Change location of static files on server
Change location of static files on server
Python
mit
nkhumphreys/gobananas,nkhumphreys/gobananas,nkhumphreys/gobananas
from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd) Change location of static files on server
from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/nkhumphreys/assets/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd)
<commit_before>from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd) <commit_msg>Change location of static files on server<commit_after>
from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/nkhumphreys/assets/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd)
from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd) Change location of static files on serverfrom fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/nkhumphreys/assets/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd)
<commit_before>from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd) <commit_msg>Change location of static files on server<commit_after>from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/nkhumphreys/assets/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd)
92ca74258f0028bf3b12a84a7f7741f7b72ec45d
db/migrations/migration2.py
db/migrations/migration2.py
import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER not in mapping[1]: raise Exception("To complete migration 2 please run openbazaard at least once using the original " "data folder location before moving it to a different location.") path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close()
import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER in mapping[1]: path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close()
Remove exception in migration Some users moved their data folder despite the code not permitting it yet. This migration will fail for those users, but they will still be able to run the app.
Remove exception in migration Some users moved their data folder despite the code not permitting it yet. This migration will fail for those users, but they will still be able to run the app.
Python
mit
OpenBazaar/Network,OpenBazaar/OpenBazaar-Server,tomgalloway/OpenBazaar-Server,saltduck/OpenBazaar-Server,tomgalloway/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,saltduck/OpenBazaar-Server,cpacia/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,OpenBazaar/Network,OpenBazaar/OpenBazaar-Server,saltduck/OpenBazaar-Server,OpenBazaar/Network,cpacia/OpenBazaar-Server,OpenBazaar/OpenBazaar-Server,cpacia/OpenBazaar-Server,tomgalloway/OpenBazaar-Server,tyler-smith/OpenBazaar-Server
import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER not in mapping[1]: raise Exception("To complete migration 2 please run openbazaard at least once using the original " "data folder location before moving it to a different location.") path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close() Remove exception in migration Some users moved their data folder despite the code not permitting it yet. This migration will fail for those users, but they will still be able to run the app.
import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER in mapping[1]: path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close()
<commit_before>import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER not in mapping[1]: raise Exception("To complete migration 2 please run openbazaard at least once using the original " "data folder location before moving it to a different location.") path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close() <commit_msg>Remove exception in migration Some users moved their data folder despite the code not permitting it yet. This migration will fail for those users, but they will still be able to run the app.<commit_after>
import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER in mapping[1]: path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close()
import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER not in mapping[1]: raise Exception("To complete migration 2 please run openbazaard at least once using the original " "data folder location before moving it to a different location.") path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close() Remove exception in migration Some users moved their data folder despite the code not permitting it yet. This migration will fail for those users, but they will still be able to run the app.import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER in mapping[1]: path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close()
<commit_before>import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER not in mapping[1]: raise Exception("To complete migration 2 please run openbazaard at least once using the original " "data folder location before moving it to a different location.") path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close() <commit_msg>Remove exception in migration Some users moved their data folder despite the code not permitting it yet. This migration will fail for those users, but they will still be able to run the app.<commit_after>import sqlite3 from config import DATA_FOLDER def migrate(database_path): print "migrating to db version 2" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # read hashmap from db cursor.execute('''SELECT * FROM hashmap''') mappings = cursor.fetchall() for mapping in mappings: if DATA_FOLDER in mapping[1]: path = mapping[1][len(DATA_FOLDER):] cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath) VALUES (?,?)''', (mapping[0], path)) # update version cursor.execute('''PRAGMA user_version = 2''') conn.commit() conn.close()
c441eee6acd694553e5ed79f4014eef387b9bd9e
s3file/checks.py
s3file/checks.py
from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ]
from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ] return []
Fix deployment check return value
Fix deployment check return value AssertionError: The function <function storage_check at 0x7f8571c1a048> did not return a list. All functions registered with the checks registry must return a list.
Python
mit
codingjoe/django-s3file,codingjoe/django-s3file,codingjoe/django-s3file
from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ] Fix deployment check return value AssertionError: The function <function storage_check at 0x7f8571c1a048> did not return a list. All functions registered with the checks registry must return a list.
from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ] return []
<commit_before>from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ] <commit_msg>Fix deployment check return value AssertionError: The function <function storage_check at 0x7f8571c1a048> did not return a list. All functions registered with the checks registry must return a list.<commit_after>
from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ] return []
from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ] Fix deployment check return value AssertionError: The function <function storage_check at 0x7f8571c1a048> did not return a list. All functions registered with the checks registry must return a list.from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ] return []
<commit_before>from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ] <commit_msg>Fix deployment check return value AssertionError: The function <function storage_check at 0x7f8571c1a048> did not return a list. All functions registered with the checks registry must return a list.<commit_after>from django.core.checks import Error from django.core.files.storage import FileSystemStorage, default_storage def storage_check(app_configs, **kwargs): if isinstance(default_storage, FileSystemStorage): return [ Error( 'FileSystemStorage should not be used in a production environment.', hint='Please verify your DEFAULT_FILE_STORAGE setting.', id='s3file.E001', ) ] return []
bb9116940ffba48a1a930e7c3203bd2d8b8bbb6e
docs/examples/compute/pricing.py
docs/examples/compute/pricing.py
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() >>> sizes[:5] [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None price=0.02 driver=Amazon EC2 ...>, <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None price=0.065 driver=Amazon EC2 ...>, <NodeSize: id=m1.medium, name=Medium Instance, ram=3700 disk=410 bandwidth=None price=0.13 driver=Amazon EC2 ...>, <NodeSize: id=m1.large, name=Large Instance, ram=7680 disk=850 bandwidth=None price=0.26 driver=Amazon EC2 ...>, <NodeSize: id=m1.xlarge, name=Extra Large Instance, ram=15360 disk=1690 bandwidth=None price=0.52 driver=Amazon EC2 ...>] >>> sizes[0].price 0.02 >>>
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() # >>> sizes[:2] # [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None # price=0.02 driver=Amazon EC2 ...>, # <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None # price=0.065 driver=Amazon EC2 ...>, # >>> sizes[0].price # 0.02 # >>>
Fix pep8 violations in the doc examples.
Fix pep8 violations in the doc examples.
Python
apache-2.0
t-tran/libcloud,illfelder/libcloud,ByteInternet/libcloud,mgogoulos/libcloud,Scalr/libcloud,apache/libcloud,erjohnso/libcloud,jimbobhickville/libcloud,erjohnso/libcloud,sahildua2305/libcloud,curoverse/libcloud,sfriesel/libcloud,wrigri/libcloud,Scalr/libcloud,supertom/libcloud,sfriesel/libcloud,StackPointCloud/libcloud,aleGpereira/libcloud,Itxaka/libcloud,Kami/libcloud,briancurtin/libcloud,thesquelched/libcloud,kater169/libcloud,mbrukman/libcloud,jimbobhickville/libcloud,sahildua2305/libcloud,mtekel/libcloud,curoverse/libcloud,wuyuewen/libcloud,mgogoulos/libcloud,smaffulli/libcloud,iPlantCollaborativeOpenSource/libcloud,sergiorua/libcloud,Cloud-Elasticity-Services/as-libcloud,samuelchong/libcloud,schaubl/libcloud,aviweit/libcloud,pantheon-systems/libcloud,mistio/libcloud,aviweit/libcloud,Verizon/libcloud,wuyuewen/libcloud,MrBasset/libcloud,pquentin/libcloud,thesquelched/libcloud,techhat/libcloud,ZuluPro/libcloud,kater169/libcloud,sergiorua/libcloud,SecurityCompass/libcloud,samuelchong/libcloud,briancurtin/libcloud,illfelder/libcloud,Cloud-Elasticity-Services/as-libcloud,watermelo/libcloud,atsaki/libcloud,pquentin/libcloud,SecurityCompass/libcloud,aleGpereira/libcloud,DimensionDataCBUSydney/libcloud,sfriesel/libcloud,sahildua2305/libcloud,Scalr/libcloud,wido/libcloud,kater169/libcloud,mathspace/libcloud,niteoweb/libcloud,watermelo/libcloud,apache/libcloud,techhat/libcloud,munkiat/libcloud,sgammon/libcloud,Verizon/libcloud,thesquelched/libcloud,JamesGuthrie/libcloud,andrewsomething/libcloud,mathspace/libcloud,JamesGuthrie/libcloud,pquentin/libcloud,supertom/libcloud,niteoweb/libcloud,cryptickp/libcloud,curoverse/libcloud,munkiat/libcloud,ZuluPro/libcloud,DimensionDataCBUSydney/libcloud,pantheon-systems/libcloud,apache/libcloud,JamesGuthrie/libcloud,ByteInternet/libcloud,sergiorua/libcloud,samuelchong/libcloud,lochiiconnectivity/libcloud,dcorbacho/libcloud,jerryblakley/libcloud,NexusIS/libcloud,Verizon/libcloud,mtekel/libcloud,watermelo/libcloud,jerryblakley/libcloud,StackPointCloud/libcloud,wuyuewen/libcloud,Itxaka/libcloud,smaffulli/libcloud,Kami/libcloud,Itxaka/libcloud,wrigri/libcloud,cryptickp/libcloud,ByteInternet/libcloud,vongazman/libcloud,supertom/libcloud,illfelder/libcloud,lochiiconnectivity/libcloud,wido/libcloud,vongazman/libcloud,mgogoulos/libcloud,iPlantCollaborativeOpenSource/libcloud,carletes/libcloud,ClusterHQ/libcloud,sgammon/libcloud,Cloud-Elasticity-Services/as-libcloud,marcinzaremba/libcloud,mbrukman/libcloud,andrewsomething/libcloud,t-tran/libcloud,andrewsomething/libcloud,ClusterHQ/libcloud,niteoweb/libcloud,erjohnso/libcloud,atsaki/libcloud,pantheon-systems/libcloud,cloudControl/libcloud,mistio/libcloud,NexusIS/libcloud,jimbobhickville/libcloud,marcinzaremba/libcloud,mbrukman/libcloud,aleGpereira/libcloud,lochiiconnectivity/libcloud,wido/libcloud,cryptickp/libcloud,wrigri/libcloud,atsaki/libcloud,cloudControl/libcloud,schaubl/libcloud,aviweit/libcloud,DimensionDataCBUSydney/libcloud,Kami/libcloud,SecurityCompass/libcloud,iPlantCollaborativeOpenSource/libcloud,cloudControl/libcloud,carletes/libcloud,dcorbacho/libcloud,NexusIS/libcloud,mistio/libcloud,carletes/libcloud,ZuluPro/libcloud,briancurtin/libcloud,mtekel/libcloud,munkiat/libcloud,MrBasset/libcloud,techhat/libcloud,MrBasset/libcloud,StackPointCloud/libcloud,schaubl/libcloud,vongazman/libcloud,jerryblakley/libcloud,t-tran/libcloud,marcinzaremba/libcloud,mathspace/libcloud,smaffulli/libcloud,dcorbacho/libcloud
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() >>> sizes[:5] [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None price=0.02 driver=Amazon EC2 ...>, <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None price=0.065 driver=Amazon EC2 ...>, <NodeSize: id=m1.medium, name=Medium Instance, ram=3700 disk=410 bandwidth=None price=0.13 driver=Amazon EC2 ...>, <NodeSize: id=m1.large, name=Large Instance, ram=7680 disk=850 bandwidth=None price=0.26 driver=Amazon EC2 ...>, <NodeSize: id=m1.xlarge, name=Extra Large Instance, ram=15360 disk=1690 bandwidth=None price=0.52 driver=Amazon EC2 ...>] >>> sizes[0].price 0.02 >>> Fix pep8 violations in the doc examples.
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() # >>> sizes[:2] # [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None # price=0.02 driver=Amazon EC2 ...>, # <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None # price=0.065 driver=Amazon EC2 ...>, # >>> sizes[0].price # 0.02 # >>>
<commit_before>from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() >>> sizes[:5] [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None price=0.02 driver=Amazon EC2 ...>, <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None price=0.065 driver=Amazon EC2 ...>, <NodeSize: id=m1.medium, name=Medium Instance, ram=3700 disk=410 bandwidth=None price=0.13 driver=Amazon EC2 ...>, <NodeSize: id=m1.large, name=Large Instance, ram=7680 disk=850 bandwidth=None price=0.26 driver=Amazon EC2 ...>, <NodeSize: id=m1.xlarge, name=Extra Large Instance, ram=15360 disk=1690 bandwidth=None price=0.52 driver=Amazon EC2 ...>] >>> sizes[0].price 0.02 >>> <commit_msg>Fix pep8 violations in the doc examples.<commit_after>
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() # >>> sizes[:2] # [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None # price=0.02 driver=Amazon EC2 ...>, # <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None # price=0.065 driver=Amazon EC2 ...>, # >>> sizes[0].price # 0.02 # >>>
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() >>> sizes[:5] [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None price=0.02 driver=Amazon EC2 ...>, <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None price=0.065 driver=Amazon EC2 ...>, <NodeSize: id=m1.medium, name=Medium Instance, ram=3700 disk=410 bandwidth=None price=0.13 driver=Amazon EC2 ...>, <NodeSize: id=m1.large, name=Large Instance, ram=7680 disk=850 bandwidth=None price=0.26 driver=Amazon EC2 ...>, <NodeSize: id=m1.xlarge, name=Extra Large Instance, ram=15360 disk=1690 bandwidth=None price=0.52 driver=Amazon EC2 ...>] >>> sizes[0].price 0.02 >>> Fix pep8 violations in the doc examples.from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() # >>> sizes[:2] # [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None # price=0.02 driver=Amazon EC2 ...>, # <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None # price=0.065 driver=Amazon EC2 ...>, # >>> sizes[0].price # 0.02 # >>>
<commit_before>from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() >>> sizes[:5] [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None price=0.02 driver=Amazon EC2 ...>, <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None price=0.065 driver=Amazon EC2 ...>, <NodeSize: id=m1.medium, name=Medium Instance, ram=3700 disk=410 bandwidth=None price=0.13 driver=Amazon EC2 ...>, <NodeSize: id=m1.large, name=Large Instance, ram=7680 disk=850 bandwidth=None price=0.26 driver=Amazon EC2 ...>, <NodeSize: id=m1.xlarge, name=Extra Large Instance, ram=15360 disk=1690 bandwidth=None price=0.52 driver=Amazon EC2 ...>] >>> sizes[0].price 0.02 >>> <commit_msg>Fix pep8 violations in the doc examples.<commit_after>from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver EC2_ACCESS_ID = 'your access id' EC2_SECRET_KEY = 'your secret key' cls = get_driver(Provider.EC2) driver = cls(EC2_ACCESS_ID, EC2_SECRET_KEY) sizes = driver.list_sizes() # >>> sizes[:2] # [<NodeSize: id=t1.micro, name=Micro Instance, ram=613 disk=15 bandwidth=None # price=0.02 driver=Amazon EC2 ...>, # <NodeSize: id=m1.small, name=Small Instance, ram=1740 disk=160 bandwidth=None # price=0.065 driver=Amazon EC2 ...>, # >>> sizes[0].price # 0.02 # >>>
c069142d4d85cf134384d7c245469e961d600f47
project/apps/convention/signals.py
project/apps/convention/signals.py
from django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(instance.name)
from django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(unicode(instance.name))
Add unicode to slug creation
Add unicode to slug creation
Python
bsd-2-clause
dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore-django
from django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(instance.name) Add unicode to slug creation
from django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(unicode(instance.name))
<commit_before>from django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(instance.name) <commit_msg>Add unicode to slug creation<commit_after>
from django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(unicode(instance.name))
from django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(instance.name) Add unicode to slug creationfrom django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(unicode(instance.name))
<commit_before>from django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(instance.name) <commit_msg>Add unicode to slug creation<commit_after>from django.db.models.signals import pre_save from django.dispatch import receiver import logging log = logging.getLogger('apps.convention') from django.utils.text import slugify from .models import ( Contestant, ) @receiver(pre_save, sender=Contestant) def contestant_pre_save(sender, instance, **kwargs): """ Builds the slug; required before the contestant model can be saved. """ instance.slug = slugify(unicode(instance.name))
4f9f23f26d4117763ad179b7de8f2e206d21c13b
server.py
server.py
"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, BucketListApi app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/user/<user_id>/bucketlists/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, \ BucketListApi, UserLogin, UserRegister app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/bucketlists/') api.add_resource(UserLogin, '/auth/login/') api.add_resource(UserRegister, '/auth/register/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
Add Login, Registration, Bucketlists endpoints.
[Feature] Add Login, Registration, Bucketlists endpoints.
Python
mit
andela-akiura/bucketlist
"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, BucketListApi app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/user/<user_id>/bucketlists/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run() [Feature] Add Login, Registration, Bucketlists endpoints.
"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, \ BucketListApi, UserLogin, UserRegister app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/bucketlists/') api.add_resource(UserLogin, '/auth/login/') api.add_resource(UserRegister, '/auth/register/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
<commit_before>"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, BucketListApi app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/user/<user_id>/bucketlists/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run() <commit_msg>[Feature] Add Login, Registration, Bucketlists endpoints.<commit_after>
"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, \ BucketListApi, UserLogin, UserRegister app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/bucketlists/') api.add_resource(UserLogin, '/auth/login/') api.add_resource(UserRegister, '/auth/register/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, BucketListApi app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/user/<user_id>/bucketlists/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run() [Feature] Add Login, Registration, Bucketlists endpoints."""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, \ BucketListApi, UserLogin, UserRegister app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/bucketlists/') api.add_resource(UserLogin, '/auth/login/') api.add_resource(UserRegister, '/auth/register/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
<commit_before>"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, BucketListApi app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/user/<user_id>/bucketlists/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run() <commit_msg>[Feature] Add Login, Registration, Bucketlists endpoints.<commit_after>"""This module runs the api server.""" import os from app import flask_app, db from app.models import User, BucketList, BucketListItem from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.restful import Resource, Api from app.api_v1.resources import TestResource, \ BucketListApi, UserLogin, UserRegister app = flask_app api = Api(app=app, prefix='/api/v1.0') manager = Manager(app) migrate = Migrate(app, db) # add resources api.add_resource(TestResource, '/') api.add_resource(BucketListApi, '/bucketlists/') api.add_resource(UserLogin, '/auth/login/') api.add_resource(UserRegister, '/auth/register/') def make_shell_context(): """Add app, database and models to the shell.""" return dict(app=app, db=db, User=User, BucketList=BucketList, BucketListItem=BucketListItem) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) @manager.command def run_tests(): """Run tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
f22beb7995fb20c477d837c0400b77480e5f1a13
yunity/users/tests/test_model.py
yunity/users/tests/test_model.py
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long)
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
Add test for model representation
Add test for model representation
Python
agpl-3.0
yunity/foodsaving-backend,yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) Add test for model representation
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
<commit_before>from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) <commit_msg>Add test for model representation<commit_after>
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) Add test for model representationfrom django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
<commit_before>from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) <commit_msg>Add test for model representation<commit_after>from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': 'user@example.com', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
ea48f0fbe09fbcce843b6d380743ee65a31aa8f8
app/evolver.py
app/evolver.py
import app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) return words, changes
import app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def rewrite(words, rewrite_rules, to='ipa'): '''Rewrite a list of words according to a list of tuple rules of form (plain, ipa), in direction given by target.''' modified = [] for word in words: for rule in rewrite_rules: if to == 'ipa': word = word.replace(rule[0], rule[1]) elif to == 'plain': word = word.replace(rule[1], rule[0]) modified.append(word) return modified def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' # Apply the given transcription rules words = rewrite(words, rewrite_rules, to='ipa') changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) # Convert back to orthographic representation using the given transcription # rules words = rewrite(words, rewrite_rules, to='plain') return words, changes
Add transcription to and from IPA
Add transcription to and from IPA
Python
mit
kdelwat/LangEvolve,kdelwat/LangEvolve,kdelwat/LangEvolve
import app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) return words, changes Add transcription to and from IPA
import app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def rewrite(words, rewrite_rules, to='ipa'): '''Rewrite a list of words according to a list of tuple rules of form (plain, ipa), in direction given by target.''' modified = [] for word in words: for rule in rewrite_rules: if to == 'ipa': word = word.replace(rule[0], rule[1]) elif to == 'plain': word = word.replace(rule[1], rule[0]) modified.append(word) return modified def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' # Apply the given transcription rules words = rewrite(words, rewrite_rules, to='ipa') changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) # Convert back to orthographic representation using the given transcription # rules words = rewrite(words, rewrite_rules, to='plain') return words, changes
<commit_before>import app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) return words, changes <commit_msg>Add transcription to and from IPA<commit_after>
import app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def rewrite(words, rewrite_rules, to='ipa'): '''Rewrite a list of words according to a list of tuple rules of form (plain, ipa), in direction given by target.''' modified = [] for word in words: for rule in rewrite_rules: if to == 'ipa': word = word.replace(rule[0], rule[1]) elif to == 'plain': word = word.replace(rule[1], rule[0]) modified.append(word) return modified def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' # Apply the given transcription rules words = rewrite(words, rewrite_rules, to='ipa') changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) # Convert back to orthographic representation using the given transcription # rules words = rewrite(words, rewrite_rules, to='plain') return words, changes
import app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) return words, changes Add transcription to and from IPAimport app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def rewrite(words, rewrite_rules, to='ipa'): '''Rewrite a list of words according to a list of tuple rules of form (plain, ipa), in direction given by target.''' modified = [] for word in words: for rule in rewrite_rules: if to == 'ipa': word = word.replace(rule[0], rule[1]) elif to == 'plain': word = word.replace(rule[1], rule[0]) modified.append(word) return modified def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' # Apply the given transcription rules words = rewrite(words, rewrite_rules, to='ipa') changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) # Convert back to orthographic representation using the given transcription # rules words = rewrite(words, rewrite_rules, to='plain') return words, changes
<commit_before>import app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) return words, changes <commit_msg>Add transcription to and from IPA<commit_after>import app.selector as selector import app.applier as applier from app.rules import rules def rule_representation(rule): '''Takes a Rule and returns a list of strings which represent it, in the form [name, target, replacement, environment]''' return [rule.name, rule.target, rule.replacement, rule.environments[0][1]] def rewrite(words, rewrite_rules, to='ipa'): '''Rewrite a list of words according to a list of tuple rules of form (plain, ipa), in direction given by target.''' modified = [] for word in words: for rule in rewrite_rules: if to == 'ipa': word = word.replace(rule[0], rule[1]) elif to == 'plain': word = word.replace(rule[1], rule[0]) modified.append(word) return modified def evolve(words, generations=5, rewrite_rules=[]): '''Evolves the language specified by: words: list [strings] for the given number of generations. One sound change is applied per generation.''' # Apply the given transcription rules words = rewrite(words, rewrite_rules, to='ipa') changes = [] for _ in range(generations): # Try to select a valid rule try: sound_change = selector.select_rule(words, rules) # If there aren't any, finish early by breaking from the loop. except ValueError: break changes.append(rule_representation(sound_change)) print(sound_change) words = applier.apply_rule(words, sound_change) # Convert back to orthographic representation using the given transcription # rules words = rewrite(words, rewrite_rules, to='plain') return words, changes
7c679e019d455564f2f609799b33cab75bc361c8
modules/test.py
modules/test.py
import unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def getFellowPlayers(response): for games in range(10): for players in range(9): print(response["games"][games]["fellowPlayers"][players]["summonerId"])
import unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def winOrLose(championsID, response): wlRatio = 0 kdRatio = 0 gamesWon = 0 gamesLoss = 0 numKills = 0 numDeaths = 0 for games in range(10): if championsID == response["games"][games]["championId"]: numKills += response["games"][games]["stats"]["championsKilled"] numDeaths += (response["games"][games]["stats"]["numDeaths"]) if response["games"][games]["stats"]["win"] == "true": gamesWon += 1 if response["games"][games]["stats"]["win"] == "false": gamesLoss += 1 if gamesLoss > 0: wlRatio = gamesWon/gamesLoss else: wlRatio = gamesWon if numDeaths > 0: kdRatio = numKills/numDeaths else: kdRatio = numKills if gamesWon > 0: print("W/L Ratio: " + wlRatio) else: print("Unable to calculate W/L Ratio") if numKills > 0: print("K/D Ratio: " +kdRatio) else: print("Unable to calculate K/D Ratio")
Check W/L Ratio and K/D Ratio
Check W/L Ratio and K/D Ratio
Python
apache-2.0
Timothylock/league-carnage-notifier-Raspberry-Pi,Timothylock/league-carnage-notifier-Raspberry-Pi
import unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def getFellowPlayers(response): for games in range(10): for players in range(9): print(response["games"][games]["fellowPlayers"][players]["summonerId"]) Check W/L Ratio and K/D Ratio
import unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def winOrLose(championsID, response): wlRatio = 0 kdRatio = 0 gamesWon = 0 gamesLoss = 0 numKills = 0 numDeaths = 0 for games in range(10): if championsID == response["games"][games]["championId"]: numKills += response["games"][games]["stats"]["championsKilled"] numDeaths += (response["games"][games]["stats"]["numDeaths"]) if response["games"][games]["stats"]["win"] == "true": gamesWon += 1 if response["games"][games]["stats"]["win"] == "false": gamesLoss += 1 if gamesLoss > 0: wlRatio = gamesWon/gamesLoss else: wlRatio = gamesWon if numDeaths > 0: kdRatio = numKills/numDeaths else: kdRatio = numKills if gamesWon > 0: print("W/L Ratio: " + wlRatio) else: print("Unable to calculate W/L Ratio") if numKills > 0: print("K/D Ratio: " +kdRatio) else: print("Unable to calculate K/D Ratio")
<commit_before>import unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def getFellowPlayers(response): for games in range(10): for players in range(9): print(response["games"][games]["fellowPlayers"][players]["summonerId"]) <commit_msg>Check W/L Ratio and K/D Ratio<commit_after>
import unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def winOrLose(championsID, response): wlRatio = 0 kdRatio = 0 gamesWon = 0 gamesLoss = 0 numKills = 0 numDeaths = 0 for games in range(10): if championsID == response["games"][games]["championId"]: numKills += response["games"][games]["stats"]["championsKilled"] numDeaths += (response["games"][games]["stats"]["numDeaths"]) if response["games"][games]["stats"]["win"] == "true": gamesWon += 1 if response["games"][games]["stats"]["win"] == "false": gamesLoss += 1 if gamesLoss > 0: wlRatio = gamesWon/gamesLoss else: wlRatio = gamesWon if numDeaths > 0: kdRatio = numKills/numDeaths else: kdRatio = numKills if gamesWon > 0: print("W/L Ratio: " + wlRatio) else: print("Unable to calculate W/L Ratio") if numKills > 0: print("K/D Ratio: " +kdRatio) else: print("Unable to calculate K/D Ratio")
import unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def getFellowPlayers(response): for games in range(10): for players in range(9): print(response["games"][games]["fellowPlayers"][players]["summonerId"]) Check W/L Ratio and K/D Ratioimport unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def winOrLose(championsID, response): wlRatio = 0 kdRatio = 0 gamesWon = 0 gamesLoss = 0 numKills = 0 numDeaths = 0 for games in range(10): if championsID == response["games"][games]["championId"]: numKills += response["games"][games]["stats"]["championsKilled"] numDeaths += (response["games"][games]["stats"]["numDeaths"]) if response["games"][games]["stats"]["win"] == "true": gamesWon += 1 if response["games"][games]["stats"]["win"] == "false": gamesLoss += 1 if gamesLoss > 0: wlRatio = gamesWon/gamesLoss else: wlRatio = gamesWon if numDeaths > 0: kdRatio = numKills/numDeaths else: kdRatio = numKills if gamesWon > 0: print("W/L Ratio: " + wlRatio) else: print("Unable to calculate W/L Ratio") if numKills > 0: print("K/D Ratio: " +kdRatio) else: print("Unable to calculate K/D Ratio")
<commit_before>import unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def getFellowPlayers(response): for games in range(10): for players in range(9): print(response["games"][games]["fellowPlayers"][players]["summonerId"]) <commit_msg>Check W/L Ratio and K/D Ratio<commit_after>import unirest def getTeam(summonerID): response = unirest.get("https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/" + str(summonerID) + "/recent?api_key=4ef4ddb0-44e4-4757-8cd5-6aa9f512a813", headers={ } ) return(response.body) def winOrLose(championsID, response): wlRatio = 0 kdRatio = 0 gamesWon = 0 gamesLoss = 0 numKills = 0 numDeaths = 0 for games in range(10): if championsID == response["games"][games]["championId"]: numKills += response["games"][games]["stats"]["championsKilled"] numDeaths += (response["games"][games]["stats"]["numDeaths"]) if response["games"][games]["stats"]["win"] == "true": gamesWon += 1 if response["games"][games]["stats"]["win"] == "false": gamesLoss += 1 if gamesLoss > 0: wlRatio = gamesWon/gamesLoss else: wlRatio = gamesWon if numDeaths > 0: kdRatio = numKills/numDeaths else: kdRatio = numKills if gamesWon > 0: print("W/L Ratio: " + wlRatio) else: print("Unable to calculate W/L Ratio") if numKills > 0: print("K/D Ratio: " +kdRatio) else: print("Unable to calculate K/D Ratio")
7eed609f1ada212046bf1c5c18084b9a598089d8
addons/purchase/__terp__.py
addons/purchase/__terp__.py
{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml" ], "active": False, "installable": True }
{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml", "purchase_security.xml" ], "active": False, "installable": True }
Add purchase_security.xml file entry in update_xml section
Add purchase_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-231e8ef2a888ac261ce0278ca7f6c387760d8ea3
Python
agpl-3.0
BT-ojossen/odoo,CatsAndDogsbvba/odoo,Danisan/odoo-1,chiragjogi/odoo,nhomar/odoo-mirror,tarzan0820/odoo,klunwebale/odoo,shaufi/odoo,Bachaco-ve/odoo,gvb/odoo,patmcb/odoo,abdellatifkarroum/odoo,Ernesto99/odoo,papouso/odoo,ingadhoc/odoo,camptocamp/ngo-addons-backport,bplancher/odoo,credativUK/OCB,hubsaysnuaa/odoo,addition-it-solutions/project-all,addition-it-solutions/project-all,grap/OpenUpgrade,lgscofield/odoo,takis/odoo,makinacorpus/odoo,Gitlab11/odoo,KontorConsulting/odoo,guewen/OpenUpgrade,jaxkodex/odoo,ubic135/odoo-design,eino-makitalo/odoo,fuselock/odoo,goliveirab/odoo,NL66278/OCB,eino-makitalo/odoo,Kilhog/odoo,bobisme/odoo,minhtuancn/odoo,sv-dev1/odoo,Nowheresly/odoo,alexcuellar/odoo,rahuldhote/odoo,janocat/odoo,mmbtba/odoo,AuyaJackie/odoo,dariemp/odoo,hanicker/odoo,ubic135/odoo-design,jeasoft/odoo,takis/odoo,VitalPet/odoo,cedk/odoo,luiseduardohdbackup/odoo,idncom/odoo,andreparames/odoo,Ichag/odoo,steedos/odoo,rgeleta/odoo,papouso/odoo,0k/OpenUpgrade,matrixise/odoo,shivam1111/odoo,leoliujie/odoo,patmcb/odoo,colinnewell/odoo,rdeheele/odoo,dezynetechnologies/odoo,oasiswork/odoo,nuncjo/odoo,VielSoft/odoo,tangyiyong/odoo,leoliujie/odoo,pedrobaeza/OpenUpgrade,ShineFan/odoo,draugiskisprendimai/odoo,ramadhane/odoo,credativUK/OCB,bealdav/OpenUpgrade,thanhacun/odoo,vnsofthe/odoo,Elico-Corp/odoo_OCB,hip-odoo/odoo,nuncjo/odoo,Nowheresly/odoo,abdellatifkarroum/odoo,christophlsa/odoo,syci/OCB,gavin-feng/odoo,FlorianLudwig/odoo,ovnicraft/odoo,Codefans-fan/odoo,ygol/odoo,bwrsandman/OpenUpgrade,n0m4dz/odoo,demon-ru/iml-crm,bkirui/odoo,mmbtba/odoo,thanhacun/odoo,factorlibre/OCB,VitalPet/odoo,dfang/odoo,rowemoore/odoo,bobisme/odoo,QianBIG/odoo,alexcuellar/odoo,bkirui/odoo,prospwro/odoo,0k/OpenUpgrade,cedk/odoo,dsfsdgsbngfggb/odoo,erkrishna9/odoo,csrocha/OpenUpgrade,acshan/odoo,Nick-OpusVL/odoo,lightcn/odoo,florian-dacosta/OpenUpgrade,savoirfairelinux/OpenUpgrade,javierTerry/odoo,VielSoft/odoo,podemos-info/odoo,charbeljc/OCB,lightcn/odoo,frouty/odoo_oph,abstract-open-solutions/OCB,tinkhaven-organization/odoo,provaleks/o8,doomsterinc/odoo,sergio-incaser/odoo,thanhacun/odoo,nhomar/odoo,gavin-feng/odoo,kirca/OpenUpgrade,minhtuancn/odoo,Daniel-CA/odoo,slevenhagen/odoo-npg,slevenhagen/odoo,BT-ojossen/odoo,microcom/odoo,shingonoide/odoo,wangjun/odoo,GauravSahu/odoo,laslabs/odoo,rubencabrera/odoo,funkring/fdoo,fgesora/odoo,stonegithubs/odoo,oasiswork/odoo,jiangzhixiao/odoo,jiangzhixiao/odoo,nexiles/odoo,VielSoft/odoo,hbrunn/OpenUpgrade,CatsAndDogsbvba/odoo,alexteodor/odoo,sebalix/OpenUpgrade,lombritz/odoo,markeTIC/OCB,arthru/OpenUpgrade,hubsaysnuaa/odoo,abenzbiria/clients_odoo,provaleks/o8,savoirfairelinux/odoo,ccomb/OpenUpgrade,leorochael/odoo,charbeljc/OCB,bobisme/odoo,mustafat/odoo-1,gavin-feng/odoo,MarcosCommunity/odoo,RafaelTorrealba/odoo,dezynetechnologies/odoo,simongoffin/website_version,savoirfairelinux/odoo,srimai/odoo,OpusVL/odoo,Nowheresly/odoo,podemos-info/odoo,CatsAndDogsbvba/odoo,nagyistoce/odoo-dev-odoo,ojengwa/odoo,glovebx/odoo,minhtuancn/odoo,ovnicraft/odoo,VielSoft/odoo,papouso/odoo,Maspear/odoo,nhomar/odoo,shaufi/odoo,alhashash/odoo,fjbatresv/odoo,Codefans-fan/odoo,alhashash/odoo,dezynetechnologies/odoo,ClearCorp-dev/odoo,abenzbiria/clients_odoo,markeTIC/OCB,rdeheele/odoo,nhomar/odoo,bplancher/odoo,glovebx/odoo,stonegithubs/odoo,jpshort/odoo,shaufi/odoo,hmen89/odoo,Endika/OpenUpgrade,andreparames/odoo,sebalix/OpenUpgrade,vrenaville/ngo-addons-backport,optima-ict/odoo,massot/odoo,stonegithubs/odoo,collex100/odoo,guewen/OpenUpgrade,FlorianLudwig/odoo,nuuuboo/odoo,javierTerry/odoo,brijeshkesariya/odoo,juanalfonsopr/odoo,mlaitinen/odoo,salaria/odoo,BT-astauder/odoo,OpenUpgrade/OpenUpgrade,abenzbiria/clients_odoo,funkring/fdoo,vrenaville/ngo-addons-backport,leorochael/odoo,srsman/odoo,bguillot/OpenUpgrade,Bachaco-ve/odoo,lombritz/odoo,doomsterinc/odoo,provaleks/o8,acshan/odoo,shaufi/odoo,0k/OpenUpgrade,dfang/odoo,osvalr/odoo,ygol/odoo,Eric-Zhong/odoo,ihsanudin/odoo,ihsanudin/odoo,markeTIC/OCB,OpenUpgrade/OpenUpgrade,xzYue/odoo,pedrobaeza/OpenUpgrade,frouty/odoogoeen,massot/odoo,CopeX/odoo,ygol/odoo,Eric-Zhong/odoo,naousse/odoo,salaria/odoo,tarzan0820/odoo,BT-rmartin/odoo,BT-astauder/odoo,Bachaco-ve/odoo,Ernesto99/odoo,dsfsdgsbngfggb/odoo,cloud9UG/odoo,MarcosCommunity/odoo,damdam-s/OpenUpgrade,lsinfo/odoo,Ichag/odoo,storm-computers/odoo,fuselock/odoo,tvtsoft/odoo8,steedos/odoo,storm-computers/odoo,ujjwalwahi/odoo,csrocha/OpenUpgrade,christophlsa/odoo,Gitlab11/odoo,omprakasha/odoo,bealdav/OpenUpgrade,FlorianLudwig/odoo,mmbtba/odoo,blaggacao/OpenUpgrade,xujb/odoo,Bachaco-ve/odoo,patmcb/odoo,dgzurita/odoo,joshuajan/odoo,javierTerry/odoo,patmcb/odoo,bakhtout/odoo-educ,elmerdpadilla/iv,MarcosCommunity/odoo,dalegregory/odoo,BT-fgarbely/odoo,diagramsoftware/odoo,NeovaHealth/odoo,deKupini/erp,Endika/OpenUpgrade,x111ong/odoo,pedrobaeza/odoo,nitinitprof/odoo,zchking/odoo,aviciimaxwell/odoo,hoatle/odoo,NeovaHealth/odoo,sinbazhou/odoo,numerigraphe/odoo,joshuajan/odoo,kybriainfotech/iSocioCRM,dkubiak789/odoo,sebalix/OpenUpgrade,BT-ojossen/odoo,shingonoide/odoo,sve-odoo/odoo,jolevq/odoopub,kybriainfotech/iSocioCRM,Eric-Zhong/odoo,dfang/odoo,sv-dev1/odoo,syci/OCB,NL66278/OCB,shaufi10/odoo,makinacorpus/odoo,nuuuboo/odoo,virgree/odoo,havt/odoo,lightcn/odoo,FlorianLudwig/odoo,simongoffin/website_version,CopeX/odoo,stephen144/odoo,fevxie/odoo,poljeff/odoo,ramitalat/odoo,osvalr/odoo,vrenaville/ngo-addons-backport,dezynetechnologies/odoo,luiseduardohdbackup/odoo,srsman/odoo,jiangzhixiao/odoo,ThinkOpen-Solutions/odoo,BT-rmartin/odoo,OpenPymeMx/OCB,Endika/odoo,fossoult/odoo,lsinfo/odoo,apanju/GMIO_Odoo,gvb/odoo,podemos-info/odoo,JonathanStein/odoo,TRESCLOUD/odoopub,lightcn/odoo,makinacorpus/odoo,alexteodor/odoo,NeovaHealth/odoo,tvibliani/odoo,BT-fgarbely/odoo,janocat/odoo,hifly/OpenUpgrade,Antiun/odoo,Kilhog/odoo,dalegregory/odoo,incaser/odoo-odoo,ihsanudin/odoo,tinkhaven-organization/odoo,JGarcia-Panach/odoo,incaser/odoo-odoo,goliveirab/odoo,ovnicraft/odoo,sinbazhou/odoo,bwrsandman/OpenUpgrade,cloud9UG/odoo,charbeljc/OCB,microcom/odoo,ehirt/odoo,RafaelTorrealba/odoo,frouty/odoo_oph,wangjun/odoo,demon-ru/iml-crm,rschnapka/odoo,fuhongliang/odoo,jusdng/odoo,ingadhoc/odoo,hassoon3/odoo,0k/OpenUpgrade,ujjwalwahi/odoo,Danisan/odoo-1,AuyaJackie/odoo,gavin-feng/odoo,csrocha/OpenUpgrade,ehirt/odoo,draugiskisprendimai/odoo,draugiskisprendimai/odoo,ClearCorp-dev/odoo,tarzan0820/odoo,BT-astauder/odoo,sinbazhou/odoo,OpenPymeMx/OCB,cedk/odoo,leorochael/odoo,ramadhane/odoo,sinbazhou/odoo,grap/OCB,leoliujie/odoo,JCA-Developpement/Odoo,joariasl/odoo,xzYue/odoo,alexcuellar/odoo,podemos-info/odoo,jeasoft/odoo,NeovaHealth/odoo,syci/OCB,tarzan0820/odoo,rahuldhote/odoo,osvalr/odoo,feroda/odoo,Gitlab11/odoo,shaufi/odoo,naousse/odoo,nagyistoce/odoo-dev-odoo,x111ong/odoo,VitalPet/odoo,leorochael/odoo,Kilhog/odoo,nuncjo/odoo,thanhacun/odoo,joshuajan/odoo,bguillot/OpenUpgrade,realsaiko/odoo,synconics/odoo,MarcosCommunity/odoo,joariasl/odoo,Eric-Zhong/odoo,avoinsystems/odoo,guerrerocarlos/odoo,bguillot/OpenUpgrade,blaggacao/OpenUpgrade,Endika/OpenUpgrade,numerigraphe/odoo,naousse/odoo,ramitalat/odoo,blaggacao/OpenUpgrade,Endika/OpenUpgrade,mustafat/odoo-1,havt/odoo,dariemp/odoo,kittiu/odoo,ShineFan/odoo,Codefans-fan/odoo,wangjun/odoo,tinkhaven-organization/odoo,BT-fgarbely/odoo,gavin-feng/odoo,OpusVL/odoo,gdgellatly/OCB1,alhashash/odoo,cloud9UG/odoo,collex100/odoo,sv-dev1/odoo,shaufi/odoo,leorochael/odoo,odootr/odoo,dalegregory/odoo,christophlsa/odoo,ingadhoc/odoo,JGarcia-Panach/odoo,bobisme/odoo,prospwro/odoo,highco-groupe/odoo,zchking/odoo,OpenPymeMx/OCB,Maspear/odoo,MarcosCommunity/odoo,rgeleta/odoo,papouso/odoo,virgree/odoo,funkring/fdoo,chiragjogi/odoo,ClearCorp-dev/odoo,prospwro/odoo,datenbetrieb/odoo,apocalypsebg/odoo,leoliujie/odoo,CatsAndDogsbvba/odoo,hifly/OpenUpgrade,oasiswork/odoo,BT-fgarbely/odoo,lsinfo/odoo,Ichag/odoo,spadae22/odoo,dllsf/odootest,tvtsoft/odoo8,FlorianLudwig/odoo,lgscofield/odoo,collex100/odoo,bguillot/OpenUpgrade,Nick-OpusVL/odoo,omprakasha/odoo,mlaitinen/odoo,guerrerocarlos/odoo,havt/odoo,hifly/OpenUpgrade,idncom/odoo,patmcb/odoo,glovebx/odoo,fevxie/odoo,jeasoft/odoo,microcom/odoo,alqfahad/odoo,RafaelTorrealba/odoo,cysnake4713/odoo,Maspear/odoo,erkrishna9/odoo,grap/OpenUpgrade,abenzbiria/clients_odoo,podemos-info/odoo,vrenaville/ngo-addons-backport,OpusVL/odoo,odoo-turkiye/odoo,sergio-incaser/odoo,ehirt/odoo,rdeheele/odoo,dfang/odoo,bwrsandman/OpenUpgrade,storm-computers/odoo,BT-astauder/odoo,gorjuce/odoo,AuyaJackie/odoo,Codefans-fan/odoo,gorjuce/odoo,tangyiyong/odoo,0k/odoo,jusdng/odoo,jusdng/odoo,fuselock/odoo,avoinsystems/odoo,SAM-IT-SA/odoo,rgeleta/odoo,papouso/odoo,nagyistoce/odoo-dev-odoo,agrista/odoo-saas,nhomar/odoo-mirror,slevenhagen/odoo,odoousers2014/odoo,collex100/odoo,ThinkOpen-Solutions/odoo,jfpla/odoo,massot/odoo,shingonoide/odoo,Ichag/odoo,ygol/odoo,QianBIG/odoo,mlaitinen/odoo,ehirt/odoo,ShineFan/odoo,GauravSahu/odoo,alqfahad/odoo,bwrsandman/OpenUpgrade,Bachaco-ve/odoo,markeTIC/OCB,abstract-open-solutions/OCB,xujb/odoo,Endika/odoo,Endika/odoo,ecosoft-odoo/odoo,idncom/odoo,lgscofield/odoo,BT-ojossen/odoo,rubencabrera/odoo,omprakasha/odoo,slevenhagen/odoo,fevxie/odoo,tangyiyong/odoo,microcom/odoo,aviciimaxwell/odoo,guerrerocarlos/odoo,aviciimaxwell/odoo,RafaelTorrealba/odoo,agrista/odoo-saas,fjbatresv/odoo,Nick-OpusVL/odoo,factorlibre/OCB,poljeff/odoo,cpyou/odoo,dgzurita/odoo,lombritz/odoo,frouty/odoogoeen,shaufi10/odoo,highco-groupe/odoo,jpshort/odoo,tarzan0820/odoo,havt/odoo,tvibliani/odoo,shivam1111/odoo,sinbazhou/odoo,sadleader/odoo,provaleks/o8,datenbetrieb/odoo,grap/OpenUpgrade,klunwebale/odoo,codekaki/odoo,spadae22/odoo,kirca/OpenUpgrade,damdam-s/OpenUpgrade,sysadminmatmoz/OCB,stephen144/odoo,ygol/odoo,jpshort/odoo,nexiles/odoo,ClearCorp-dev/odoo,kittiu/odoo,tvibliani/odoo,ingadhoc/odoo,windedge/odoo,abstract-open-solutions/OCB,hassoon3/odoo,Antiun/odoo,osvalr/odoo,JonathanStein/odoo,FlorianLudwig/odoo,nhomar/odoo-mirror,JCA-Developpement/Odoo,dkubiak789/odoo,fuselock/odoo,charbeljc/OCB,Ernesto99/odoo,hanicker/odoo,storm-computers/odoo,oihane/odoo,ramadhane/odoo,brijeshkesariya/odoo,mmbtba/odoo,ecosoft-odoo/odoo,abdellatifkarroum/odoo,nexiles/odoo,dkubiak789/odoo,Codefans-fan/odoo,tangyiyong/odoo,agrista/odoo-saas,grap/OpenUpgrade,glovebx/odoo,dariemp/odoo,hifly/OpenUpgrade,ihsanudin/odoo,glovebx/odoo,dkubiak789/odoo,charbeljc/OCB,JGarcia-Panach/odoo,florentx/OpenUpgrade,Elico-Corp/odoo_OCB,GauravSahu/odoo,agrista/odoo-saas,elmerdpadilla/iv,virgree/odoo,mvaled/OpenUpgrade,sysadminmatmoz/OCB,cysnake4713/odoo,markeTIC/OCB,gdgellatly/OCB1,ecosoft-odoo/odoo,hmen89/odoo,makinacorpus/odoo,xzYue/odoo,VitalPet/odoo,brijeshkesariya/odoo,mkieszek/odoo,rgeleta/odoo,Endika/OpenUpgrade,TRESCLOUD/odoopub,ccomb/OpenUpgrade,vrenaville/ngo-addons-backport,blaggacao/OpenUpgrade,zchking/odoo,grap/OCB,alqfahad/odoo,OpenUpgrade-dev/OpenUpgrade,leoliujie/odoo,ovnicraft/odoo,ubic135/odoo-design,Daniel-CA/odoo,codekaki/odoo,SAM-IT-SA/odoo,nuncjo/odoo,shaufi10/odoo,leorochael/odoo,inspyration/odoo,Gitlab11/odoo,oasiswork/odoo,pedrobaeza/OpenUpgrade,jesramirez/odoo,eino-makitalo/odoo,florian-dacosta/OpenUpgrade,CopeX/odoo,slevenhagen/odoo-npg,diagramsoftware/odoo,fuhongliang/odoo,minhtuancn/odoo,havt/odoo,ramitalat/odoo,alexcuellar/odoo,dezynetechnologies/odoo,mustafat/odoo-1,kybriainfotech/iSocioCRM,dgzurita/odoo,colinnewell/odoo,charbeljc/OCB,jolevq/odoopub,oihane/odoo,collex100/odoo,florian-dacosta/OpenUpgrade,gavin-feng/odoo,credativUK/OCB,ClearCorp-dev/odoo,blaggacao/OpenUpgrade,Bachaco-ve/odoo,GauravSahu/odoo,xujb/odoo,rgeleta/odoo,srimai/odoo,VitalPet/odoo,apocalypsebg/odoo,bakhtout/odoo-educ,savoirfairelinux/odoo,florentx/OpenUpgrade,nexiles/odoo,VitalPet/odoo,savoirfairelinux/odoo,apanju/odoo,lightcn/odoo,ihsanudin/odoo,massot/odoo,rowemoore/odoo,cloud9UG/odoo,sysadminmatmoz/OCB,odootr/odoo,slevenhagen/odoo-npg,CubicERP/odoo,kittiu/odoo,incaser/odoo-odoo,srsman/odoo,collex100/odoo,apanju/GMIO_Odoo,NL66278/OCB,sv-dev1/odoo,salaria/odoo,Nowheresly/odoo,AuyaJackie/odoo,stonegithubs/odoo,apanju/GMIO_Odoo,dariemp/odoo,hbrunn/OpenUpgrade,bakhtout/odoo-educ,luistorresm/odoo,chiragjogi/odoo,jolevq/odoopub,dalegregory/odoo,goliveirab/odoo,realsaiko/odoo,OpenUpgrade/OpenUpgrade,Eric-Zhong/odoo,PongPi/isl-odoo,codekaki/odoo,PongPi/isl-odoo,laslabs/odoo,acshan/odoo,savoirfairelinux/OpenUpgrade,OpenPymeMx/OCB,osvalr/odoo,ThinkOpen-Solutions/odoo,OpenPymeMx/OCB,apanju/GMIO_Odoo,fjbatresv/odoo,rahuldhote/odoo,dgzurita/odoo,frouty/odoo_oph,cpyou/odoo,deKupini/erp,CubicERP/odoo,odooindia/odoo,damdam-s/OpenUpgrade,colinnewell/odoo,Eric-Zhong/odoo,rowemoore/odoo,idncom/odoo,shingonoide/odoo,ubic135/odoo-design,jeasoft/odoo,juanalfonsopr/odoo,dalegregory/odoo,srsman/odoo,xzYue/odoo,CubicERP/odoo,glovebx/odoo,nuuuboo/odoo,zchking/odoo,janocat/odoo,simongoffin/website_version,incaser/odoo-odoo,hmen89/odoo,hbrunn/OpenUpgrade,odoousers2014/odoo,rahuldhote/odoo,sebalix/OpenUpgrade,klunwebale/odoo,ramadhane/odoo,Danisan/odoo-1,collex100/odoo,CatsAndDogsbvba/odoo,KontorConsulting/odoo,nexiles/odoo,SerpentCS/odoo,dsfsdgsbngfggb/odoo,Ernesto99/odoo,OpenUpgrade-dev/OpenUpgrade,nexiles/odoo,slevenhagen/odoo,savoirfairelinux/odoo,idncom/odoo,funkring/fdoo,bkirui/odoo,ThinkOpen-Solutions/odoo,ChanduERP/odoo,factorlibre/OCB,Nick-OpusVL/odoo,Antiun/odoo,sadleader/odoo,OpenUpgrade/OpenUpgrade,numerigraphe/odoo,PongPi/isl-odoo,windedge/odoo,oliverhr/odoo,ehirt/odoo,sinbazhou/odoo,Ernesto99/odoo,bakhtout/odoo-educ,ujjwalwahi/odoo,kybriainfotech/iSocioCRM,ThinkOpen-Solutions/odoo,apocalypsebg/odoo,laslabs/odoo,dfang/odoo,mszewczy/odoo,feroda/odoo,mvaled/OpenUpgrade,credativUK/OCB,tinkerthaler/odoo,bplancher/odoo,waytai/odoo,cedk/odoo,alexteodor/odoo,BT-fgarbely/odoo,luistorresm/odoo,abdellatifkarroum/odoo,lombritz/odoo,hassoon3/odoo,stonegithubs/odoo,savoirfairelinux/OpenUpgrade,ecosoft-odoo/odoo,gorjuce/odoo,NeovaHealth/odoo,matrixise/odoo,hubsaysnuaa/odoo,nitinitprof/odoo,bakhtout/odoo-educ,alexcuellar/odoo,janocat/odoo,Kilhog/odoo,dkubiak789/odoo,slevenhagen/odoo-npg,Drooids/odoo,jiachenning/odoo,javierTerry/odoo,OpenPymeMx/OCB,wangjun/odoo,dgzurita/odoo,bwrsandman/OpenUpgrade,Noviat/odoo,synconics/odoo,abenzbiria/clients_odoo,srsman/odoo,QianBIG/odoo,ApuliaSoftware/odoo,bguillot/OpenUpgrade,OSSESAC/odoopubarquiluz,deKupini/erp,odootr/odoo,rubencabrera/odoo,dkubiak789/odoo,jfpla/odoo,JGarcia-Panach/odoo,lgscofield/odoo,mmbtba/odoo,datenbetrieb/odoo,OpenUpgrade-dev/OpenUpgrade,simongoffin/website_version,mustafat/odoo-1,cloud9UG/odoo,srimai/odoo,fevxie/odoo,hoatle/odoo,SAM-IT-SA/odoo,fevxie/odoo,waytai/odoo,joariasl/odoo,camptocamp/ngo-addons-backport,rubencabrera/odoo,tinkerthaler/odoo,frouty/odoogoeen,bplancher/odoo,mszewczy/odoo,oliverhr/odoo,JCA-Developpement/Odoo,rubencabrera/odoo,NL66278/OCB,Maspear/odoo,fgesora/odoo,simongoffin/website_version,Drooids/odoo,vrenaville/ngo-addons-backport,kifcaliph/odoo,OpusVL/odoo,slevenhagen/odoo,osvalr/odoo,apanju/GMIO_Odoo,gorjuce/odoo,gsmartway/odoo,stephen144/odoo,CubicERP/odoo,demon-ru/iml-crm,deKupini/erp,demon-ru/iml-crm,Danisan/odoo-1,poljeff/odoo,ujjwalwahi/odoo,janocat/odoo,MarcosCommunity/odoo,podemos-info/odoo,ecosoft-odoo/odoo,ojengwa/odoo,srimai/odoo,gsmartway/odoo,lsinfo/odoo,credativUK/OCB,gdgellatly/OCB1,steedos/odoo,bakhtout/odoo-educ,rschnapka/odoo,KontorConsulting/odoo,jiachenning/odoo,charbeljc/OCB,rowemoore/odoo,rschnapka/odoo,chiragjogi/odoo,dllsf/odootest,jusdng/odoo,lightcn/odoo,windedge/odoo,jeasoft/odoo,addition-it-solutions/project-all,hmen89/odoo,SAM-IT-SA/odoo,shivam1111/odoo,gdgellatly/OCB1,Antiun/odoo,nuncjo/odoo,inspyration/odoo,fossoult/odoo,storm-computers/odoo,ingadhoc/odoo,Daniel-CA/odoo,Danisan/odoo-1,waytai/odoo,chiragjogi/odoo,waytai/odoo,BT-rmartin/odoo,Grirrane/odoo,idncom/odoo,jpshort/odoo,mkieszek/odoo,cloud9UG/odoo,mlaitinen/odoo,lsinfo/odoo,Grirrane/odoo,oliverhr/odoo,mszewczy/odoo,bkirui/odoo,ShineFan/odoo,camptocamp/ngo-addons-backport,hanicker/odoo,SAM-IT-SA/odoo,Endika/odoo,ChanduERP/odoo,Grirrane/odoo,fgesora/odoo,shaufi/odoo,leoliujie/odoo,ccomb/OpenUpgrade,hopeall/odoo,feroda/odoo,luiseduardohdbackup/odoo,bealdav/OpenUpgrade,tarzan0820/odoo,fuselock/odoo,credativUK/OCB,sve-odoo/odoo,Maspear/odoo,savoirfairelinux/OpenUpgrade,stephen144/odoo,ccomb/OpenUpgrade,datenbetrieb/odoo,xzYue/odoo,sysadminmatmoz/OCB,datenbetrieb/odoo,ovnicraft/odoo,naousse/odoo,odootr/odoo,ThinkOpen-Solutions/odoo,ojengwa/odoo,rowemoore/odoo,hubsaysnuaa/odoo,kifcaliph/odoo,ojengwa/odoo,sadleader/odoo,x111ong/odoo,Danisan/odoo-1,alexteodor/odoo,sv-dev1/odoo,tinkhaven-organization/odoo,Noviat/odoo,feroda/odoo,ecosoft-odoo/odoo,nitinitprof/odoo,wangjun/odoo,n0m4dz/odoo,joariasl/odoo,Noviat/odoo,alqfahad/odoo,provaleks/o8,jaxkodex/odoo,hopeall/odoo,syci/OCB,odooindia/odoo,gdgellatly/OCB1,ramadhane/odoo,fevxie/odoo,camptocamp/ngo-addons-backport,lgscofield/odoo,tangyiyong/odoo,windedge/odoo,OSSESAC/odoopubarquiluz,QianBIG/odoo,Antiun/odoo,ihsanudin/odoo,jaxkodex/odoo,vnsofthe/odoo,grap/OCB,BT-ojossen/odoo,srsman/odoo,highco-groupe/odoo,fuhongliang/odoo,ramitalat/odoo,guewen/OpenUpgrade,srimai/odoo,gorjuce/odoo,arthru/OpenUpgrade,dezynetechnologies/odoo,gvb/odoo,OpenUpgrade-dev/OpenUpgrade,OSSESAC/odoopubarquiluz,highco-groupe/odoo,hassoon3/odoo,savoirfairelinux/OpenUpgrade,lsinfo/odoo,poljeff/odoo,BT-fgarbely/odoo,csrocha/OpenUpgrade,mkieszek/odoo,addition-it-solutions/project-all,tvtsoft/odoo8,ecosoft-odoo/odoo,slevenhagen/odoo-npg,bobisme/odoo,sv-dev1/odoo,fdvarela/odoo8,lgscofield/odoo,Ernesto99/odoo,ramadhane/odoo,sinbazhou/odoo,ApuliaSoftware/odoo,BT-rmartin/odoo,jesramirez/odoo,VielSoft/odoo,pedrobaeza/odoo,mszewczy/odoo,Gitlab11/odoo,oasiswork/odoo,shingonoide/odoo,tvtsoft/odoo8,papouso/odoo,goliveirab/odoo,jesramirez/odoo,rschnapka/odoo,Adel-Magebinary/odoo,lombritz/odoo,apocalypsebg/odoo,tvibliani/odoo,demon-ru/iml-crm,apanju/GMIO_Odoo,apanju/odoo,ehirt/odoo,joshuajan/odoo,ujjwalwahi/odoo,alexcuellar/odoo,joshuajan/odoo,ujjwalwahi/odoo,fjbatresv/odoo,cedk/odoo,kirca/OpenUpgrade,diagramsoftware/odoo,optima-ict/odoo,hip-odoo/odoo,fdvarela/odoo8,doomsterinc/odoo,odootr/odoo,gorjuce/odoo,brijeshkesariya/odoo,brijeshkesariya/odoo,gsmartway/odoo,OpenUpgrade/OpenUpgrade,odoo-turkiye/odoo,Adel-Magebinary/odoo,christophlsa/odoo,lsinfo/odoo,mustafat/odoo-1,gvb/odoo,oihane/odoo,bplancher/odoo,feroda/odoo,hassoon3/odoo,VitalPet/odoo,hassoon3/odoo,kirca/OpenUpgrade,salaria/odoo,realsaiko/odoo,JonathanStein/odoo,luiseduardohdbackup/odoo,lombritz/odoo,xzYue/odoo,spadae22/odoo,datenbetrieb/odoo,naousse/odoo,dsfsdgsbngfggb/odoo,naousse/odoo,fgesora/odoo,diagramsoftware/odoo,KontorConsulting/odoo,kittiu/odoo,ApuliaSoftware/odoo,juanalfonsopr/odoo,massot/odoo,goliveirab/odoo,BT-ojossen/odoo,grap/OpenUpgrade,abdellatifkarroum/odoo,Endika/odoo,shaufi10/odoo,havt/odoo,pplatek/odoo,Daniel-CA/odoo,hifly/OpenUpgrade,x111ong/odoo,steedos/odoo,luiseduardohdbackup/odoo,realsaiko/odoo,kifcaliph/odoo,kifcaliph/odoo,nitinitprof/odoo,hip-odoo/odoo,nuuuboo/odoo,damdam-s/OpenUpgrade,papouso/odoo,salaria/odoo,mmbtba/odoo,Danisan/odoo-1,hubsaysnuaa/odoo,apanju/odoo,Noviat/odoo,x111ong/odoo,0k/OpenUpgrade,SAM-IT-SA/odoo,cedk/odoo,factorlibre/OCB,kybriainfotech/iSocioCRM,florian-dacosta/OpenUpgrade,KontorConsulting/odoo,joariasl/odoo,apanju/odoo,virgree/odoo,jfpla/odoo,dfang/odoo,jesramirez/odoo,doomsterinc/odoo,jpshort/odoo,optima-ict/odoo,chiragjogi/odoo,abdellatifkarroum/odoo,ccomb/OpenUpgrade,odoo-turkiye/odoo,sve-odoo/odoo,grap/OCB,odooindia/odoo,kirca/OpenUpgrade,pplatek/odoo,kittiu/odoo,Nowheresly/odoo,luistorresm/odoo,sadleader/odoo,pedrobaeza/OpenUpgrade,Endika/OpenUpgrade,tangyiyong/odoo,grap/OCB,OSSESAC/odoopubarquiluz,abstract-open-solutions/OCB,tinkhaven-organization/odoo,tarzan0820/odoo,hoatle/odoo,Noviat/odoo,CopeX/odoo,synconics/odoo,rschnapka/odoo,SerpentCS/odoo,alhashash/odoo,sebalix/OpenUpgrade,christophlsa/odoo,Maspear/odoo,luistorresm/odoo,Ichag/odoo,alqfahad/odoo,gorjuce/odoo,highco-groupe/odoo,jiachenning/odoo,guerrerocarlos/odoo,arthru/OpenUpgrade,Adel-Magebinary/odoo,incaser/odoo-odoo,codekaki/odoo,waytai/odoo,rubencabrera/odoo,vnsofthe/odoo,bealdav/OpenUpgrade,optima-ict/odoo,xujb/odoo,ramitalat/odoo,hifly/OpenUpgrade,poljeff/odoo,nitinitprof/odoo,javierTerry/odoo,hoatle/odoo,gsmartway/odoo,kittiu/odoo,cpyou/odoo,doomsterinc/odoo,makinacorpus/odoo,syci/OCB,jeasoft/odoo,tinkhaven-organization/odoo,cpyou/odoo,thanhacun/odoo,odoousers2014/odoo,bkirui/odoo,Grirrane/odoo,Antiun/odoo,frouty/odoogoeen,hubsaysnuaa/odoo,eino-makitalo/odoo,jaxkodex/odoo,optima-ict/odoo,fdvarela/odoo8,patmcb/odoo,florian-dacosta/OpenUpgrade,Elico-Corp/odoo_OCB,luistorresm/odoo,luiseduardohdbackup/odoo,JonathanStein/odoo,markeTIC/OCB,hanicker/odoo,AuyaJackie/odoo,MarcosCommunity/odoo,shivam1111/odoo,bobisme/odoo,hbrunn/OpenUpgrade,synconics/odoo,abstract-open-solutions/OCB,andreparames/odoo,steedos/odoo,bobisme/odoo,bguillot/OpenUpgrade,cpyou/odoo,tvtsoft/odoo8,virgree/odoo,javierTerry/odoo,cloud9UG/odoo,matrixise/odoo,Drooids/odoo,odoousers2014/odoo,prospwro/odoo,funkring/fdoo,mvaled/OpenUpgrade,odoousers2014/odoo,BT-astauder/odoo,matrixise/odoo,guerrerocarlos/odoo,ramitalat/odoo,avoinsystems/odoo,JGarcia-Panach/odoo,florentx/OpenUpgrade,Eric-Zhong/odoo,jpshort/odoo,draugiskisprendimai/odoo,kirca/OpenUpgrade,xujb/odoo,javierTerry/odoo,shivam1111/odoo,Ichag/odoo,pedrobaeza/odoo,klunwebale/odoo,cdrooom/odoo,fuhongliang/odoo,RafaelTorrealba/odoo,jaxkodex/odoo,pplatek/odoo,fdvarela/odoo8,Drooids/odoo,hip-odoo/odoo,ovnicraft/odoo,pedrobaeza/OpenUpgrade,fuhongliang/odoo,zchking/odoo,nagyistoce/odoo-dev-odoo,erkrishna9/odoo,nitinitprof/odoo,juanalfonsopr/odoo,optima-ict/odoo,frouty/odoo_oph,BT-rmartin/odoo,makinacorpus/odoo,waytai/odoo,kittiu/odoo,colinnewell/odoo,nuuuboo/odoo,bealdav/OpenUpgrade,sysadminmatmoz/OCB,mlaitinen/odoo,Adel-Magebinary/odoo,csrocha/OpenUpgrade,SerpentCS/odoo,Nowheresly/odoo,minhtuancn/odoo,apanju/GMIO_Odoo,omprakasha/odoo,gdgellatly/OCB1,ingadhoc/odoo,odooindia/odoo,lgscofield/odoo,oihane/odoo,gvb/odoo,oihane/odoo,vnsofthe/odoo,omprakasha/odoo,JonathanStein/odoo,xujb/odoo,CubicERP/odoo,Kilhog/odoo,sadleader/odoo,jusdng/odoo,mvaled/OpenUpgrade,cdrooom/odoo,cysnake4713/odoo,JCA-Developpement/Odoo,QianBIG/odoo,jiachenning/odoo,abstract-open-solutions/OCB,damdam-s/OpenUpgrade,RafaelTorrealba/odoo,jiangzhixiao/odoo,alqfahad/odoo,BT-ojossen/odoo,laslabs/odoo,oliverhr/odoo,doomsterinc/odoo,srimai/odoo,tinkerthaler/odoo,Drooids/odoo,ApuliaSoftware/odoo,zchking/odoo,jiachenning/odoo,nitinitprof/odoo,poljeff/odoo,ChanduERP/odoo,ubic135/odoo-design,ygol/odoo,dsfsdgsbngfggb/odoo,dalegregory/odoo,synconics/odoo,Adel-Magebinary/odoo,Endika/OpenUpgrade,dllsf/odootest,PongPi/isl-odoo,rahuldhote/odoo,vrenaville/ngo-addons-backport,nhomar/odoo,Gitlab11/odoo,cedk/odoo,brijeshkesariya/odoo,gsmartway/odoo,erkrishna9/odoo,takis/odoo,provaleks/o8,arthru/OpenUpgrade,slevenhagen/odoo-npg,tinkerthaler/odoo,fgesora/odoo,synconics/odoo,Ichag/odoo,ramadhane/odoo,dalegregory/odoo,sv-dev1/odoo,vnsofthe/odoo,kirca/OpenUpgrade,ihsanudin/odoo,florentx/OpenUpgrade,BT-rmartin/odoo,storm-computers/odoo,oliverhr/odoo,oliverhr/odoo,doomsterinc/odoo,glovebx/odoo,apocalypsebg/odoo,microcom/odoo,mkieszek/odoo,joshuajan/odoo,ehirt/odoo,Codefans-fan/odoo,ygol/odoo,minhtuancn/odoo,camptocamp/ngo-addons-backport,VielSoft/odoo,leorochael/odoo,mustafat/odoo-1,provaleks/o8,xzYue/odoo,shingonoide/odoo,funkring/fdoo,diagramsoftware/odoo,aviciimaxwell/odoo,Codefans-fan/odoo,hmen89/odoo,pplatek/odoo,ChanduERP/odoo,apanju/odoo,tinkhaven-organization/odoo,klunwebale/odoo,christophlsa/odoo,dllsf/odootest,jaxkodex/odoo,joariasl/odoo,tvibliani/odoo,brijeshkesariya/odoo,Endika/odoo,Gitlab11/odoo,NeovaHealth/odoo,0k/odoo,GauravSahu/odoo,credativUK/OCB,n0m4dz/odoo,srimai/odoo,gvb/odoo,damdam-s/OpenUpgrade,SerpentCS/odoo,rowemoore/odoo,Antiun/odoo,Kilhog/odoo,codekaki/odoo,dariemp/odoo,janocat/odoo,jesramirez/odoo,jusdng/odoo,tinkerthaler/odoo,credativUK/OCB,juanalfonsopr/odoo,KontorConsulting/odoo,fuselock/odoo,windedge/odoo,factorlibre/OCB,hopeall/odoo,apocalypsebg/odoo,BT-fgarbely/odoo,Daniel-CA/odoo,abstract-open-solutions/OCB,klunwebale/odoo,zchking/odoo,ShineFan/odoo,jfpla/odoo,waytai/odoo,alqfahad/odoo,oliverhr/odoo,pedrobaeza/odoo,OSSESAC/odoopubarquiluz,ThinkOpen-Solutions/odoo,Maspear/odoo,gvb/odoo,ShineFan/odoo,chiragjogi/odoo,andreparames/odoo,bwrsandman/OpenUpgrade,jfpla/odoo,draugiskisprendimai/odoo,virgree/odoo,Drooids/odoo,minhtuancn/odoo,acshan/odoo,wangjun/odoo,prospwro/odoo,mlaitinen/odoo,numerigraphe/odoo,blaggacao/OpenUpgrade,tvibliani/odoo,rschnapka/odoo,jiangzhixiao/odoo,odootr/odoo,fjbatresv/odoo,inspyration/odoo,tvtsoft/odoo8,JCA-Developpement/Odoo,gsmartway/odoo,takis/odoo,camptocamp/ngo-addons-backport,mvaled/OpenUpgrade,codekaki/odoo,ApuliaSoftware/odoo,florentx/OpenUpgrade,christophlsa/odoo,juanalfonsopr/odoo,OpenPymeMx/OCB,jiangzhixiao/odoo,0k/odoo,CubicERP/odoo,virgree/odoo,KontorConsulting/odoo,Nowheresly/odoo,omprakasha/odoo,TRESCLOUD/odoopub,pedrobaeza/OpenUpgrade,CopeX/odoo,takis/odoo,JonathanStein/odoo,lombritz/odoo,Adel-Magebinary/odoo,NeovaHealth/odoo,andreparames/odoo,sysadminmatmoz/OCB,kybriainfotech/iSocioCRM,ojengwa/odoo,BT-rmartin/odoo,MarcosCommunity/odoo,OpenUpgrade-dev/OpenUpgrade,AuyaJackie/odoo,mmbtba/odoo,ujjwalwahi/odoo,bplancher/odoo,bkirui/odoo,deKupini/erp,TRESCLOUD/odoopub,addition-it-solutions/project-all,fevxie/odoo,sebalix/OpenUpgrade,stonegithubs/odoo,fossoult/odoo,nhomar/odoo-mirror,cdrooom/odoo,dezynetechnologies/odoo,syci/OCB,takis/odoo,omprakasha/odoo,andreparames/odoo,hopeall/odoo,hifly/OpenUpgrade,jfpla/odoo,sve-odoo/odoo,goliveirab/odoo,odoo-turkiye/odoo,slevenhagen/odoo,odoousers2014/odoo,tinkerthaler/odoo,CubicERP/odoo,Bachaco-ve/odoo,mszewczy/odoo,Daniel-CA/odoo,nagyistoce/odoo-dev-odoo,alhashash/odoo,factorlibre/OCB,windedge/odoo,Adel-Magebinary/odoo,dariemp/odoo,rgeleta/odoo,podemos-info/odoo,savoirfairelinux/OpenUpgrade,alexcuellar/odoo,patmcb/odoo,damdam-s/OpenUpgrade,tvibliani/odoo,csrocha/OpenUpgrade,fossoult/odoo,eino-makitalo/odoo,odooindia/odoo,diagramsoftware/odoo,hanicker/odoo,oihane/odoo,spadae22/odoo,jiachenning/odoo,AuyaJackie/odoo,datenbetrieb/odoo,luistorresm/odoo,Nick-OpusVL/odoo,janocat/odoo,FlorianLudwig/odoo,pedrobaeza/odoo,leoliujie/odoo,guewen/OpenUpgrade,hbrunn/OpenUpgrade,fuselock/odoo,hbrunn/OpenUpgrade,luiseduardohdbackup/odoo,Elico-Corp/odoo_OCB,vnsofthe/odoo,andreparames/odoo,dsfsdgsbngfggb/odoo,Kilhog/odoo,shaufi10/odoo,shivam1111/odoo,guewen/OpenUpgrade,elmerdpadilla/iv,laslabs/odoo,kifcaliph/odoo,bkirui/odoo,mvaled/OpenUpgrade,colinnewell/odoo,Daniel-CA/odoo,draugiskisprendimai/odoo,OpenUpgrade-dev/OpenUpgrade,feroda/odoo,grap/OCB,pplatek/odoo,inspyration/odoo,grap/OpenUpgrade,acshan/odoo,x111ong/odoo,sysadminmatmoz/OCB,naousse/odoo,PongPi/isl-odoo,ShineFan/odoo,guerrerocarlos/odoo,steedos/odoo,guerrerocarlos/odoo,florian-dacosta/OpenUpgrade,x111ong/odoo,grap/OCB,hopeall/odoo,salaria/odoo,salaria/odoo,JGarcia-Panach/odoo,luistorresm/odoo,wangjun/odoo,guewen/OpenUpgrade,incaser/odoo-odoo,feroda/odoo,TRESCLOUD/odoopub,Elico-Corp/odoo_OCB,frouty/odoo_oph,bguillot/OpenUpgrade,Noviat/odoo,ChanduERP/odoo,sergio-incaser/odoo,mkieszek/odoo,0k/odoo,grap/OpenUpgrade,fuhongliang/odoo,rdeheele/odoo,nhomar/odoo,addition-it-solutions/project-all,diagramsoftware/odoo,rahuldhote/odoo,klunwebale/odoo,erkrishna9/odoo,mlaitinen/odoo,poljeff/odoo,savoirfairelinux/odoo,JGarcia-Panach/odoo,OpenUpgrade/OpenUpgrade,tangyiyong/odoo,rschnapka/odoo,fdvarela/odoo8,funkring/fdoo,QianBIG/odoo,ChanduERP/odoo,alexteodor/odoo,frouty/odoogoeen,fgesora/odoo,SerpentCS/odoo,pplatek/odoo,codekaki/odoo,nhomar/odoo-mirror,nexiles/odoo,hubsaysnuaa/odoo,spadae22/odoo,takis/odoo,OSSESAC/odoopubarquiluz,nuncjo/odoo,numerigraphe/odoo,VitalPet/odoo,jusdng/odoo,mkieszek/odoo,odoo-turkiye/odoo,eino-makitalo/odoo,Elico-Corp/odoo_OCB,gdgellatly/OCB1,pedrobaeza/OpenUpgrade,0k/odoo,fjbatresv/odoo,RafaelTorrealba/odoo,mszewczy/odoo,camptocamp/ngo-addons-backport,odoo-turkiye/odoo,n0m4dz/odoo,bakhtout/odoo-educ,oasiswork/odoo,sergio-incaser/odoo,csrocha/OpenUpgrade,synconics/odoo,spadae22/odoo,agrista/odoo-saas,ingadhoc/odoo,goliveirab/odoo,Noviat/odoo,rgeleta/odoo,camptocamp/ngo-addons-backport,fjbatresv/odoo,frouty/odoogoeen,ccomb/OpenUpgrade,arthru/OpenUpgrade,factorlibre/OCB,vrenaville/ngo-addons-backport,lightcn/odoo,apocalypsebg/odoo,draugiskisprendimai/odoo,avoinsystems/odoo,ojengwa/odoo,stephen144/odoo,hanicker/odoo,dllsf/odootest,NL66278/OCB,havt/odoo,PongPi/isl-odoo,elmerdpadilla/iv,VielSoft/odoo,osvalr/odoo,nuuuboo/odoo,Grirrane/odoo,PongPi/isl-odoo,jiangzhixiao/odoo,matrixise/odoo,juanalfonsopr/odoo,jeasoft/odoo,CopeX/odoo,mvaled/OpenUpgrade,abdellatifkarroum/odoo,ovnicraft/odoo,SAM-IT-SA/odoo,Ernesto99/odoo,rowemoore/odoo,florentx/OpenUpgrade,avoinsystems/odoo,markeTIC/OCB,Grirrane/odoo,ApuliaSoftware/odoo,acshan/odoo,kybriainfotech/iSocioCRM,makinacorpus/odoo,dkubiak789/odoo,incaser/odoo-odoo,fuhongliang/odoo,dgzurita/odoo,windedge/odoo,nuncjo/odoo,jolevq/odoopub,prospwro/odoo,GauravSahu/odoo,gsmartway/odoo,oihane/odoo,shaufi10/odoo,stephen144/odoo,gdgellatly/OCB1,sergio-incaser/odoo,hoatle/odoo,cysnake4713/odoo,shaufi10/odoo,CatsAndDogsbvba/odoo,jpshort/odoo,ojengwa/odoo,cdrooom/odoo,rahuldhote/odoo,thanhacun/odoo,frouty/odoogoeen,nhomar/odoo,shingonoide/odoo,hoatle/odoo,sergio-incaser/odoo,dgzurita/odoo,blaggacao/OpenUpgrade,CopeX/odoo,bealdav/OpenUpgrade,dsfsdgsbngfggb/odoo,fgesora/odoo,shivam1111/odoo,colinnewell/odoo,frouty/odoogoeen,fossoult/odoo,hanicker/odoo,OpenPymeMx/OCB,hopeall/odoo,cysnake4713/odoo,jaxkodex/odoo,aviciimaxwell/odoo,xujb/odoo,GauravSahu/odoo,fossoult/odoo,colinnewell/odoo,sebalix/OpenUpgrade,avoinsystems/odoo,pedrobaeza/odoo,odoo-turkiye/odoo,n0m4dz/odoo,mszewczy/odoo,aviciimaxwell/odoo,steedos/odoo,bwrsandman/OpenUpgrade,nagyistoce/odoo-dev-odoo,oasiswork/odoo,tinkerthaler/odoo,numerigraphe/odoo,Nick-OpusVL/odoo,rdeheele/odoo,0k/OpenUpgrade,dariemp/odoo,ApuliaSoftware/odoo,apanju/odoo,apanju/odoo,hopeall/odoo,spadae22/odoo,Drooids/odoo,arthru/OpenUpgrade,nagyistoce/odoo-dev-odoo,idncom/odoo,gavin-feng/odoo,realsaiko/odoo,n0m4dz/odoo,guewen/OpenUpgrade,SerpentCS/odoo,elmerdpadilla/iv,mustafat/odoo-1,OpenUpgrade/OpenUpgrade,JonathanStein/odoo,nuuuboo/odoo,n0m4dz/odoo,srsman/odoo,numerigraphe/odoo,joariasl/odoo,rschnapka/odoo,avoinsystems/odoo,odootr/odoo,slevenhagen/odoo,laslabs/odoo,SerpentCS/odoo,rubencabrera/odoo,jeasoft/odoo,aviciimaxwell/odoo,jolevq/odoopub,Endika/odoo,Nick-OpusVL/odoo,fossoult/odoo,eino-makitalo/odoo,thanhacun/odoo,jfpla/odoo,CatsAndDogsbvba/odoo,stonegithubs/odoo,microcom/odoo,acshan/odoo,vnsofthe/odoo,prospwro/odoo,sve-odoo/odoo,pplatek/odoo,grap/OCB,hip-odoo/odoo,hip-odoo/odoo,ccomb/OpenUpgrade,alhashash/odoo,codekaki/odoo,frouty/odoo_oph,ChanduERP/odoo,slevenhagen/odoo-npg,hoatle/odoo
{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml" ], "active": False, "installable": True } Add purchase_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-231e8ef2a888ac261ce0278ca7f6c387760d8ea3
{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml", "purchase_security.xml" ], "active": False, "installable": True }
<commit_before>{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml" ], "active": False, "installable": True } <commit_msg>Add purchase_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-231e8ef2a888ac261ce0278ca7f6c387760d8ea3<commit_after>
{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml", "purchase_security.xml" ], "active": False, "installable": True }
{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml" ], "active": False, "installable": True } Add purchase_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-231e8ef2a888ac261ce0278ca7f6c387760d8ea3{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml", "purchase_security.xml" ], "active": False, "installable": True }
<commit_before>{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml" ], "active": False, "installable": True } <commit_msg>Add purchase_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-231e8ef2a888ac261ce0278ca7f6c387760d8ea3<commit_after>{ "name" : "Purchase Management", "version" : "1.0", "author" : "Tiny", "website" : "http://tinyerp.com/module_purchase.html", "depends" : ["base", "account", "stock"], "category" : "Generic Modules/Sales & Purchases", "init_xml" : [], "demo_xml" : ["purchase_demo.xml", "purchase_unit_test.xml"], "update_xml" : [ "purchase_workflow.xml", "purchase_sequence.xml", "purchase_data.xml", "purchase_view.xml", "purchase_report.xml", "purchase_wizard.xml", "stock_view.xml", "purchase_security.xml" ], "active": False, "installable": True }
2b1e61d5e24e31598a213614a6f78270474a3e60
source/bark/__init__.py
source/bark/__init__.py
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args, and **kw. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw)
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args*, and *kw*. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw)
Fix argument reference in docstring.
Fix argument reference in docstring.
Python
apache-2.0
4degrees/sawmill,4degrees/mill
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args, and **kw. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw) Fix argument reference in docstring.
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args*, and *kw*. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw)
<commit_before># :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args, and **kw. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw) <commit_msg>Fix argument reference in docstring.<commit_after>
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args*, and *kw*. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw)
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args, and **kw. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw) Fix argument reference in docstring.# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args*, and *kw*. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw)
<commit_before># :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args, and **kw. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw) <commit_msg>Fix argument reference in docstring.<commit_after># :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from .handler.distribute import Distribute from .configurator import classic #: Top level handler responsible for relaying all logs to other handlers. handler = Distribute() handlers = handler.handlers #: Main handle method that should be called with :py:class:`~bark.log.Log` #: instances. handle = handler.handle #: Log levels ordered by severity. Do not rely on the index of the level name # as it may change depending on the configuration. levels = [ 'debug', 'info', 'warning', 'error' ] #: Configurators registered for use with the :py:func:`bark.configure` #: function. configurators = { 'classic': classic.configure } def configure(configurator='classic', *args, **kw): '''Configure Bark using *configurator*. Will call registered configuration function matching the *configurator* name with *args*, and *kw*. ''' configurator = configurators.get(configurator) if configurator is None: raise ValueError('No configurator found with name {0}. Check that ' 'the configurator is registered correctly in the ' 'bark.configurators dictionary.') configurator(*args, **kw)
87983a254ba1d1f036a555aab73fcc07c7f5882b
doc/pyplots/plot_density.py
doc/pyplots/plot_density.py
# -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap import typhon nc = Dataset('_data/test_data.nc') lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) vmr = nc.variables['qv'][:] fig, ax = plt.subplots(figsize=(10, 8)) m = Basemap(projection='cyl', resolution='i', llcrnrlat=47, llcrnrlon=3, urcrnrlat=56, urcrnrlon=16) m.drawcoastlines() m.drawcountries() m.drawmeridians(np.arange(0, 20, 2), labels=[0, 0, 0, 1]) m.drawparallels(np.arange(45, 60, 2), labels=[1, 0, 0, 0]) m.pcolormesh(lon, lat, vmr, latlon=True, cmap='density', rasterized=True) cb = m.colorbar(label='Water vapor [VMR]') fig.tight_layout() plt.show()
# -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import matplotlib.pyplot as plt import netCDF4 import numpy as np import cartopy.crs as ccrs from cartopy.mpl.gridliner import (LONGITUDE_FORMATTER, LATITUDE_FORMATTER) from typhon.plots.maps import get_cfeatures_at_scale # Read air temperature data. with netCDF4.Dataset('_data/test_data.nc') as nc: lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) h2o = nc.variables['qv'][:] # Create plot with PlateCarree projection. fig, ax = plt.subplots(figsize=(10, 8)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([3, 16, 47, 56]) # Add map "features". features = get_cfeatures_at_scale(scale='50m') ax.add_feature(features.BORDERS) ax.add_feature(features.COASTLINE) # Plot the actual data. sm = ax.pcolormesh(lon, lat, h2o, cmap='density', rasterized=True, transform=ccrs.PlateCarree(), ) fig.colorbar(sm, label='Water vapor [VMR]', fraction=0.0328, pad=0.02) # Add coordinate system without drawing gridlines. gl = ax.gridlines(draw_labels=True, color='none') gl.xformatter, gl.yformatter = LONGITUDE_FORMATTER, LATITUDE_FORMATTER gl.xlabels_top = gl.ylabels_right = False fig.tight_layout() plt.show()
Migrate density example to cartopy.
Migrate density example to cartopy.
Python
mit
atmtools/typhon,atmtools/typhon
# -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap import typhon nc = Dataset('_data/test_data.nc') lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) vmr = nc.variables['qv'][:] fig, ax = plt.subplots(figsize=(10, 8)) m = Basemap(projection='cyl', resolution='i', llcrnrlat=47, llcrnrlon=3, urcrnrlat=56, urcrnrlon=16) m.drawcoastlines() m.drawcountries() m.drawmeridians(np.arange(0, 20, 2), labels=[0, 0, 0, 1]) m.drawparallels(np.arange(45, 60, 2), labels=[1, 0, 0, 0]) m.pcolormesh(lon, lat, vmr, latlon=True, cmap='density', rasterized=True) cb = m.colorbar(label='Water vapor [VMR]') fig.tight_layout() plt.show() Migrate density example to cartopy.
# -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import matplotlib.pyplot as plt import netCDF4 import numpy as np import cartopy.crs as ccrs from cartopy.mpl.gridliner import (LONGITUDE_FORMATTER, LATITUDE_FORMATTER) from typhon.plots.maps import get_cfeatures_at_scale # Read air temperature data. with netCDF4.Dataset('_data/test_data.nc') as nc: lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) h2o = nc.variables['qv'][:] # Create plot with PlateCarree projection. fig, ax = plt.subplots(figsize=(10, 8)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([3, 16, 47, 56]) # Add map "features". features = get_cfeatures_at_scale(scale='50m') ax.add_feature(features.BORDERS) ax.add_feature(features.COASTLINE) # Plot the actual data. sm = ax.pcolormesh(lon, lat, h2o, cmap='density', rasterized=True, transform=ccrs.PlateCarree(), ) fig.colorbar(sm, label='Water vapor [VMR]', fraction=0.0328, pad=0.02) # Add coordinate system without drawing gridlines. gl = ax.gridlines(draw_labels=True, color='none') gl.xformatter, gl.yformatter = LONGITUDE_FORMATTER, LATITUDE_FORMATTER gl.xlabels_top = gl.ylabels_right = False fig.tight_layout() plt.show()
<commit_before># -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap import typhon nc = Dataset('_data/test_data.nc') lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) vmr = nc.variables['qv'][:] fig, ax = plt.subplots(figsize=(10, 8)) m = Basemap(projection='cyl', resolution='i', llcrnrlat=47, llcrnrlon=3, urcrnrlat=56, urcrnrlon=16) m.drawcoastlines() m.drawcountries() m.drawmeridians(np.arange(0, 20, 2), labels=[0, 0, 0, 1]) m.drawparallels(np.arange(45, 60, 2), labels=[1, 0, 0, 0]) m.pcolormesh(lon, lat, vmr, latlon=True, cmap='density', rasterized=True) cb = m.colorbar(label='Water vapor [VMR]') fig.tight_layout() plt.show() <commit_msg>Migrate density example to cartopy.<commit_after>
# -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import matplotlib.pyplot as plt import netCDF4 import numpy as np import cartopy.crs as ccrs from cartopy.mpl.gridliner import (LONGITUDE_FORMATTER, LATITUDE_FORMATTER) from typhon.plots.maps import get_cfeatures_at_scale # Read air temperature data. with netCDF4.Dataset('_data/test_data.nc') as nc: lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) h2o = nc.variables['qv'][:] # Create plot with PlateCarree projection. fig, ax = plt.subplots(figsize=(10, 8)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([3, 16, 47, 56]) # Add map "features". features = get_cfeatures_at_scale(scale='50m') ax.add_feature(features.BORDERS) ax.add_feature(features.COASTLINE) # Plot the actual data. sm = ax.pcolormesh(lon, lat, h2o, cmap='density', rasterized=True, transform=ccrs.PlateCarree(), ) fig.colorbar(sm, label='Water vapor [VMR]', fraction=0.0328, pad=0.02) # Add coordinate system without drawing gridlines. gl = ax.gridlines(draw_labels=True, color='none') gl.xformatter, gl.yformatter = LONGITUDE_FORMATTER, LATITUDE_FORMATTER gl.xlabels_top = gl.ylabels_right = False fig.tight_layout() plt.show()
# -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap import typhon nc = Dataset('_data/test_data.nc') lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) vmr = nc.variables['qv'][:] fig, ax = plt.subplots(figsize=(10, 8)) m = Basemap(projection='cyl', resolution='i', llcrnrlat=47, llcrnrlon=3, urcrnrlat=56, urcrnrlon=16) m.drawcoastlines() m.drawcountries() m.drawmeridians(np.arange(0, 20, 2), labels=[0, 0, 0, 1]) m.drawparallels(np.arange(45, 60, 2), labels=[1, 0, 0, 0]) m.pcolormesh(lon, lat, vmr, latlon=True, cmap='density', rasterized=True) cb = m.colorbar(label='Water vapor [VMR]') fig.tight_layout() plt.show() Migrate density example to cartopy.# -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import matplotlib.pyplot as plt import netCDF4 import numpy as np import cartopy.crs as ccrs from cartopy.mpl.gridliner import (LONGITUDE_FORMATTER, LATITUDE_FORMATTER) from typhon.plots.maps import get_cfeatures_at_scale # Read air temperature data. with netCDF4.Dataset('_data/test_data.nc') as nc: lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) h2o = nc.variables['qv'][:] # Create plot with PlateCarree projection. fig, ax = plt.subplots(figsize=(10, 8)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([3, 16, 47, 56]) # Add map "features". features = get_cfeatures_at_scale(scale='50m') ax.add_feature(features.BORDERS) ax.add_feature(features.COASTLINE) # Plot the actual data. sm = ax.pcolormesh(lon, lat, h2o, cmap='density', rasterized=True, transform=ccrs.PlateCarree(), ) fig.colorbar(sm, label='Water vapor [VMR]', fraction=0.0328, pad=0.02) # Add coordinate system without drawing gridlines. gl = ax.gridlines(draw_labels=True, color='none') gl.xformatter, gl.yformatter = LONGITUDE_FORMATTER, LATITUDE_FORMATTER gl.xlabels_top = gl.ylabels_right = False fig.tight_layout() plt.show()
<commit_before># -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import numpy as np import matplotlib.pyplot as plt from netCDF4 import Dataset from mpl_toolkits.basemap import Basemap import typhon nc = Dataset('_data/test_data.nc') lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) vmr = nc.variables['qv'][:] fig, ax = plt.subplots(figsize=(10, 8)) m = Basemap(projection='cyl', resolution='i', llcrnrlat=47, llcrnrlon=3, urcrnrlat=56, urcrnrlon=16) m.drawcoastlines() m.drawcountries() m.drawmeridians(np.arange(0, 20, 2), labels=[0, 0, 0, 1]) m.drawparallels(np.arange(45, 60, 2), labels=[1, 0, 0, 0]) m.pcolormesh(lon, lat, vmr, latlon=True, cmap='density', rasterized=True) cb = m.colorbar(label='Water vapor [VMR]') fig.tight_layout() plt.show() <commit_msg>Migrate density example to cartopy.<commit_after># -*- coding: utf-8 -*- """Plot to demonstrate the density colormap. """ import matplotlib.pyplot as plt import netCDF4 import numpy as np import cartopy.crs as ccrs from cartopy.mpl.gridliner import (LONGITUDE_FORMATTER, LATITUDE_FORMATTER) from typhon.plots.maps import get_cfeatures_at_scale # Read air temperature data. with netCDF4.Dataset('_data/test_data.nc') as nc: lon, lat = np.meshgrid(nc.variables['lon'][:], nc.variables['lat'][:]) h2o = nc.variables['qv'][:] # Create plot with PlateCarree projection. fig, ax = plt.subplots(figsize=(10, 8)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent([3, 16, 47, 56]) # Add map "features". features = get_cfeatures_at_scale(scale='50m') ax.add_feature(features.BORDERS) ax.add_feature(features.COASTLINE) # Plot the actual data. sm = ax.pcolormesh(lon, lat, h2o, cmap='density', rasterized=True, transform=ccrs.PlateCarree(), ) fig.colorbar(sm, label='Water vapor [VMR]', fraction=0.0328, pad=0.02) # Add coordinate system without drawing gridlines. gl = ax.gridlines(draw_labels=True, color='none') gl.xformatter, gl.yformatter = LONGITUDE_FORMATTER, LATITUDE_FORMATTER gl.xlabels_top = gl.ylabels_right = False fig.tight_layout() plt.show()
e9a73945d57f93ef71d971aab5ae5cc501800c17
aslo/api/gh.py
aslo/api/gh.py
import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() tag_commit = None for tag in tags: if tag.name == tag_name: tag_commit = tag.commit return tag_commit def comment_on_commit(commit, message): commit.create_comment(message)
import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() for tag in tags: if tag.name == tag_name: return tag.commit return None def comment_on_commit(commit, message): commit.create_comment(message)
Improve performance of find tags function
Improve performance of find tags function
Python
mit
jatindhankhar/aslo-v3,jatindhankhar/aslo-v3,jatindhankhar/aslo-v3,jatindhankhar/aslo-v3
import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() tag_commit = None for tag in tags: if tag.name == tag_name: tag_commit = tag.commit return tag_commit def comment_on_commit(commit, message): commit.create_comment(message) Improve performance of find tags function
import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() for tag in tags: if tag.name == tag_name: return tag.commit return None def comment_on_commit(commit, message): commit.create_comment(message)
<commit_before>import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() tag_commit = None for tag in tags: if tag.name == tag_name: tag_commit = tag.commit return tag_commit def comment_on_commit(commit, message): commit.create_comment(message) <commit_msg>Improve performance of find tags function<commit_after>
import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() for tag in tags: if tag.name == tag_name: return tag.commit return None def comment_on_commit(commit, message): commit.create_comment(message)
import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() tag_commit = None for tag in tags: if tag.name == tag_name: tag_commit = tag.commit return tag_commit def comment_on_commit(commit, message): commit.create_comment(message) Improve performance of find tags functionimport hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() for tag in tags: if tag.name == tag_name: return tag.commit return None def comment_on_commit(commit, message): commit.create_comment(message)
<commit_before>import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() tag_commit = None for tag in tags: if tag.name == tag_name: tag_commit = tag.commit return tag_commit def comment_on_commit(commit, message): commit.create_comment(message) <commit_msg>Improve performance of find tags function<commit_after>import hmac import hashlib from flask import current_app as app from urllib.parse import urlparse from github import Github def verify_signature(gh_signature, body, secret): sha1 = hmac.new(secret.encode(), body, hashlib.sha1).hexdigest() return hmac.compare_digest('sha1=' + sha1, gh_signature) def auth(): g = Github(app.config['GITHUB_OAUTH_TOKEN']) return g def get_developers(repo_url): o = urlparse(repo_url) repo = o.path[1:].strip('.git') g = auth() repository = g.get_repo(repo) contributors = repository.get_contributors() developers = [] for c in contributors: dev = {'email': c.email, 'page': c.html_url, 'avatar': c.avatar_url} dev['name'] = c.name if c.name else c.login developers.append(dev) return developers def find_tag_commit(repo_name, tag_name): g = auth() tags = g.get_repo(repo_name).get_tags() for tag in tags: if tag.name == tag_name: return tag.commit return None def comment_on_commit(commit, message): commit.create_comment(message)
3be50d7b6f3cbd3bc5185257377efe9c39ebb01f
server_tracking/django/settings.py
server_tracking/django/settings.py
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING = settings.SERVER_SIDE_TRACKING SERVER_SIDE_TRACKING_GA = settings.SERVER_SIDE_TRACKING_GA if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.")
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .. import DEFER_METHOD_CELERY from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) SERVER_SIDE_TRACKING = update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING_GA = update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) if SERVER_SIDE_TRACKING['defer'] == DEFER_METHOD_CELERY: from ..google import tasks if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.")
Load tasks module on app load.
Load tasks module on app load.
Python
mit
merll/server-side-tracking,merll/server-tracking
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING = settings.SERVER_SIDE_TRACKING SERVER_SIDE_TRACKING_GA = settings.SERVER_SIDE_TRACKING_GA if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.") Load tasks module on app load.
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .. import DEFER_METHOD_CELERY from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) SERVER_SIDE_TRACKING = update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING_GA = update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) if SERVER_SIDE_TRACKING['defer'] == DEFER_METHOD_CELERY: from ..google import tasks if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.")
<commit_before># -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING = settings.SERVER_SIDE_TRACKING SERVER_SIDE_TRACKING_GA = settings.SERVER_SIDE_TRACKING_GA if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.") <commit_msg>Load tasks module on app load.<commit_after>
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .. import DEFER_METHOD_CELERY from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) SERVER_SIDE_TRACKING = update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING_GA = update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) if SERVER_SIDE_TRACKING['defer'] == DEFER_METHOD_CELERY: from ..google import tasks if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.")
# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING = settings.SERVER_SIDE_TRACKING SERVER_SIDE_TRACKING_GA = settings.SERVER_SIDE_TRACKING_GA if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.") Load tasks module on app load.# -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .. import DEFER_METHOD_CELERY from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) SERVER_SIDE_TRACKING = update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING_GA = update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) if SERVER_SIDE_TRACKING['defer'] == DEFER_METHOD_CELERY: from ..google import tasks if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.")
<commit_before># -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING = settings.SERVER_SIDE_TRACKING SERVER_SIDE_TRACKING_GA = settings.SERVER_SIDE_TRACKING_GA if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.") <commit_msg>Load tasks module on app load.<commit_after># -*- coding: utf-8 -*- from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .. import DEFER_METHOD_CELERY from ..settings import SST_DEFAULT_SETTINGS, GA_DEFAULT_SETTINGS, update_default_settings SST_DEFAULT_SETTINGS.update( cookie_path=getattr(settings, 'SESSION_COOKIE_PATH', '/'), cookie_salt=getattr(settings, 'SECRET_KEY', ''), debug=getattr(settings, 'DEBUG', False), pageview_exclude=( 'admin/', ), django_title_extractors=( 'server_tracking.django.utils.ContextTitleExtractor', 'server_tracking.django.utils.ViewTitleExtractor', ), ) SERVER_SIDE_TRACKING = update_default_settings(settings, 'SERVER_SIDE_TRACKING', SST_DEFAULT_SETTINGS) SERVER_SIDE_TRACKING_GA = update_default_settings(settings, 'SERVER_SIDE_TRACKING_GA', GA_DEFAULT_SETTINGS) if SERVER_SIDE_TRACKING['defer'] == DEFER_METHOD_CELERY: from ..google import tasks if 'property' not in SERVER_SIDE_TRACKING_GA: raise ImproperlyConfigured("SERVER_SIDE_TRACKING_GA must be defined in Django settings with a key 'property'.")
1d9217ae9652a152033f8691f2bc5e78d3600684
server/server.py
server/server.py
from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Starting Turtle Control System... [PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server()
from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Turtle Control Software v' + version_info) logger.info('[PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server()
Add info about version to log
Add info about version to log
Python
mit
TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control
from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Starting Turtle Control System... [PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server() Add info about version to log
from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Turtle Control Software v' + version_info) logger.info('[PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server()
<commit_before>from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Starting Turtle Control System... [PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server() <commit_msg>Add info about version to log<commit_after>
from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Turtle Control Software v' + version_info) logger.info('[PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server()
from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Starting Turtle Control System... [PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server() Add info about version to logfrom killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Turtle Control Software v' + version_info) logger.info('[PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server()
<commit_before>from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Starting Turtle Control System... [PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server() <commit_msg>Add info about version to log<commit_after>from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Turtle Control Software v' + version_info) logger.info('[PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server()
7c1538c9991badf205214e9f4e567cc4f1879ce6
pasta/base/ast_constants.py
pasta/base/ast_constants.py
"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.Sub: ('-',), ast.Mult: ('*',), ast.Div: ('/',), ast.Mod: ('%',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Pow: ('**',), ast.LShift: ('<<',), ast.RShift: ('>>',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Invert: ('~',), ast.Not: ('not',), ast.UAdd: ('+',), ast.USub: ('-',), ast.And: ('and',), ast.Or: ('or',), ast.Eq: ('==',), ast.NotEq: ('!=',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.In: ('in',), ast.NotIn: ('not', 'in',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',)
"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.And: ('and',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.Div: ('/',), ast.Eq: ('==',), ast.FloorDiv: ('//',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.In: ('in',), ast.Invert: ('~',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.LShift: ('<<',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Mod: ('%',), ast.Mult: ('*',), ast.Not: ('not',), ast.NotEq: ('!=',), ast.NotIn: ('not', 'in',), ast.Or: ('or',), ast.Pow: ('**',), ast.RShift: ('>>',), ast.Sub: ('-',), ast.UAdd: ('+',), ast.USub: ('-',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',)
Sort ast nodes in constants + remove duplicates
Sort ast nodes in constants + remove duplicates
Python
apache-2.0
google/pasta
"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.Sub: ('-',), ast.Mult: ('*',), ast.Div: ('/',), ast.Mod: ('%',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Pow: ('**',), ast.LShift: ('<<',), ast.RShift: ('>>',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Invert: ('~',), ast.Not: ('not',), ast.UAdd: ('+',), ast.USub: ('-',), ast.And: ('and',), ast.Or: ('or',), ast.Eq: ('==',), ast.NotEq: ('!=',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.In: ('in',), ast.NotIn: ('not', 'in',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',) Sort ast nodes in constants + remove duplicates
"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.And: ('and',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.Div: ('/',), ast.Eq: ('==',), ast.FloorDiv: ('//',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.In: ('in',), ast.Invert: ('~',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.LShift: ('<<',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Mod: ('%',), ast.Mult: ('*',), ast.Not: ('not',), ast.NotEq: ('!=',), ast.NotIn: ('not', 'in',), ast.Or: ('or',), ast.Pow: ('**',), ast.RShift: ('>>',), ast.Sub: ('-',), ast.UAdd: ('+',), ast.USub: ('-',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',)
<commit_before>"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.Sub: ('-',), ast.Mult: ('*',), ast.Div: ('/',), ast.Mod: ('%',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Pow: ('**',), ast.LShift: ('<<',), ast.RShift: ('>>',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Invert: ('~',), ast.Not: ('not',), ast.UAdd: ('+',), ast.USub: ('-',), ast.And: ('and',), ast.Or: ('or',), ast.Eq: ('==',), ast.NotEq: ('!=',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.In: ('in',), ast.NotIn: ('not', 'in',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',) <commit_msg>Sort ast nodes in constants + remove duplicates<commit_after>
"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.And: ('and',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.Div: ('/',), ast.Eq: ('==',), ast.FloorDiv: ('//',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.In: ('in',), ast.Invert: ('~',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.LShift: ('<<',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Mod: ('%',), ast.Mult: ('*',), ast.Not: ('not',), ast.NotEq: ('!=',), ast.NotIn: ('not', 'in',), ast.Or: ('or',), ast.Pow: ('**',), ast.RShift: ('>>',), ast.Sub: ('-',), ast.UAdd: ('+',), ast.USub: ('-',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',)
"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.Sub: ('-',), ast.Mult: ('*',), ast.Div: ('/',), ast.Mod: ('%',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Pow: ('**',), ast.LShift: ('<<',), ast.RShift: ('>>',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Invert: ('~',), ast.Not: ('not',), ast.UAdd: ('+',), ast.USub: ('-',), ast.And: ('and',), ast.Or: ('or',), ast.Eq: ('==',), ast.NotEq: ('!=',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.In: ('in',), ast.NotIn: ('not', 'in',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',) Sort ast nodes in constants + remove duplicates"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.And: ('and',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.Div: ('/',), ast.Eq: ('==',), ast.FloorDiv: ('//',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.In: ('in',), ast.Invert: ('~',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.LShift: ('<<',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Mod: ('%',), ast.Mult: ('*',), ast.Not: ('not',), ast.NotEq: ('!=',), ast.NotIn: ('not', 'in',), ast.Or: ('or',), ast.Pow: ('**',), ast.RShift: ('>>',), ast.Sub: ('-',), ast.UAdd: ('+',), ast.USub: ('-',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',)
<commit_before>"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.Sub: ('-',), ast.Mult: ('*',), ast.Div: ('/',), ast.Mod: ('%',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Pow: ('**',), ast.LShift: ('<<',), ast.RShift: ('>>',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.FloorDiv: ('//',), ast.Invert: ('~',), ast.Not: ('not',), ast.UAdd: ('+',), ast.USub: ('-',), ast.And: ('and',), ast.Or: ('or',), ast.Eq: ('==',), ast.NotEq: ('!=',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.In: ('in',), ast.NotIn: ('not', 'in',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',) <commit_msg>Sort ast nodes in constants + remove duplicates<commit_after>"""Constants relevant to ast code.""" import ast NODE_TYPE_TO_TOKENS = { ast.Add: ('+',), ast.And: ('and',), ast.BitAnd: ('&',), ast.BitOr: ('|',), ast.BitXor: ('^',), ast.Div: ('/',), ast.Eq: ('==',), ast.FloorDiv: ('//',), ast.Gt: ('>',), ast.GtE: ('>=',), ast.In: ('in',), ast.Invert: ('~',), ast.Is: ('is',), ast.IsNot: ('is', 'not',), ast.LShift: ('<<',), ast.Lt: ('<',), ast.LtE: ('<=',), ast.Mod: ('%',), ast.Mult: ('*',), ast.Not: ('not',), ast.NotEq: ('!=',), ast.NotIn: ('not', 'in',), ast.Or: ('or',), ast.Pow: ('**',), ast.RShift: ('>>',), ast.Sub: ('-',), ast.UAdd: ('+',), ast.USub: ('-',), } if hasattr(ast, 'MatMult'): NODE_TYPE_TO_TOKENS[ast.MatMult] = ('@',)
373ce0f89a9253065114c757d3484849349a716d
tests/data_context/test_data_context_utils.py
tests/data_context/test_data_context_utils.py
import pytest import os from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 second_path = os.path.join(project_path,"second_path") print(second_path) print(type(second_path)) safe_mmkdir(os.path.dirname(second_path))
import pytest import os import six from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 if six.PY2: with pytest.raises(TypeError) as e: next_project_path = tmp_path_factory.mktemp('test_safe_mmkdir__dir_b') safe_mmkdir(next_project_path) assert e.value.message == "directory must be of type str, not {'directory_type': \"<class 'pathlib2.PosixPath'>\"}"
Add test for the intended use case
Add test for the intended use case
Python
apache-2.0
great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations
import pytest import os from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 second_path = os.path.join(project_path,"second_path") print(second_path) print(type(second_path)) safe_mmkdir(os.path.dirname(second_path)) Add test for the intended use case
import pytest import os import six from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 if six.PY2: with pytest.raises(TypeError) as e: next_project_path = tmp_path_factory.mktemp('test_safe_mmkdir__dir_b') safe_mmkdir(next_project_path) assert e.value.message == "directory must be of type str, not {'directory_type': \"<class 'pathlib2.PosixPath'>\"}"
<commit_before>import pytest import os from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 second_path = os.path.join(project_path,"second_path") print(second_path) print(type(second_path)) safe_mmkdir(os.path.dirname(second_path)) <commit_msg>Add test for the intended use case<commit_after>
import pytest import os import six from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 if six.PY2: with pytest.raises(TypeError) as e: next_project_path = tmp_path_factory.mktemp('test_safe_mmkdir__dir_b') safe_mmkdir(next_project_path) assert e.value.message == "directory must be of type str, not {'directory_type': \"<class 'pathlib2.PosixPath'>\"}"
import pytest import os from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 second_path = os.path.join(project_path,"second_path") print(second_path) print(type(second_path)) safe_mmkdir(os.path.dirname(second_path)) Add test for the intended use caseimport pytest import os import six from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 if six.PY2: with pytest.raises(TypeError) as e: next_project_path = tmp_path_factory.mktemp('test_safe_mmkdir__dir_b') safe_mmkdir(next_project_path) assert e.value.message == "directory must be of type str, not {'directory_type': \"<class 'pathlib2.PosixPath'>\"}"
<commit_before>import pytest import os from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 second_path = os.path.join(project_path,"second_path") print(second_path) print(type(second_path)) safe_mmkdir(os.path.dirname(second_path)) <commit_msg>Add test for the intended use case<commit_after>import pytest import os import six from great_expectations.data_context.util import ( safe_mmkdir, ) def test_safe_mmkdir(tmp_path_factory): project_path = str(tmp_path_factory.mktemp('empty_dir')) first_path = os.path.join(project_path,"first_path") safe_mmkdir(first_path) assert os.path.isdir(first_path) with pytest.raises(TypeError): safe_mmkdir(1) #This should trigger python 2 if six.PY2: with pytest.raises(TypeError) as e: next_project_path = tmp_path_factory.mktemp('test_safe_mmkdir__dir_b') safe_mmkdir(next_project_path) assert e.value.message == "directory must be of type str, not {'directory_type': \"<class 'pathlib2.PosixPath'>\"}"
44ff3a216c1f1e22862e1cac9c33a4e3a99860a7
pyramda/iterable/reject.py
pyramda/iterable/reject.py
from pyramda.function.curry import curry from . import filter @curry def reject(f, xs): """ Acts as a compliment of `filter` :param f: function :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(f, xs)))
from pyramda.function.curry import curry from . import filter @curry def reject(p, xs): """ Acts as a complement of `filter` :param p: predicate :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(p, xs)))
Rename function arg and spelling fix in docstring
Rename function arg and spelling fix in docstring
Python
mit
jackfirth/pyramda
from pyramda.function.curry import curry from . import filter @curry def reject(f, xs): """ Acts as a compliment of `filter` :param f: function :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(f, xs))) Rename function arg and spelling fix in docstring
from pyramda.function.curry import curry from . import filter @curry def reject(p, xs): """ Acts as a complement of `filter` :param p: predicate :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(p, xs)))
<commit_before>from pyramda.function.curry import curry from . import filter @curry def reject(f, xs): """ Acts as a compliment of `filter` :param f: function :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(f, xs))) <commit_msg>Rename function arg and spelling fix in docstring<commit_after>
from pyramda.function.curry import curry from . import filter @curry def reject(p, xs): """ Acts as a complement of `filter` :param p: predicate :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(p, xs)))
from pyramda.function.curry import curry from . import filter @curry def reject(f, xs): """ Acts as a compliment of `filter` :param f: function :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(f, xs))) Rename function arg and spelling fix in docstringfrom pyramda.function.curry import curry from . import filter @curry def reject(p, xs): """ Acts as a complement of `filter` :param p: predicate :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(p, xs)))
<commit_before>from pyramda.function.curry import curry from . import filter @curry def reject(f, xs): """ Acts as a compliment of `filter` :param f: function :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(f, xs))) <commit_msg>Rename function arg and spelling fix in docstring<commit_after>from pyramda.function.curry import curry from . import filter @curry def reject(p, xs): """ Acts as a complement of `filter` :param p: predicate :param xs: Iterable. A sequence, a container which supports iteration or an iterator :return: list """ return list(set(xs) - set(filter(p, xs)))
39e7bbeadab2437b5dcfc3ffda685f07a3312206
polls/models.py
polls/models.py
from django.db import models from django.contrib.auth.models import User class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(User) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll'))
from django.db import models from django.conf import settings class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll'))
Support for custom user model
Support for custom user model
Python
bsd-3-clause
byteweaver/django-polls,byteweaver/django-polls
from django.db import models from django.contrib.auth.models import User class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(User) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll')) Support for custom user model
from django.db import models from django.conf import settings class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll'))
<commit_before>from django.db import models from django.contrib.auth.models import User class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(User) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll')) <commit_msg>Support for custom user model<commit_after>
from django.db import models from django.conf import settings class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll'))
from django.db import models from django.contrib.auth.models import User class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(User) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll')) Support for custom user modelfrom django.db import models from django.conf import settings class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll'))
<commit_before>from django.db import models from django.contrib.auth.models import User class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(User) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll')) <commit_msg>Support for custom user model<commit_after>from django.db import models from django.conf import settings class Poll(models.Model): question = models.CharField(max_length=255) description = models.TextField(blank=True) def count_choices(self): return self.choice_set.count() def count_total_votes(self): result = 0 for choice in self.choice_set.all(): result += choice.count_votes() return result def can_vote(self, user): return not self.vote_set.filter(user=user).exists() def __unicode__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=255) def count_votes(self): return self.vote_set.count() def __unicode__(self): return self.choice class Meta: ordering = ['choice'] class Vote(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) poll = models.ForeignKey(Poll) choice = models.ForeignKey(Choice) def __unicode__(self): return u'Vote for %s' % (self.choice) class Meta: unique_together = (('user', 'poll'))
5131e5d84c498c28ab26f4eae40ba8e0223dc33c
tests/unit/compat_tests.py
tests/unit/compat_tests.py
try: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0))
try: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0)) def test_get_linux_version_gcp(self): self.assertEqual(compat.get_linux_version("4.4.64+"), (4, 4, 64))
Add a test for `get_linux_version` for GCP
Add a test for `get_linux_version` for GCP
Python
bsd-3-clause
pika/pika,vitaly-krugl/pika
try: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0)) Add a test for `get_linux_version` for GCP
try: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0)) def test_get_linux_version_gcp(self): self.assertEqual(compat.get_linux_version("4.4.64+"), (4, 4, 64))
<commit_before>try: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0)) <commit_msg>Add a test for `get_linux_version` for GCP<commit_after>
try: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0)) def test_get_linux_version_gcp(self): self.assertEqual(compat.get_linux_version("4.4.64+"), (4, 4, 64))
try: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0)) Add a test for `get_linux_version` for GCPtry: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0)) def test_get_linux_version_gcp(self): self.assertEqual(compat.get_linux_version("4.4.64+"), (4, 4, 64))
<commit_before>try: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0)) <commit_msg>Add a test for `get_linux_version` for GCP<commit_after>try: import unittest2 as unittest except ImportError: import unittest from pika import compat class UtilsTests(unittest.TestCase): def test_get_linux_version_normal(self): self.assertEqual(compat.get_linux_version("4.11.0-2-amd64"), (4, 11, 0)) def test_get_linux_version_short(self): self.assertEqual(compat.get_linux_version("4.11.0"), (4, 11, 0)) def test_get_linux_version_gcp(self): self.assertEqual(compat.get_linux_version("4.4.64+"), (4, 4, 64))
a02739581d6c9dbde900c226d121b4fb889b4e2d
window.py
window.py
from PySide import QtGui from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) editor = Editor() self.setCentralWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized()
from PySide import QtGui, QtCore from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) treeview = QtGui.QTreeView() editor = Editor() self.setCentralWidget(splitter) splitter.addWidget(treeview) splitter.addWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized()
Add splitter with treeview/editor split.
Add splitter with treeview/editor split.
Python
bsd-3-clause
audreyr/sphinx-gui,techdragon/sphinx-gui,audreyr/sphinx-gui,techdragon/sphinx-gui
from PySide import QtGui from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) editor = Editor() self.setCentralWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized() Add splitter with treeview/editor split.
from PySide import QtGui, QtCore from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) treeview = QtGui.QTreeView() editor = Editor() self.setCentralWidget(splitter) splitter.addWidget(treeview) splitter.addWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized()
<commit_before>from PySide import QtGui from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) editor = Editor() self.setCentralWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized() <commit_msg>Add splitter with treeview/editor split.<commit_after>
from PySide import QtGui, QtCore from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) treeview = QtGui.QTreeView() editor = Editor() self.setCentralWidget(splitter) splitter.addWidget(treeview) splitter.addWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized()
from PySide import QtGui from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) editor = Editor() self.setCentralWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized() Add splitter with treeview/editor split.from PySide import QtGui, QtCore from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) treeview = QtGui.QTreeView() editor = Editor() self.setCentralWidget(splitter) splitter.addWidget(treeview) splitter.addWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized()
<commit_before>from PySide import QtGui from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) editor = Editor() self.setCentralWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized() <commit_msg>Add splitter with treeview/editor split.<commit_after>from PySide import QtGui, QtCore from editor import Editor class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) treeview = QtGui.QTreeView() editor = Editor() self.setCentralWidget(splitter) splitter.addWidget(treeview) splitter.addWidget(editor) self.setWindowTitle("RST Previewer") self.showMaximized()
92031812b77479fe9a3dbd3ca512ba97e700384e
fusion_index/test/test_lookup.py
fusion_index/test/test_lookup.py
from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, lists, text, tuples, characters from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(e, t, k)] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
import string from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, characters, lists, text, tuples from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) _lower_table = dict( zip(map(ord, string.uppercase.decode('ascii')), map(ord, string.lowercase.decode('ascii')))) def _lower(s): """ Lowercase only ASCII characters, like SQLite NOCASE. """ return s.translate(_lower_table) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(_lower(e), _lower(t), _lower(k))] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
Fix test model to be case-insensitive.
Fix test model to be case-insensitive.
Python
mit
fusionapp/fusion-index
from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, lists, text, tuples, characters from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(e, t, k)] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx) Fix test model to be case-insensitive.
import string from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, characters, lists, text, tuples from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) _lower_table = dict( zip(map(ord, string.uppercase.decode('ascii')), map(ord, string.lowercase.decode('ascii')))) def _lower(s): """ Lowercase only ASCII characters, like SQLite NOCASE. """ return s.translate(_lower_table) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(_lower(e), _lower(t), _lower(k))] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
<commit_before>from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, lists, text, tuples, characters from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(e, t, k)] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx) <commit_msg>Fix test model to be case-insensitive.<commit_after>
import string from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, characters, lists, text, tuples from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) _lower_table = dict( zip(map(ord, string.uppercase.decode('ascii')), map(ord, string.lowercase.decode('ascii')))) def _lower(s): """ Lowercase only ASCII characters, like SQLite NOCASE. """ return s.translate(_lower_table) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(_lower(e), _lower(t), _lower(k))] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, lists, text, tuples, characters from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(e, t, k)] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx) Fix test model to be case-insensitive.import string from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, characters, lists, text, tuples from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) _lower_table = dict( zip(map(ord, string.uppercase.decode('ascii')), map(ord, string.lowercase.decode('ascii')))) def _lower(s): """ Lowercase only ASCII characters, like SQLite NOCASE. """ return s.translate(_lower_table) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(_lower(e), _lower(t), _lower(k))] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
<commit_before>from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, lists, text, tuples, characters from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(e, t, k)] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx) <commit_msg>Fix test model to be case-insensitive.<commit_after>import string from axiom.store import Store from hypothesis import given from hypothesis.strategies import binary, characters, lists, text, tuples from testtools import TestCase from testtools.matchers import Equals from fusion_index.lookup import LookupEntry def axiom_text(): return text( alphabet=characters( blacklist_categories={'Cs'}, blacklist_characters={u'\x00'}), average_size=5) _lower_table = dict( zip(map(ord, string.uppercase.decode('ascii')), map(ord, string.lowercase.decode('ascii')))) def _lower(s): """ Lowercase only ASCII characters, like SQLite NOCASE. """ return s.translate(_lower_table) class LookupTests(TestCase): @given(lists(tuples(axiom_text(), axiom_text(), axiom_text(), binary()))) def test_inserts(self, values): """ Test inserting and retrieving arbitrary entries. """ s = Store() def _tx(): d = {} for e, t, k, v in values: LookupEntry.set(s, e, t, k, v) d[(_lower(e), _lower(t), _lower(k))] = v self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) for (e, t, k), v in d.iteritems(): self.assertThat(LookupEntry.get(s, e, t, k), Equals(v)) s.transact(_tx)
d86fe37bb29cc8c09c4659de579d4c370a59c40b
scripts/container_log_collector.py
scripts/container_log_collector.py
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs) stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name)
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs, encoding="utf-8") stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name)
Set docker log encoding to utf-8
Set docker log encoding to utf-8
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs) stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name) Set docker log encoding to utf-8
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs, encoding="utf-8") stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name)
<commit_before># stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs) stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name) <commit_msg>Set docker log encoding to utf-8<commit_after>
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs, encoding="utf-8") stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name)
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs) stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name) Set docker log encoding to utf-8# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs, encoding="utf-8") stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name)
<commit_before># stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs) stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name) <commit_msg>Set docker log encoding to utf-8<commit_after># stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs, encoding="utf-8") stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name)
bd9a52bdf4d0d2a80467c144b21b13e77a7d92c2
examples/redis/src/bolts.py
examples/redis/src/bolts.py
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(WordCountBolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by self.redis.zincrby("words", word, inc_by)
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(Bolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by return self.redis.zincrby("words", word, inc_by) def process(self, tup): word = tup.values[0] count = self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, count])
Make RedisWordCountBolt inherit direclty from Bolt
Make RedisWordCountBolt inherit direclty from Bolt
Python
apache-2.0
Parsely/streamparse,codywilbourn/streamparse,codywilbourn/streamparse,Parsely/streamparse
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(WordCountBolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by self.redis.zincrby("words", word, inc_by) Make RedisWordCountBolt inherit direclty from Bolt
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(Bolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by return self.redis.zincrby("words", word, inc_by) def process(self, tup): word = tup.values[0] count = self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, count])
<commit_before>from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(WordCountBolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by self.redis.zincrby("words", word, inc_by) <commit_msg>Make RedisWordCountBolt inherit direclty from Bolt<commit_after>
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(Bolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by return self.redis.zincrby("words", word, inc_by) def process(self, tup): word = tup.values[0] count = self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, count])
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(WordCountBolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by self.redis.zincrby("words", word, inc_by) Make RedisWordCountBolt inherit direclty from Boltfrom collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(Bolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by return self.redis.zincrby("words", word, inc_by) def process(self, tup): word = tup.values[0] count = self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, count])
<commit_before>from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(WordCountBolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by self.redis.zincrby("words", word, inc_by) <commit_msg>Make RedisWordCountBolt inherit direclty from Bolt<commit_after>from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += inc_by self.total += inc_by def process(self, tup): word = tup.values[0] self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, self.counter[word]]) class RedisWordCountBolt(Bolt): def initialize(self, conf, ctx): self.redis = StrictRedis() self.total = 0 def _increment(self, word, inc_by): self.total += inc_by return self.redis.zincrby("words", word, inc_by) def process(self, tup): word = tup.values[0] count = self._increment(word, 10 if word == "dog" else 1) if self.total % 1000 == 0: self.logger.info("counted %i words", self.total) self.emit([word, count])
15421e7e4a7964d77bcbed5549b9616cbb9de3c1
src/ansible/forms.py
src/ansible/forms.py
from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80}))
from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80}))
Add Field for Playbook filename
Add Field for Playbook filename
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80})) Add Field for Playbook filename
from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80}))
<commit_before>from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80})) <commit_msg>Add Field for Playbook filename<commit_after>
from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80}))
from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80})) Add Field for Playbook filenamefrom django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80}))
<commit_before>from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80})) <commit_msg>Add Field for Playbook filename<commit_after>from django import forms from django.conf import settings from django.forms import ModelForm from ansible.models import Playbook class AnsibleForm1(ModelForm): class Meta: model = Playbook fields = ['repository', 'username'] class AnsibleForm2(ModelForm): class Meta: model = Playbook fields = ['inventory', 'user'] class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) class PlaybookFileForm(forms.Form): filename = forms.CharField(label='Filename', max_length=100) playbook = forms.CharField(widget=forms.Textarea(attrs={'rows':30,'cols':80}))
655c2e6c91d70dd7985518ae19606ab407ce687f
lymph/core/declarations.py
lymph/core/declarations.py
def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): interface.components[self] = self.factory(interface, *self.args, **self.kwargs) def __get__(self, interface, cls): if interface is None: return self return interface.components[self]
def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): component = self.factory(interface, *self.args, **self.kwargs) interface.components[self] = component return component def __get__(self, interface, cls): if interface is None: return self return interface.components[self]
Return component instance from Declaration.install()
Return component instance from Declaration.install()
Python
apache-2.0
kstrempel/lymph,alazaro/lymph,lyudmildrx/lymph,alazaro/lymph,mouadino/lymph,mouadino/lymph,emulbreh/lymph,vpikulik/lymph,mamachanko/lymph,itakouna/lymph,lyudmildrx/lymph,mamachanko/lymph,emulbreh/lymph,itakouna/lymph,alazaro/lymph,lyudmildrx/lymph,mouadino/lymph,Drahflow/lymph,dushyant88/lymph,itakouna/lymph,mamachanko/lymph,deliveryhero/lymph,torte/lymph
def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): interface.components[self] = self.factory(interface, *self.args, **self.kwargs) def __get__(self, interface, cls): if interface is None: return self return interface.components[self] Return component instance from Declaration.install()
def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): component = self.factory(interface, *self.args, **self.kwargs) interface.components[self] = component return component def __get__(self, interface, cls): if interface is None: return self return interface.components[self]
<commit_before>def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): interface.components[self] = self.factory(interface, *self.args, **self.kwargs) def __get__(self, interface, cls): if interface is None: return self return interface.components[self] <commit_msg>Return component instance from Declaration.install()<commit_after>
def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): component = self.factory(interface, *self.args, **self.kwargs) interface.components[self] = component return component def __get__(self, interface, cls): if interface is None: return self return interface.components[self]
def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): interface.components[self] = self.factory(interface, *self.args, **self.kwargs) def __get__(self, interface, cls): if interface is None: return self return interface.components[self] Return component instance from Declaration.install()def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): component = self.factory(interface, *self.args, **self.kwargs) interface.components[self] = component return component def __get__(self, interface, cls): if interface is None: return self return interface.components[self]
<commit_before>def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): interface.components[self] = self.factory(interface, *self.args, **self.kwargs) def __get__(self, interface, cls): if interface is None: return self return interface.components[self] <commit_msg>Return component instance from Declaration.install()<commit_after>def declaration(*args, **kwargs): def decorator(factory): return Declaration(factory, *args, **kwargs) return decorator class Declaration(object): def __init__(self, factory, *args, **kwargs): self.factory = factory self.args = args self.kwargs = kwargs def install(self, interface): component = self.factory(interface, *self.args, **self.kwargs) interface.components[self] = component return component def __get__(self, interface, cls): if interface is None: return self return interface.components[self]
7892fd7421c39df3190c0b1f7223a8f2083d1893
common/lib/xmodule/xmodule/util/date_utils.py
common/lib/xmodule/xmodule/util/date_utils.py
import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if dt is not None and show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta
import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta
Remove extraneous test for already handled edge case
Remove extraneous test for already handled edge case
Python
agpl-3.0
EduPepperPD/pepper2013,pomegranited/edx-platform,dkarakats/edx-platform,B-MOOC/edx-platform,wwj718/edx-platform,ESOedX/edx-platform,mjirayu/sit_academy,abdoosh00/edraak,Edraak/edx-platform,Ayub-Khan/edx-platform,knehez/edx-platform,nikolas/edx-platform,Kalyzee/edx-platform,ahmadio/edx-platform,cognitiveclass/edx-platform,kursitet/edx-platform,sudheerchintala/LearnEraPlatForm,MakeHer/edx-platform,zadgroup/edx-platform,jzoldak/edx-platform,Edraak/circleci-edx-platform,msegado/edx-platform,jelugbo/tundex,morenopc/edx-platform,jamiefolsom/edx-platform,Edraak/circleci-edx-platform,appliedx/edx-platform,shubhdev/edxOnBaadal,morenopc/edx-platform,sameetb-cuelogic/edx-platform-test,mjg2203/edx-platform-seas,waheedahmed/edx-platform,martynovp/edx-platform,10clouds/edx-platform,jbzdak/edx-platform,ampax/edx-platform,TsinghuaX/edx-platform,CourseTalk/edx-platform,tanmaykm/edx-platform,mbareta/edx-platform-ft,halvertoluke/edx-platform,tiagochiavericosta/edx-platform,kmoocdev2/edx-platform,tiagochiavericosta/edx-platform,gsehub/edx-platform,ahmadiga/min_edx,nanolearningllc/edx-platform-cypress-2,lduarte1991/edx-platform,kmoocdev2/edx-platform,AkA84/edx-platform,jbassen/edx-platform,lduarte1991/edx-platform,zerobatu/edx-platform,rismalrv/edx-platform,Kalyzee/edx-platform,romain-li/edx-platform,wwj718/ANALYSE,bitifirefly/edx-platform,IITBinterns13/edx-platform-dev,tiagochiavericosta/edx-platform,jjmiranda/edx-platform,UOMx/edx-platform,beni55/edx-platform,MSOpenTech/edx-platform,JCBarahona/edX,Unow/edx-platform,beacloudgenius/edx-platform,LearnEra/LearnEraPlaftform,vasyarv/edx-platform,eduNEXT/edunext-platform,mcgachey/edx-platform,simbs/edx-platform,xuxiao19910803/edx-platform,beacloudgenius/edx-platform,vismartltd/edx-platform,nikolas/edx-platform,jruiperezv/ANALYSE,chauhanhardik/populo,jazztpt/edx-platform,sameetb-cuelogic/edx-platform-test,PepperPD/edx-pepper-platform,bdero/edx-platform,pabloborrego93/edx-platform,solashirai/edx-platform,Lektorium-LLC/edx-platform,cognitiveclass/edx-platform,carsongee/edx-platform,atsolakid/edx-platform,jjmiranda/edx-platform,amir-qayyum-khan/edx-platform,jolyonb/edx-platform,naresh21/synergetics-edx-platform,CourseTalk/edx-platform,don-github/edx-platform,ovnicraft/edx-platform,kmoocdev/edx-platform,utecuy/edx-platform,AkA84/edx-platform,knehez/edx-platform,chauhanhardik/populo_2,morenopc/edx-platform,teltek/edx-platform,kursitet/edx-platform,pomegranited/edx-platform,hkawasaki/kawasaki-aio8-1,ferabra/edx-platform,cselis86/edx-platform,OmarIthawi/edx-platform,fly19890211/edx-platform,tanmaykm/edx-platform,ampax/edx-platform,shubhdev/openedx,PepperPD/edx-pepper-platform,eemirtekin/edx-platform,pelikanchik/edx-platform,4eek/edx-platform,jswope00/GAI,doismellburning/edx-platform,OmarIthawi/edx-platform,wwj718/edx-platform,IITBinterns13/edx-platform-dev,sameetb-cuelogic/edx-platform-test,ferabra/edx-platform,dsajkl/123,iivic/BoiseStateX,pepeportela/edx-platform,msegado/edx-platform,eestay/edx-platform,teltek/edx-platform,pepeportela/edx-platform,ZLLab-Mooc/edx-platform,jazkarta/edx-platform,cpennington/edx-platform,edry/edx-platform,cecep-edu/edx-platform,fly19890211/edx-platform,cselis86/edx-platform,Unow/edx-platform,jzoldak/edx-platform,hkawasaki/kawasaki-aio8-2,miptliot/edx-platform,procangroup/edx-platform,praveen-pal/edx-platform,stvstnfrd/edx-platform,stvstnfrd/edx-platform,polimediaupv/edx-platform,jswope00/griffinx,franosincic/edx-platform,nanolearningllc/edx-platform-cypress,cecep-edu/edx-platform,vismartltd/edx-platform,dkarakats/edx-platform,devs1991/test_edx_docmode,eduNEXT/edunext-platform,torchingloom/edx-platform,nagyistoce/edx-platform,rationalAgent/edx-platform-custom,y12uc231/edx-platform,DefyVentures/edx-platform,carsongee/edx-platform,cselis86/edx-platform,LICEF/edx-platform,kalebhartje/schoolboost,arbrandes/edx-platform,Livit/Livit.Learn.EdX,bitifirefly/edx-platform,SivilTaram/edx-platform,synergeticsedx/deployment-wipro,yokose-ks/edx-platform,nanolearning/edx-platform,utecuy/edx-platform,analyseuc3m/ANALYSE-v1,RPI-OPENEDX/edx-platform,DNFcode/edx-platform,marcore/edx-platform,AkA84/edx-platform,procangroup/edx-platform,pelikanchik/edx-platform,shashank971/edx-platform,Kalyzee/edx-platform,vasyarv/edx-platform,mahendra-r/edx-platform,dkarakats/edx-platform,fly19890211/edx-platform,rhndg/openedx,martynovp/edx-platform,JioEducation/edx-platform,olexiim/edx-platform,proversity-org/edx-platform,synergeticsedx/deployment-wipro,J861449197/edx-platform,xingyepei/edx-platform,nagyistoce/edx-platform,ZLLab-Mooc/edx-platform,utecuy/edx-platform,defance/edx-platform,arifsetiawan/edx-platform,yokose-ks/edx-platform,Semi-global/edx-platform,kursitet/edx-platform,nanolearning/edx-platform,prarthitm/edxplatform,torchingloom/edx-platform,romain-li/edx-platform,motion2015/edx-platform,unicri/edx-platform,ovnicraft/edx-platform,synergeticsedx/deployment-wipro,UXE/local-edx,ahmadiga/min_edx,caesar2164/edx-platform,kxliugang/edx-platform,MakeHer/edx-platform,halvertoluke/edx-platform,adoosii/edx-platform,iivic/BoiseStateX,wwj718/ANALYSE,dsajkl/123,devs1991/test_edx_docmode,mtlchun/edx,jamiefolsom/edx-platform,dsajkl/reqiop,eemirtekin/edx-platform,chauhanhardik/populo_2,chauhanhardik/populo,pomegranited/edx-platform,eestay/edx-platform,Ayub-Khan/edx-platform,pku9104038/edx-platform,jolyonb/edx-platform,Endika/edx-platform,apigee/edx-platform,MSOpenTech/edx-platform,rismalrv/edx-platform,torchingloom/edx-platform,kmoocdev/edx-platform,hastexo/edx-platform,arbrandes/edx-platform,cyanna/edx-platform,DNFcode/edx-platform,xuxiao19910803/edx-platform,halvertoluke/edx-platform,deepsrijit1105/edx-platform,edx-solutions/edx-platform,shurihell/testasia,MSOpenTech/edx-platform,halvertoluke/edx-platform,sameetb-cuelogic/edx-platform-test,rue89-tech/edx-platform,xuxiao19910803/edx,JioEducation/edx-platform,don-github/edx-platform,morenopc/edx-platform,mahendra-r/edx-platform,mjirayu/sit_academy,waheedahmed/edx-platform,Semi-global/edx-platform,alu042/edx-platform,antoviaque/edx-platform,wwj718/ANALYSE,caesar2164/edx-platform,pepeportela/edx-platform,devs1991/test_edx_docmode,dcosentino/edx-platform,vikas1885/test1,SivilTaram/edx-platform,4eek/edx-platform,eestay/edx-platform,PepperPD/edx-pepper-platform,andyzsf/edx,Shrhawk/edx-platform,beacloudgenius/edx-platform,xuxiao19910803/edx,CredoReference/edx-platform,chand3040/cloud_that,zerobatu/edx-platform,hkawasaki/kawasaki-aio8-1,praveen-pal/edx-platform,beni55/edx-platform,ampax/edx-platform-backup,caesar2164/edx-platform,nanolearningllc/edx-platform-cypress,edry/edx-platform,y12uc231/edx-platform,10clouds/edx-platform,unicri/edx-platform,jonathan-beard/edx-platform,ahmadio/edx-platform,zofuthan/edx-platform,nagyistoce/edx-platform,unicri/edx-platform,nagyistoce/edx-platform,fintech-circle/edx-platform,waheedahmed/edx-platform,waheedahmed/edx-platform,gymnasium/edx-platform,kmoocdev/edx-platform,olexiim/edx-platform,etzhou/edx-platform,longmen21/edx-platform,ferabra/edx-platform,polimediaupv/edx-platform,valtech-mooc/edx-platform,iivic/BoiseStateX,a-parhom/edx-platform,hkawasaki/kawasaki-aio8-0,chand3040/cloud_that,ZLLab-Mooc/edx-platform,Lektorium-LLC/edx-platform,mitocw/edx-platform,pabloborrego93/edx-platform,inares/edx-platform,pku9104038/edx-platform,LearnEra/LearnEraPlaftform,jazkarta/edx-platform,xinjiguaike/edx-platform,unicri/edx-platform,leansoft/edx-platform,miptliot/edx-platform,Livit/Livit.Learn.EdX,WatanabeYasumasa/edx-platform,antonve/s4-project-mooc,JCBarahona/edX,defance/edx-platform,inares/edx-platform,hkawasaki/kawasaki-aio8-2,etzhou/edx-platform,jazkarta/edx-platform-for-isc,benpatterson/edx-platform,BehavioralInsightsTeam/edx-platform,ahmedaljazzar/edx-platform,EDUlib/edx-platform,EduPepperPDTesting/pepper2013-testing,IndonesiaX/edx-platform,antonve/s4-project-mooc,pelikanchik/edx-platform,beni55/edx-platform,ak2703/edx-platform,Edraak/edx-platform,abdoosh00/edx-rtl-final,dcosentino/edx-platform,Endika/edx-platform,hamzehd/edx-platform,edx/edx-platform,mushtaqak/edx-platform,devs1991/test_edx_docmode,peterm-itr/edx-platform,alexthered/kienhoc-platform,zhenzhai/edx-platform,tanmaykm/edx-platform,jbassen/edx-platform,edry/edx-platform,bitifirefly/edx-platform,kxliugang/edx-platform,kalebhartje/schoolboost,motion2015/a3,eduNEXT/edx-platform,praveen-pal/edx-platform,mjirayu/sit_academy,jbassen/edx-platform,louyihua/edx-platform,ahmedaljazzar/edx-platform,hkawasaki/kawasaki-aio8-1,RPI-OPENEDX/edx-platform,rationalAgent/edx-platform-custom,Edraak/edraak-platform,Semi-global/edx-platform,jamiefolsom/edx-platform,jamesblunt/edx-platform,hastexo/edx-platform,jswope00/GAI,raccoongang/edx-platform,naresh21/synergetics-edx-platform,raccoongang/edx-platform,olexiim/edx-platform,mahendra-r/edx-platform,ovnicraft/edx-platform,peterm-itr/edx-platform,eestay/edx-platform,xuxiao19910803/edx-platform,alu042/edx-platform,IONISx/edx-platform,leansoft/edx-platform,shabab12/edx-platform,ahmadio/edx-platform,MakeHer/edx-platform,rismalrv/edx-platform,defance/edx-platform,franosincic/edx-platform,y12uc231/edx-platform,chand3040/cloud_that,MSOpenTech/edx-platform,chudaol/edx-platform,RPI-OPENEDX/edx-platform,gymnasium/edx-platform,gsehub/edx-platform,shurihell/testasia,gsehub/edx-platform,fintech-circle/edx-platform,jbzdak/edx-platform,devs1991/test_edx_docmode,wwj718/edx-platform,jswope00/GAI,Lektorium-LLC/edx-platform,jamesblunt/edx-platform,morpheby/levelup-by,DefyVentures/edx-platform,chrisndodge/edx-platform,bigdatauniversity/edx-platform,bigdatauniversity/edx-platform,ubc/edx-platform,martynovp/edx-platform,TsinghuaX/edx-platform,shubhdev/openedx,alexthered/kienhoc-platform,mjirayu/sit_academy,jjmiranda/edx-platform,zubair-arbi/edx-platform,philanthropy-u/edx-platform,kxliugang/edx-platform,zerobatu/edx-platform,valtech-mooc/edx-platform,jruiperezv/ANALYSE,romain-li/edx-platform,knehez/edx-platform,angelapper/edx-platform,amir-qayyum-khan/edx-platform,DNFcode/edx-platform,Semi-global/edx-platform,ovnicraft/edx-platform,EduPepperPDTesting/pepper2013-testing,motion2015/a3,IONISx/edx-platform,EDUlib/edx-platform,zhenzhai/edx-platform,jazztpt/edx-platform,SivilTaram/edx-platform,CredoReference/edx-platform,devs1991/test_edx_docmode,Shrhawk/edx-platform,auferack08/edx-platform,romain-li/edx-platform,shubhdev/edx-platform,tiagochiavericosta/edx-platform,EduPepperPD/pepper2013,rationalAgent/edx-platform-custom,jolyonb/edx-platform,SivilTaram/edx-platform,kxliugang/edx-platform,bdero/edx-platform,tanmaykm/edx-platform,hmcmooc/muddx-platform,xinjiguaike/edx-platform,xingyepei/edx-platform,dcosentino/edx-platform,ESOedX/edx-platform,DefyVentures/edx-platform,utecuy/edx-platform,nanolearningllc/edx-platform-cypress-2,hmcmooc/muddx-platform,abdoosh00/edx-rtl-final,nttks/jenkins-test,valtech-mooc/edx-platform,xuxiao19910803/edx,shubhdev/edx-platform,motion2015/a3,hamzehd/edx-platform,dsajkl/reqiop,wwj718/edx-platform,arbrandes/edx-platform,jonathan-beard/edx-platform,ubc/edx-platform,knehez/edx-platform,longmen21/edx-platform,antonve/s4-project-mooc,nagyistoce/edx-platform,shashank971/edx-platform,jruiperezv/ANALYSE,angelapper/edx-platform,dsajkl/reqiop,hkawasaki/kawasaki-aio8-0,zubair-arbi/edx-platform,polimediaupv/edx-platform,stvstnfrd/edx-platform,mtlchun/edx,Ayub-Khan/edx-platform,JioEducation/edx-platform,ubc/edx-platform,angelapper/edx-platform,chand3040/cloud_that,openfun/edx-platform,ovnicraft/edx-platform,jbzdak/edx-platform,BehavioralInsightsTeam/edx-platform,abdoosh00/edx-rtl-final,pdehaye/theming-edx-platform,eemirtekin/edx-platform,andyzsf/edx,cognitiveclass/edx-platform,yokose-ks/edx-platform,ampax/edx-platform-backup,pelikanchik/edx-platform,SravanthiSinha/edx-platform,itsjeyd/edx-platform,deepsrijit1105/edx-platform,EDUlib/edx-platform,zhenzhai/edx-platform,xuxiao19910803/edx-platform,jazkarta/edx-platform-for-isc,atsolakid/edx-platform,olexiim/edx-platform,eduNEXT/edx-platform,peterm-itr/edx-platform,WatanabeYasumasa/edx-platform,valtech-mooc/edx-platform,shubhdev/edxOnBaadal,Shrhawk/edx-platform,torchingloom/edx-platform,louyihua/edx-platform,mcgachey/edx-platform,appsembler/edx-platform,RPI-OPENEDX/edx-platform,jelugbo/tundex,atsolakid/edx-platform,edry/edx-platform,hamzehd/edx-platform,pomegranited/edx-platform,arbrandes/edx-platform,CredoReference/edx-platform,nttks/jenkins-test,PepperPD/edx-pepper-platform,mitocw/edx-platform,WatanabeYasumasa/edx-platform,hamzehd/edx-platform,etzhou/edx-platform,edx-solutions/edx-platform,Edraak/circleci-edx-platform,xuxiao19910803/edx,kalebhartje/schoolboost,zerobatu/edx-platform,hastexo/edx-platform,Edraak/edx-platform,kursitet/edx-platform,LICEF/edx-platform,jamesblunt/edx-platform,SravanthiSinha/edx-platform,B-MOOC/edx-platform,4eek/edx-platform,openfun/edx-platform,syjeon/new_edx,chudaol/edx-platform,xingyepei/edx-platform,mcgachey/edx-platform,msegado/edx-platform,eemirtekin/edx-platform,wwj718/ANALYSE,analyseuc3m/ANALYSE-v1,EduPepperPDTesting/pepper2013-testing,motion2015/a3,Livit/Livit.Learn.EdX,kalebhartje/schoolboost,CourseTalk/edx-platform,apigee/edx-platform,motion2015/edx-platform,ahmadiga/min_edx,dcosentino/edx-platform,rue89-tech/edx-platform,shubhdev/edx-platform,J861449197/edx-platform,Ayub-Khan/edx-platform,chauhanhardik/populo,mbareta/edx-platform-ft,nttks/jenkins-test,shubhdev/edxOnBaadal,pomegranited/edx-platform,jazkarta/edx-platform-for-isc,syjeon/new_edx,zadgroup/edx-platform,Softmotions/edx-platform,philanthropy-u/edx-platform,rue89-tech/edx-platform,chrisndodge/edx-platform,arifsetiawan/edx-platform,edry/edx-platform,caesar2164/edx-platform,IITBinterns13/edx-platform-dev,arifsetiawan/edx-platform,mushtaqak/edx-platform,cecep-edu/edx-platform,utecuy/edx-platform,vasyarv/edx-platform,kalebhartje/schoolboost,10clouds/edx-platform,nikolas/edx-platform,zofuthan/edx-platform,polimediaupv/edx-platform,rationalAgent/edx-platform-custom,tiagochiavericosta/edx-platform,teltek/edx-platform,alu042/edx-platform,pku9104038/edx-platform,AkA84/edx-platform,dcosentino/edx-platform,chand3040/cloud_that,nttks/edx-platform,apigee/edx-platform,cpennington/edx-platform,playm2mboy/edx-platform,eduNEXT/edx-platform,philanthropy-u/edx-platform,nttks/edx-platform,leansoft/edx-platform,bdero/edx-platform,zadgroup/edx-platform,EduPepperPDTesting/pepper2013-testing,MakeHer/edx-platform,franosincic/edx-platform,Softmotions/edx-platform,doganov/edx-platform,rhndg/openedx,apigee/edx-platform,syjeon/new_edx,jbassen/edx-platform,10clouds/edx-platform,marcore/edx-platform,pdehaye/theming-edx-platform,kamalx/edx-platform,abdoosh00/edx-rtl-final,appliedx/edx-platform,alexthered/kienhoc-platform,ESOedX/edx-platform,kamalx/edx-platform,chudaol/edx-platform,polimediaupv/edx-platform,jamesblunt/edx-platform,rhndg/openedx,doismellburning/edx-platform,adoosii/edx-platform,zofuthan/edx-platform,DNFcode/edx-platform,ZLLab-Mooc/edx-platform,analyseuc3m/ANALYSE-v1,morpheby/levelup-by,ahmadiga/min_edx,chauhanhardik/populo_2,vikas1885/test1,prarthitm/edxplatform,fly19890211/edx-platform,J861449197/edx-platform,rue89-tech/edx-platform,jazkarta/edx-platform,unicri/edx-platform,xingyepei/edx-platform,OmarIthawi/edx-platform,EduPepperPDTesting/pepper2013-testing,jamiefolsom/edx-platform,kmoocdev2/edx-platform,dsajkl/reqiop,chudaol/edx-platform,jazkarta/edx-platform,antoviaque/edx-platform,eduNEXT/edunext-platform,dkarakats/edx-platform,LearnEra/LearnEraPlaftform,adoosii/edx-platform,playm2mboy/edx-platform,hkawasaki/kawasaki-aio8-0,nttks/edx-platform,a-parhom/edx-platform,antonve/s4-project-mooc,ak2703/edx-platform,shabab12/edx-platform,jbzdak/edx-platform,CredoReference/edx-platform,openfun/edx-platform,jzoldak/edx-platform,ahmedaljazzar/edx-platform,don-github/edx-platform,cyanna/edx-platform,mitocw/edx-platform,ak2703/edx-platform,bitifirefly/edx-platform,gsehub/edx-platform,beni55/edx-platform,jazkarta/edx-platform-for-isc,chauhanhardik/populo,DefyVentures/edx-platform,Edraak/circleci-edx-platform,appliedx/edx-platform,B-MOOC/edx-platform,cyanna/edx-platform,jswope00/GAI,shubhdev/edxOnBaadal,JCBarahona/edX,mbareta/edx-platform-ft,fintech-circle/edx-platform,vikas1885/test1,chauhanhardik/populo_2,knehez/edx-platform,Edraak/edx-platform,eduNEXT/edunext-platform,kamalx/edx-platform,motion2015/edx-platform,longmen21/edx-platform,doismellburning/edx-platform,cpennington/edx-platform,Kalyzee/edx-platform,bigdatauniversity/edx-platform,don-github/edx-platform,leansoft/edx-platform,waheedahmed/edx-platform,LICEF/edx-platform,gymnasium/edx-platform,yokose-ks/edx-platform,procangroup/edx-platform,SivilTaram/edx-platform,Stanford-Online/edx-platform,Unow/edx-platform,kmoocdev/edx-platform,vismartltd/edx-platform,dsajkl/123,hkawasaki/kawasaki-aio8-2,jelugbo/tundex,ak2703/edx-platform,shurihell/testasia,jelugbo/tundex,torchingloom/edx-platform,antoviaque/edx-platform,mcgachey/edx-platform,sameetb-cuelogic/edx-platform-test,Edraak/edx-platform,ubc/edx-platform,jonathan-beard/edx-platform,benpatterson/edx-platform,wwj718/ANALYSE,shashank971/edx-platform,jonathan-beard/edx-platform,solashirai/edx-platform,shurihell/testasia,carsongee/edx-platform,doganov/edx-platform,hkawasaki/kawasaki-aio8-2,playm2mboy/edx-platform,WatanabeYasumasa/edx-platform,kxliugang/edx-platform,AkA84/edx-platform,appliedx/edx-platform,UOMx/edx-platform,miptliot/edx-platform,philanthropy-u/edx-platform,BehavioralInsightsTeam/edx-platform,ampax/edx-platform-backup,hkawasaki/kawasaki-aio8-0,IndonesiaX/edx-platform,bigdatauniversity/edx-platform,LICEF/edx-platform,ESOedX/edx-platform,msegado/edx-platform,mjirayu/sit_academy,iivic/BoiseStateX,beacloudgenius/edx-platform,beacloudgenius/edx-platform,simbs/edx-platform,doismellburning/edx-platform,B-MOOC/edx-platform,kmoocdev2/edx-platform,lduarte1991/edx-platform,nanolearning/edx-platform,dsajkl/123,auferack08/edx-platform,dsajkl/123,edx/edx-platform,solashirai/edx-platform,simbs/edx-platform,Endika/edx-platform,mahendra-r/edx-platform,miptliot/edx-platform,msegado/edx-platform,deepsrijit1105/edx-platform,zofuthan/edx-platform,shubhdev/openedx,JCBarahona/edX,itsjeyd/edx-platform,jzoldak/edx-platform,Edraak/circleci-edx-platform,rue89-tech/edx-platform,simbs/edx-platform,ahmadio/edx-platform,benpatterson/edx-platform,Softmotions/edx-platform,vasyarv/edx-platform,ak2703/edx-platform,vismartltd/edx-platform,solashirai/edx-platform,zerobatu/edx-platform,chauhanhardik/populo_2,cpennington/edx-platform,adoosii/edx-platform,marcore/edx-platform,devs1991/test_edx_docmode,olexiim/edx-platform,inares/edx-platform,ahmadio/edx-platform,vikas1885/test1,zofuthan/edx-platform,kmoocdev/edx-platform,a-parhom/edx-platform,nanolearningllc/edx-platform-cypress,pdehaye/theming-edx-platform,zubair-arbi/edx-platform,TeachAtTUM/edx-platform,Unow/edx-platform,chudaol/edx-platform,zhenzhai/edx-platform,y12uc231/edx-platform,jruiperezv/ANALYSE,EDUlib/edx-platform,Stanford-Online/edx-platform,Edraak/edraak-platform,IndonesiaX/edx-platform,naresh21/synergetics-edx-platform,appliedx/edx-platform,mjg2203/edx-platform-seas,Endika/edx-platform,IONISx/edx-platform,openfun/edx-platform,xuxiao19910803/edx,valtech-mooc/edx-platform,J861449197/edx-platform,BehavioralInsightsTeam/edx-platform,naresh21/synergetics-edx-platform,cyanna/edx-platform,cyanna/edx-platform,hmcmooc/muddx-platform,xinjiguaike/edx-platform,Shrhawk/edx-platform,bdero/edx-platform,raccoongang/edx-platform,longmen21/edx-platform,romain-li/edx-platform,abdoosh00/edraak,nanolearningllc/edx-platform-cypress-2,kursitet/edx-platform,morenopc/edx-platform,UXE/local-edx,edx/edx-platform,doganov/edx-platform,bitifirefly/edx-platform,zadgroup/edx-platform,mbareta/edx-platform-ft,auferack08/edx-platform,mushtaqak/edx-platform,LICEF/edx-platform,shurihell/testasia,prarthitm/edxplatform,rismalrv/edx-platform,appsembler/edx-platform,pku9104038/edx-platform,nikolas/edx-platform,fly19890211/edx-platform,simbs/edx-platform,MakeHer/edx-platform,hkawasaki/kawasaki-aio8-1,rationalAgent/edx-platform-custom,carsongee/edx-platform,PepperPD/edx-pepper-platform,ferabra/edx-platform,jbzdak/edx-platform,shubhdev/openedx,benpatterson/edx-platform,UOMx/edx-platform,OmarIthawi/edx-platform,Edraak/edraak-platform,Edraak/edraak-platform,dkarakats/edx-platform,mtlchun/edx,yokose-ks/edx-platform,Kalyzee/edx-platform,vasyarv/edx-platform,nanolearningllc/edx-platform-cypress,xuxiao19910803/edx-platform,cselis86/edx-platform,cognitiveclass/edx-platform,fintech-circle/edx-platform,Stanford-Online/edx-platform,EduPepperPDTesting/pepper2013-testing,RPI-OPENEDX/edx-platform,shashank971/edx-platform,jamesblunt/edx-platform,IONISx/edx-platform,proversity-org/edx-platform,jazkarta/edx-platform-for-isc,syjeon/new_edx,Lektorium-LLC/edx-platform,chrisndodge/edx-platform,ampax/edx-platform-backup,inares/edx-platform,eestay/edx-platform,kamalx/edx-platform,mjg2203/edx-platform-seas,rismalrv/edx-platform,procangroup/edx-platform,iivic/BoiseStateX,andyzsf/edx,TeachAtTUM/edx-platform,SravanthiSinha/edx-platform,LearnEra/LearnEraPlaftform,pdehaye/theming-edx-platform,TsinghuaX/edx-platform,louyihua/edx-platform,jazztpt/edx-platform,doganov/edx-platform,doismellburning/edx-platform,jazkarta/edx-platform,Stanford-Online/edx-platform,ampax/edx-platform-backup,itsjeyd/edx-platform,cselis86/edx-platform,IndonesiaX/edx-platform,DNFcode/edx-platform,hastexo/edx-platform,SravanthiSinha/edx-platform,UXE/local-edx,sudheerchintala/LearnEraPlatForm,TeachAtTUM/edx-platform,Ayub-Khan/edx-platform,Semi-global/edx-platform,morpheby/levelup-by,beni55/edx-platform,jelugbo/tundex,shubhdev/openedx,louyihua/edx-platform,eemirtekin/edx-platform,rhndg/openedx,jonathan-beard/edx-platform,gymnasium/edx-platform,UXE/local-edx,andyzsf/edx,B-MOOC/edx-platform,cecep-edu/edx-platform,kamalx/edx-platform,antonve/s4-project-mooc,zubair-arbi/edx-platform,mtlchun/edx,appsembler/edx-platform,ZLLab-Mooc/edx-platform,jswope00/griffinx,hmcmooc/muddx-platform,teltek/edx-platform,nanolearningllc/edx-platform-cypress-2,abdoosh00/edraak,angelapper/edx-platform,alexthered/kienhoc-platform,mjg2203/edx-platform-seas,vikas1885/test1,solashirai/edx-platform,jazztpt/edx-platform,halvertoluke/edx-platform,CourseTalk/edx-platform,synergeticsedx/deployment-wipro,hamzehd/edx-platform,edx-solutions/edx-platform,peterm-itr/edx-platform,a-parhom/edx-platform,lduarte1991/edx-platform,jswope00/griffinx,martynovp/edx-platform,jswope00/griffinx,pabloborrego93/edx-platform,abdoosh00/edraak,longmen21/edx-platform,kmoocdev2/edx-platform,sudheerchintala/LearnEraPlatForm,shabab12/edx-platform,JCBarahona/edX,appsembler/edx-platform,marcore/edx-platform,don-github/edx-platform,pabloborrego93/edx-platform,y12uc231/edx-platform,4eek/edx-platform,playm2mboy/edx-platform,nttks/jenkins-test,playm2mboy/edx-platform,shubhdev/edx-platform,benpatterson/edx-platform,xinjiguaike/edx-platform,EduPepperPD/pepper2013,xingyepei/edx-platform,antoviaque/edx-platform,amir-qayyum-khan/edx-platform,shubhdev/edxOnBaadal,praveen-pal/edx-platform,vismartltd/edx-platform,Livit/Livit.Learn.EdX,jolyonb/edx-platform,xinjiguaike/edx-platform,jbassen/edx-platform,TeachAtTUM/edx-platform,alu042/edx-platform,devs1991/test_edx_docmode,mahendra-r/edx-platform,nanolearning/edx-platform,rhndg/openedx,etzhou/edx-platform,jjmiranda/edx-platform,nanolearningllc/edx-platform-cypress,atsolakid/edx-platform,shubhdev/edx-platform,analyseuc3m/ANALYSE-v1,deepsrijit1105/edx-platform,ubc/edx-platform,nanolearningllc/edx-platform-cypress-2,jswope00/griffinx,TsinghuaX/edx-platform,ahmedaljazzar/edx-platform,zubair-arbi/edx-platform,leansoft/edx-platform,morpheby/levelup-by,arifsetiawan/edx-platform,raccoongang/edx-platform,mtlchun/edx,stvstnfrd/edx-platform,etzhou/edx-platform,mushtaqak/edx-platform,arifsetiawan/edx-platform,4eek/edx-platform,nttks/jenkins-test,bigdatauniversity/edx-platform,JioEducation/edx-platform,DefyVentures/edx-platform,itsjeyd/edx-platform,edx/edx-platform,eduNEXT/edx-platform,atsolakid/edx-platform,mushtaqak/edx-platform,adoosii/edx-platform,ferabra/edx-platform,inares/edx-platform,openfun/edx-platform,alexthered/kienhoc-platform,IONISx/edx-platform,doganov/edx-platform,pepeportela/edx-platform,J861449197/edx-platform,sudheerchintala/LearnEraPlatForm,shabab12/edx-platform,amir-qayyum-khan/edx-platform,UOMx/edx-platform,shashank971/edx-platform,EduPepperPD/pepper2013,cognitiveclass/edx-platform,MSOpenTech/edx-platform,IITBinterns13/edx-platform-dev,proversity-org/edx-platform,proversity-org/edx-platform,martynovp/edx-platform,auferack08/edx-platform,cecep-edu/edx-platform,jazztpt/edx-platform,motion2015/a3,IndonesiaX/edx-platform,zadgroup/edx-platform,Softmotions/edx-platform,nikolas/edx-platform,franosincic/edx-platform,mcgachey/edx-platform,chrisndodge/edx-platform,Softmotions/edx-platform,zhenzhai/edx-platform,nttks/edx-platform,jruiperezv/ANALYSE,nanolearning/edx-platform,edx-solutions/edx-platform,EduPepperPD/pepper2013,ahmadiga/min_edx,ampax/edx-platform,franosincic/edx-platform,chauhanhardik/populo,defance/edx-platform,ampax/edx-platform,wwj718/edx-platform,motion2015/edx-platform,motion2015/edx-platform,nttks/edx-platform,Shrhawk/edx-platform,SravanthiSinha/edx-platform,jamiefolsom/edx-platform,mitocw/edx-platform,prarthitm/edxplatform
import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if dt is not None and show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta Remove extraneous test for already handled edge case
import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta
<commit_before>import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if dt is not None and show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta <commit_msg>Remove extraneous test for already handled edge case<commit_after>
import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta
import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if dt is not None and show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta Remove extraneous test for already handled edge caseimport datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta
<commit_before>import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if dt is not None and show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta <commit_msg>Remove extraneous test for already handled edge case<commit_after>import datetime def get_default_time_display(dt, show_timezone=True): """ Converts a datetime to a string representation. This is the default representation used in Studio and LMS. It is of the form "Apr 09, 2013 at 16:00" or "Apr 09, 2013 at 16:00 UTC", depending on the value of show_timezone. If None is passed in for dt, an empty string will be returned. The default value of show_timezone is True. """ if dt is None: return "" timezone = "" if show_timezone: if dt.tzinfo is not None: try: timezone = " " + dt.tzinfo.tzname(dt) except NotImplementedError: timezone = dt.strftime('%z') else: timezone = " UTC" return dt.strftime("%b %d, %Y at %H:%M") + timezone def almost_same_datetime(dt1, dt2, allowed_delta=datetime.timedelta(minutes=1)): """ Returns true if these are w/in a minute of each other. (in case secs saved to db or timezone aren't same) :param dt1: :param dt2: """ return abs(dt1 - dt2) < allowed_delta
7a4d878dda0b9b947a5991be63183e247ad4e022
grammpy_transforms/UnreachableSymbolsRemove/unreachableSymbolsRemove.py
grammpy_transforms/UnreachableSymbolsRemove/unreachableSymbolsRemove.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from copy import copy def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) raise NotImplementedError()
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from grammpy.exceptions import NotNonterminalException from copy import copy class StartSymbolNotSpecifiedException(Exception): pass def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) # Check if start symbol is set if not grammar.start_isSet(): raise StartSymbolNotSpecifiedException() # Create process sets reachable = {grammar.start_get()} rules = grammar.rules() # Begin iterations while True: # Create sets for current iteration active = reachable.copy() processedRules = [] # Loop rest of rules for rule in rules: # If left part of rule already in reachable symbols if rule.fromSymbol in reachable: # Set symbols as reachable processedRules.append(rule) for symbol in rule.right: active.add(symbol) # End of rules loop # Remove processed rules for item in processedRules: rules.remove(item) # If current and previous iterations are same, than end iterations if active == reachable: break reachable = active # End of iterations # Set symbols to remove allSymbols = set(grammar.nonterms()).union(set(x.s for x in grammar.terms())) for symbol in allSymbols.difference(reachable): try: grammar.remove_nonterm(symbol) except NotNonterminalException: grammar.remove_term(symbol) return grammar
Implement removing of unreachable symbols
Implement removing of unreachable symbols
Python
mit
PatrikValkovic/grammpy
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from copy import copy def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) raise NotImplementedError()Implement removing of unreachable symbols
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from grammpy.exceptions import NotNonterminalException from copy import copy class StartSymbolNotSpecifiedException(Exception): pass def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) # Check if start symbol is set if not grammar.start_isSet(): raise StartSymbolNotSpecifiedException() # Create process sets reachable = {grammar.start_get()} rules = grammar.rules() # Begin iterations while True: # Create sets for current iteration active = reachable.copy() processedRules = [] # Loop rest of rules for rule in rules: # If left part of rule already in reachable symbols if rule.fromSymbol in reachable: # Set symbols as reachable processedRules.append(rule) for symbol in rule.right: active.add(symbol) # End of rules loop # Remove processed rules for item in processedRules: rules.remove(item) # If current and previous iterations are same, than end iterations if active == reachable: break reachable = active # End of iterations # Set symbols to remove allSymbols = set(grammar.nonterms()).union(set(x.s for x in grammar.terms())) for symbol in allSymbols.difference(reachable): try: grammar.remove_nonterm(symbol) except NotNonterminalException: grammar.remove_term(symbol) return grammar
<commit_before>#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from copy import copy def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) raise NotImplementedError()<commit_msg>Implement removing of unreachable symbols<commit_after>
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from grammpy.exceptions import NotNonterminalException from copy import copy class StartSymbolNotSpecifiedException(Exception): pass def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) # Check if start symbol is set if not grammar.start_isSet(): raise StartSymbolNotSpecifiedException() # Create process sets reachable = {grammar.start_get()} rules = grammar.rules() # Begin iterations while True: # Create sets for current iteration active = reachable.copy() processedRules = [] # Loop rest of rules for rule in rules: # If left part of rule already in reachable symbols if rule.fromSymbol in reachable: # Set symbols as reachable processedRules.append(rule) for symbol in rule.right: active.add(symbol) # End of rules loop # Remove processed rules for item in processedRules: rules.remove(item) # If current and previous iterations are same, than end iterations if active == reachable: break reachable = active # End of iterations # Set symbols to remove allSymbols = set(grammar.nonterms()).union(set(x.s for x in grammar.terms())) for symbol in allSymbols.difference(reachable): try: grammar.remove_nonterm(symbol) except NotNonterminalException: grammar.remove_term(symbol) return grammar
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from copy import copy def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) raise NotImplementedError()Implement removing of unreachable symbols#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from grammpy.exceptions import NotNonterminalException from copy import copy class StartSymbolNotSpecifiedException(Exception): pass def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) # Check if start symbol is set if not grammar.start_isSet(): raise StartSymbolNotSpecifiedException() # Create process sets reachable = {grammar.start_get()} rules = grammar.rules() # Begin iterations while True: # Create sets for current iteration active = reachable.copy() processedRules = [] # Loop rest of rules for rule in rules: # If left part of rule already in reachable symbols if rule.fromSymbol in reachable: # Set symbols as reachable processedRules.append(rule) for symbol in rule.right: active.add(symbol) # End of rules loop # Remove processed rules for item in processedRules: rules.remove(item) # If current and previous iterations are same, than end iterations if active == reachable: break reachable = active # End of iterations # Set symbols to remove allSymbols = set(grammar.nonterms()).union(set(x.s for x in grammar.terms())) for symbol in allSymbols.difference(reachable): try: grammar.remove_nonterm(symbol) except NotNonterminalException: grammar.remove_term(symbol) return grammar
<commit_before>#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from copy import copy def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) raise NotImplementedError()<commit_msg>Implement removing of unreachable symbols<commit_after>#!/usr/bin/env python """ :Author Patrik Valkovic :Created 17.08.207 13:29 :Licence GNUv3 Part of grammpy-transforms """ from grammpy import Grammar from grammpy.exceptions import NotNonterminalException from copy import copy class StartSymbolNotSpecifiedException(Exception): pass def remove_unreachable_symbols(grammar: Grammar, transform_grammar=False) -> Grammar: # Copy if required if transform_grammar is False: grammar = copy(grammar) # Check if start symbol is set if not grammar.start_isSet(): raise StartSymbolNotSpecifiedException() # Create process sets reachable = {grammar.start_get()} rules = grammar.rules() # Begin iterations while True: # Create sets for current iteration active = reachable.copy() processedRules = [] # Loop rest of rules for rule in rules: # If left part of rule already in reachable symbols if rule.fromSymbol in reachable: # Set symbols as reachable processedRules.append(rule) for symbol in rule.right: active.add(symbol) # End of rules loop # Remove processed rules for item in processedRules: rules.remove(item) # If current and previous iterations are same, than end iterations if active == reachable: break reachable = active # End of iterations # Set symbols to remove allSymbols = set(grammar.nonterms()).union(set(x.s for x in grammar.terms())) for symbol in allSymbols.difference(reachable): try: grammar.remove_nonterm(symbol) except NotNonterminalException: grammar.remove_term(symbol) return grammar
02363de7bdd7a069243da09248816f3caf38b2e6
scripts/get-month.py
scripts/get-month.py
#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/about-us/cjis/nics/reports/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m"))
#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/file-repository/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m"))
Update "Active Records" PDF URL
Update "Active Records" PDF URL
Python
mit
BuzzFeedNews/nics-firearm-background-checks
#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/about-us/cjis/nics/reports/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m")) Update "Active Records" PDF URL
#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/file-repository/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m"))
<commit_before>#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/about-us/cjis/nics/reports/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m")) <commit_msg>Update "Active Records" PDF URL<commit_after>
#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/file-repository/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m"))
#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/about-us/cjis/nics/reports/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m")) Update "Active Records" PDF URL#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/file-repository/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m"))
<commit_before>#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/about-us/cjis/nics/reports/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m")) <commit_msg>Update "Active Records" PDF URL<commit_after>#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/file-repository/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m"))
7f006958e97cf5cc972d9f8340b327ea7508e03d
packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/TestCommandScriptImmediateOutput.py
packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/TestCommandScriptImmediateOutput.py
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are
Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@257656 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False) Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@257656 91177308-0d34-0410-b5e6-96231b3b80d8
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
<commit_before>""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False) <commit_msg>Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@257656 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after>
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False) Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@257656 91177308-0d34-0410-b5e6-96231b3b80d8""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
<commit_before>""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False) <commit_msg>Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@257656 91177308-0d34-0410-b5e6-96231b3b80d8<commit_after>""" Test that LLDB correctly allows scripted commands to set an immediate output file """ from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
bab4f346cef626f29c67cc214b03db2475ef6b64
scriptcore/process/popen.py
scriptcore/process/popen.py
from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None, timeout=None): """ Communicate :param input: Optional input :param timeout: Optional timeout :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input, timeout=timeout) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False
from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None): """ Communicate :param input: Optional input :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False
Fix error in communicate function.
Fix error in communicate function.
Python
apache-2.0
LowieHuyghe/script-core
from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None, timeout=None): """ Communicate :param input: Optional input :param timeout: Optional timeout :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input, timeout=timeout) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False Fix error in communicate function.
from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None): """ Communicate :param input: Optional input :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False
<commit_before> from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None, timeout=None): """ Communicate :param input: Optional input :param timeout: Optional timeout :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input, timeout=timeout) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False <commit_msg>Fix error in communicate function.<commit_after>
from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None): """ Communicate :param input: Optional input :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False
from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None, timeout=None): """ Communicate :param input: Optional input :param timeout: Optional timeout :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input, timeout=timeout) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False Fix error in communicate function. from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None): """ Communicate :param input: Optional input :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False
<commit_before> from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None, timeout=None): """ Communicate :param input: Optional input :param timeout: Optional timeout :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input, timeout=timeout) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False <commit_msg>Fix error in communicate function.<commit_after> from subprocess import Popen as BasePopen class Popen(BasePopen): def communicate(self, input=None): """ Communicate :param input: Optional input :return: Out, err, exitcode """ out, err = super(Popen, self).communicate(input=input) out = out.strip().split('\n') err = err.strip().split('\n') return out, err, self.returncode def is_running(self): """ Running :return: Boolean """ return True if self.poll() is None else False
fb9ca96431a4f72135245705359eb1f6d340a536
moksha/api/hub/__init__.py
moksha/api/hub/__init__.py
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import *
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import * from moksha.hub.reactor import reactor from moksha.hub.hub import MokshaHub
Make the MokshaHub and reactor available in the moksha.api.hub module
Make the MokshaHub and reactor available in the moksha.api.hub module
Python
apache-2.0
lmacken/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,lmacken/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,ralphbean/moksha,ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import * Make the MokshaHub and reactor available in the moksha.api.hub module
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import * from moksha.hub.reactor import reactor from moksha.hub.hub import MokshaHub
<commit_before># This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import * <commit_msg>Make the MokshaHub and reactor available in the moksha.api.hub module<commit_after>
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import * from moksha.hub.reactor import reactor from moksha.hub.hub import MokshaHub
# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import * Make the MokshaHub and reactor available in the moksha.api.hub module# This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import * from moksha.hub.reactor import reactor from moksha.hub.hub import MokshaHub
<commit_before># This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import * <commit_msg>Make the MokshaHub and reactor available in the moksha.api.hub module<commit_after># This file is part of Moksha. # Copyright (C) 2008-2009 Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from consumer import * from hub import * from moksha.hub.reactor import reactor from moksha.hub.hub import MokshaHub
fcff4e1d25abb173870fffdd0a0d1f63aca7fccf
numpy/_array_api/dtypes.py
numpy/_array_api/dtypes.py
from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64 # Note: This name is changed from .. import bool_ as bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
Fix the bool name in the array API namespace
Fix the bool name in the array API namespace
Python
bsd-3-clause
mhvk/numpy,pdebuyl/numpy,mhvk/numpy,jakirkham/numpy,seberg/numpy,mattip/numpy,jakirkham/numpy,numpy/numpy,numpy/numpy,endolith/numpy,endolith/numpy,charris/numpy,rgommers/numpy,endolith/numpy,mattip/numpy,charris/numpy,pdebuyl/numpy,rgommers/numpy,simongibbons/numpy,charris/numpy,seberg/numpy,jakirkham/numpy,simongibbons/numpy,anntzer/numpy,charris/numpy,pdebuyl/numpy,mattip/numpy,simongibbons/numpy,numpy/numpy,jakirkham/numpy,mattip/numpy,seberg/numpy,rgommers/numpy,pdebuyl/numpy,jakirkham/numpy,numpy/numpy,anntzer/numpy,endolith/numpy,simongibbons/numpy,anntzer/numpy,simongibbons/numpy,mhvk/numpy,seberg/numpy,mhvk/numpy,anntzer/numpy,mhvk/numpy,rgommers/numpy
from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool'] Fix the bool name in the array API namespace
from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64 # Note: This name is changed from .. import bool_ as bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
<commit_before>from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool'] <commit_msg>Fix the bool name in the array API namespace<commit_after>
from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64 # Note: This name is changed from .. import bool_ as bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool'] Fix the bool name in the array API namespacefrom .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64 # Note: This name is changed from .. import bool_ as bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
<commit_before>from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool'] <commit_msg>Fix the bool name in the array API namespace<commit_after>from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64 # Note: This name is changed from .. import bool_ as bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
4af9f51da1557715a1eaaac1c2828de4dfe5b7c7
lib/globals.py
lib/globals.py
"""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A list containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ["up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel"]
"""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A tuple containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. DEFAULT_ACTIONS A tuple of Strings, containing the names of all Actions that every character should have, such as walking, blocking, and jumping. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ("up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel") DEFAULT_NAMES = ('intro', 'stand', 'walk', 'crouch_down', 'crouching_idle', 'jump_up', 'jump_forward', 'jump_back', 'block_standing', 'block_high', 'block_low', 'standing_recoil', 'crouching_recoil', 'jumping_recoil', 'tripped', 'launched', 'falling', 'knockdown', 'recover', 'dizzy', 'chip_ko', 'victory')
Add DEFAULT_NAMES as a global tuple constant
Add DEFAULT_NAMES as a global tuple constant They will be referenced in various places in the game and should not be subject to change. INPUT_NAMES was also changed into a tuple for guaranteed immutability.
Python
unlicense
MarquisLP/Sidewalk-Champion
"""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A list containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ["up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel"] Add DEFAULT_NAMES as a global tuple constant They will be referenced in various places in the game and should not be subject to change. INPUT_NAMES was also changed into a tuple for guaranteed immutability.
"""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A tuple containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. DEFAULT_ACTIONS A tuple of Strings, containing the names of all Actions that every character should have, such as walking, blocking, and jumping. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ("up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel") DEFAULT_NAMES = ('intro', 'stand', 'walk', 'crouch_down', 'crouching_idle', 'jump_up', 'jump_forward', 'jump_back', 'block_standing', 'block_high', 'block_low', 'standing_recoil', 'crouching_recoil', 'jumping_recoil', 'tripped', 'launched', 'falling', 'knockdown', 'recover', 'dizzy', 'chip_ko', 'victory')
<commit_before>"""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A list containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ["up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel"] <commit_msg>Add DEFAULT_NAMES as a global tuple constant They will be referenced in various places in the game and should not be subject to change. INPUT_NAMES was also changed into a tuple for guaranteed immutability.<commit_after>
"""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A tuple containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. DEFAULT_ACTIONS A tuple of Strings, containing the names of all Actions that every character should have, such as walking, blocking, and jumping. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ("up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel") DEFAULT_NAMES = ('intro', 'stand', 'walk', 'crouch_down', 'crouching_idle', 'jump_up', 'jump_forward', 'jump_back', 'block_standing', 'block_high', 'block_low', 'standing_recoil', 'crouching_recoil', 'jumping_recoil', 'tripped', 'launched', 'falling', 'knockdown', 'recover', 'dizzy', 'chip_ko', 'victory')
"""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A list containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ["up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel"] Add DEFAULT_NAMES as a global tuple constant They will be referenced in various places in the game and should not be subject to change. INPUT_NAMES was also changed into a tuple for guaranteed immutability."""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A tuple containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. DEFAULT_ACTIONS A tuple of Strings, containing the names of all Actions that every character should have, such as walking, blocking, and jumping. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ("up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel") DEFAULT_NAMES = ('intro', 'stand', 'walk', 'crouch_down', 'crouching_idle', 'jump_up', 'jump_forward', 'jump_back', 'block_standing', 'block_high', 'block_low', 'standing_recoil', 'crouching_recoil', 'jumping_recoil', 'tripped', 'launched', 'falling', 'knockdown', 'recover', 'dizzy', 'chip_ko', 'victory')
<commit_before>"""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A list containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ["up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel"] <commit_msg>Add DEFAULT_NAMES as a global tuple constant They will be referenced in various places in the game and should not be subject to change. INPUT_NAMES was also changed into a tuple for guaranteed immutability.<commit_after>"""This module contains global constants that are used throughout the project. Module Constants: SCREEN_SIZE A tuple containing the width and height of the game screen, in pixels and with a 1x scale factor. FULL_SCALE An integer for the magnification factor that will cause the game to toggle fullscreen display. FRAME_RATE How many times the graphics and processes are updated each second. The game uses a universal 'frame' unit to measure time; it is equivalent to (1/FRAME_RATE) seconds. INPUT_NAMES A tuple containing all of the names for the possible input 'buttons' in the game. Each one is bound to a different key for each player. DEFAULT_ACTIONS A tuple of Strings, containing the names of all Actions that every character should have, such as walking, blocking, and jumping. """ SCREEN_SIZE = (384, 226) FULL_SCALE = 3 FRAME_RATE = 60.0 INPUT_NAMES = ("up", "back", "down", "forward", "light_punch", "medium_punch", "heavy_punch", "light_kick", "medium_kick", "heavy_kick", "start", "cancel") DEFAULT_NAMES = ('intro', 'stand', 'walk', 'crouch_down', 'crouching_idle', 'jump_up', 'jump_forward', 'jump_back', 'block_standing', 'block_high', 'block_low', 'standing_recoil', 'crouching_recoil', 'jumping_recoil', 'tripped', 'launched', 'falling', 'knockdown', 'recover', 'dizzy', 'chip_ko', 'victory')
cd3929203e758367c3ded00a554f531aedb79f05
blaze/tests/test_blfuncs.py
blaze/tests/test_blfuncs.py
from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[(_add, 'f8(f8,f8)'), (_add, 'c16(c16,c16)')]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse()
from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[('f8(f8,f8)', _add), ('c16(c16,c16)', _add)]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse()
Fix usage of urlparse. and re-order list of key, value dict specification.
Fix usage of urlparse. and re-order list of key, value dict specification.
Python
bsd-3-clause
xlhtc007/blaze,AbhiAgarwal/blaze,mrocklin/blaze,aterrel/blaze,markflorisson/blaze-core,AbhiAgarwal/blaze,jcrist/blaze,markflorisson/blaze-core,mwiebe/blaze,AbhiAgarwal/blaze,markflorisson/blaze-core,maxalbert/blaze,alexmojaki/blaze,scls19fr/blaze,cpcloud/blaze,aterrel/blaze,mrocklin/blaze,jcrist/blaze,xlhtc007/blaze,FrancescAlted/blaze,nkhuyu/blaze,maxalbert/blaze,caseyclements/blaze,mwiebe/blaze,mwiebe/blaze,AbhiAgarwal/blaze,LiaoPan/blaze,aterrel/blaze,ChinaQuants/blaze,FrancescAlted/blaze,ContinuumIO/blaze,jdmcbr/blaze,mwiebe/blaze,dwillmer/blaze,FrancescAlted/blaze,cowlicks/blaze,ContinuumIO/blaze,dwillmer/blaze,LiaoPan/blaze,nkhuyu/blaze,scls19fr/blaze,FrancescAlted/blaze,markflorisson/blaze-core,alexmojaki/blaze,cpcloud/blaze,jdmcbr/blaze,ChinaQuants/blaze,caseyclements/blaze,cowlicks/blaze
from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[(_add, 'f8(f8,f8)'), (_add, 'c16(c16,c16)')]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse() Fix usage of urlparse. and re-order list of key, value dict specification.
from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[('f8(f8,f8)', _add), ('c16(c16,c16)', _add)]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse()
<commit_before>from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[(_add, 'f8(f8,f8)'), (_add, 'c16(c16,c16)')]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse() <commit_msg>Fix usage of urlparse. and re-order list of key, value dict specification.<commit_after>
from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[('f8(f8,f8)', _add), ('c16(c16,c16)', _add)]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse()
from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[(_add, 'f8(f8,f8)'), (_add, 'c16(c16,c16)')]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse() Fix usage of urlparse. and re-order list of key, value dict specification.from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[('f8(f8,f8)', _add), ('c16(c16,c16)', _add)]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse()
<commit_before>from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[(_add, 'f8(f8,f8)'), (_add, 'c16(c16,c16)')]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse() <commit_msg>Fix usage of urlparse. and re-order list of key, value dict specification.<commit_after>from blaze.blfuncs import BlazeFunc from blaze.datashape import double, complex128 as c128 from blaze.blaze_kernels import BlazeElementKernel import blaze def _add(a,b): return a + b def _mul(a,b): return a * b add = BlazeFunc('add',[('f8(f8,f8)', _add), ('c16(c16,c16)', _add)]) mul = BlazeFunc('mul', {(double,)*3: _mul}) a = blaze.array([1,2,3],dshape=double) b = blaze.array([2,3,4],dshape=double) c = add(a,b) d = mul(c,c) d._data = d._data.fuse()
a329770bdd5fdc6a646d6a0b298f0a67c789f86a
resolwe/flow/migrations/0029_storage_m2m.py
resolwe/flow/migrations/0029_storage_m2m.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Data = apps.get_model('flow', 'Data') Storage = apps.get_model('flow', 'Storage') for data in Data.objects.all(): storage = Storage.objects.filter(data_migration_temporary=data).first() if storage: storage.data.add(data) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Storage = apps.get_model('flow', 'Storage') for storage in Storage.objects.all(): storage.data.add(storage.data_migration_temporary) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ]
Fix storage migration to process all storages
Fix storage migration to process all storages
Python
apache-2.0
genialis/resolwe,genialis/resolwe
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Data = apps.get_model('flow', 'Data') Storage = apps.get_model('flow', 'Storage') for data in Data.objects.all(): storage = Storage.objects.filter(data_migration_temporary=data).first() if storage: storage.data.add(data) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ] Fix storage migration to process all storages
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Storage = apps.get_model('flow', 'Storage') for storage in Storage.objects.all(): storage.data.add(storage.data_migration_temporary) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Data = apps.get_model('flow', 'Data') Storage = apps.get_model('flow', 'Storage') for data in Data.objects.all(): storage = Storage.objects.filter(data_migration_temporary=data).first() if storage: storage.data.add(data) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ] <commit_msg>Fix storage migration to process all storages<commit_after>
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Storage = apps.get_model('flow', 'Storage') for storage in Storage.objects.all(): storage.data.add(storage.data_migration_temporary) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Data = apps.get_model('flow', 'Data') Storage = apps.get_model('flow', 'Storage') for data in Data.objects.all(): storage = Storage.objects.filter(data_migration_temporary=data).first() if storage: storage.data.add(data) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ] Fix storage migration to process all storages# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Storage = apps.get_model('flow', 'Storage') for storage in Storage.objects.all(): storage.data.add(storage.data_migration_temporary) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ]
<commit_before># -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Data = apps.get_model('flow', 'Data') Storage = apps.get_model('flow', 'Storage') for data in Data.objects.all(): storage = Storage.objects.filter(data_migration_temporary=data).first() if storage: storage.data.add(data) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ] <commit_msg>Fix storage migration to process all storages<commit_after># -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-26 04:08 from __future__ import unicode_literals from django.db import migrations, models def set_data_relation(apps, schema_editor): Storage = apps.get_model('flow', 'Storage') for storage in Storage.objects.all(): storage.data.add(storage.data_migration_temporary) class Migration(migrations.Migration): dependencies = [ ('flow', '0028_add_data_location'), ] operations = [ migrations.RenameField( model_name='storage', old_name='data', new_name='data_migration_temporary', ), migrations.AddField( model_name='storage', name='data', field=models.ManyToManyField(related_name='storages', to='flow.Data'), ), migrations.RunPython(set_data_relation), migrations.RemoveField( model_name='storage', name='data_migration_temporary', ), ]
e98b4f2a343643c513d8cd4cf8b34a446322b0de
watson/common/exception.py
watson/common/exception.py
"""Watson's base exception handling."""
"""Watson's base exception handling.""" class WatsonException(Exception): """Base watson exception To correctly use this class, inherit from it and define a `template` property. That `template` will be formated using the keyword arguments provided to the constructor. Example: :: class NotFound(WatsonException): '''The required object is not available in container.''' template = "The %(object)r was not found in %(container)s." raise NotFound(object=object_name, container=container) """ template = "An unknown exception occurred." def __init__(self, message=None, **kwargs): message = message or self.template try: message = message % kwargs except (TypeError, KeyError): # Something went wrong during message formatting. # Probably kwargs doesn't match a variable in the message. message = ("Message: %(template)s. Extra or " "missing info: %(kwargs)s" % {"template": message, "kwargs": kwargs}) super(WatsonException, self).__init__(message)
Add base exeption for Watson project
Add base exeption for Watson project
Python
mit
alexandrucoman/watson,c-square/watson,c-square/evorepo-common
"""Watson's base exception handling.""" Add base exeption for Watson project
"""Watson's base exception handling.""" class WatsonException(Exception): """Base watson exception To correctly use this class, inherit from it and define a `template` property. That `template` will be formated using the keyword arguments provided to the constructor. Example: :: class NotFound(WatsonException): '''The required object is not available in container.''' template = "The %(object)r was not found in %(container)s." raise NotFound(object=object_name, container=container) """ template = "An unknown exception occurred." def __init__(self, message=None, **kwargs): message = message or self.template try: message = message % kwargs except (TypeError, KeyError): # Something went wrong during message formatting. # Probably kwargs doesn't match a variable in the message. message = ("Message: %(template)s. Extra or " "missing info: %(kwargs)s" % {"template": message, "kwargs": kwargs}) super(WatsonException, self).__init__(message)
<commit_before>"""Watson's base exception handling.""" <commit_msg>Add base exeption for Watson project<commit_after>
"""Watson's base exception handling.""" class WatsonException(Exception): """Base watson exception To correctly use this class, inherit from it and define a `template` property. That `template` will be formated using the keyword arguments provided to the constructor. Example: :: class NotFound(WatsonException): '''The required object is not available in container.''' template = "The %(object)r was not found in %(container)s." raise NotFound(object=object_name, container=container) """ template = "An unknown exception occurred." def __init__(self, message=None, **kwargs): message = message or self.template try: message = message % kwargs except (TypeError, KeyError): # Something went wrong during message formatting. # Probably kwargs doesn't match a variable in the message. message = ("Message: %(template)s. Extra or " "missing info: %(kwargs)s" % {"template": message, "kwargs": kwargs}) super(WatsonException, self).__init__(message)
"""Watson's base exception handling.""" Add base exeption for Watson project"""Watson's base exception handling.""" class WatsonException(Exception): """Base watson exception To correctly use this class, inherit from it and define a `template` property. That `template` will be formated using the keyword arguments provided to the constructor. Example: :: class NotFound(WatsonException): '''The required object is not available in container.''' template = "The %(object)r was not found in %(container)s." raise NotFound(object=object_name, container=container) """ template = "An unknown exception occurred." def __init__(self, message=None, **kwargs): message = message or self.template try: message = message % kwargs except (TypeError, KeyError): # Something went wrong during message formatting. # Probably kwargs doesn't match a variable in the message. message = ("Message: %(template)s. Extra or " "missing info: %(kwargs)s" % {"template": message, "kwargs": kwargs}) super(WatsonException, self).__init__(message)
<commit_before>"""Watson's base exception handling.""" <commit_msg>Add base exeption for Watson project<commit_after>"""Watson's base exception handling.""" class WatsonException(Exception): """Base watson exception To correctly use this class, inherit from it and define a `template` property. That `template` will be formated using the keyword arguments provided to the constructor. Example: :: class NotFound(WatsonException): '''The required object is not available in container.''' template = "The %(object)r was not found in %(container)s." raise NotFound(object=object_name, container=container) """ template = "An unknown exception occurred." def __init__(self, message=None, **kwargs): message = message or self.template try: message = message % kwargs except (TypeError, KeyError): # Something went wrong during message formatting. # Probably kwargs doesn't match a variable in the message. message = ("Message: %(template)s. Extra or " "missing info: %(kwargs)s" % {"template": message, "kwargs": kwargs}) super(WatsonException, self).__init__(message)
82973662e9cc8234e741d7595c95137df77296bb
tests/unit/utils/vt_test.py
tests/unit/utils/vt_test.py
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False)
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' self.skipTest('The code is not mature enough. Test disabled.') cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False)
Disable the VT test, the code ain't mature enough.
Disable the VT test, the code ain't mature enough.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False) Disable the VT test, the code ain't mature enough.
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' self.skipTest('The code is not mature enough. Test disabled.') cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False)
<commit_before># -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False) <commit_msg>Disable the VT test, the code ain't mature enough.<commit_after>
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' self.skipTest('The code is not mature enough. Test disabled.') cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False)
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False) Disable the VT test, the code ain't mature enough.# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' self.skipTest('The code is not mature enough. Test disabled.') cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False)
<commit_before># -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False) <commit_msg>Disable the VT test, the code ain't mature enough.<commit_after># -*- coding: utf-8 -*- ''' :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' self.skipTest('The code is not mature enough. Test disabled.') cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False)
9506fa3a0382ba7a156ba6188c8d05bff8be5da3
falcom/api/common/read_only_data_structure.py
falcom/api/common/read_only_data_structure.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key]
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __repr__ (self): dictstr = [self.__class__.__name__] for key, value in self.__internal.items(): dictstr.append("{}={}".format(key, repr(value))) return "<{}>".format(" ".join(dictstr)) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key]
Add repr to data structures
Add repr to data structures
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key] Add repr to data structures
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __repr__ (self): dictstr = [self.__class__.__name__] for key, value in self.__internal.items(): dictstr.append("{}={}".format(key, repr(value))) return "<{}>".format(" ".join(dictstr)) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key]
<commit_before># Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key] <commit_msg>Add repr to data structures<commit_after>
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __repr__ (self): dictstr = [self.__class__.__name__] for key, value in self.__internal.items(): dictstr.append("{}={}".format(key, repr(value))) return "<{}>".format(" ".join(dictstr)) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key]
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key] Add repr to data structures# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __repr__ (self): dictstr = [self.__class__.__name__] for key, value in self.__internal.items(): dictstr.append("{}={}".format(key, repr(value))) return "<{}>".format(" ".join(dictstr)) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key]
<commit_before># Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key] <commit_msg>Add repr to data structures<commit_after># Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __repr__ (self): dictstr = [self.__class__.__name__] for key, value in self.__internal.items(): dictstr.append("{}={}".format(key, repr(value))) return "<{}>".format(" ".join(dictstr)) def __remove_null_keys (self): null_keys = [k for k, v in self.__internal.items() if v is None] for key in null_keys: del self.__internal[key]
02ac9d6234ca00f3f5382fda9941d1e0dd0f734b
src/tenyksscripts/scripts/8ball.py
src/tenyksscripts/scripts/8ball.py
import random ateball = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", ] def run(data, settings): if ('8ball' in data['payload']): return random.choice(ateball)
import random ateball = [ "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful.", ] def run(data, settings): if '8ball' in data['payload']: say = '{nick}: {fortune}'.format(nick=data['nick'], fortune=random.choice(ateball)) return say
Revert "Revert "Added nickname and punct, removed parens""
Revert "Revert "Added nickname and punct, removed parens"" This reverts commit ab4e279a6866d432cd1f58a07879e219360b4911.
Python
mit
cblgh/tenyks-contrib,colby/tenyks-contrib,kyleterry/tenyks-contrib
import random ateball = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", ] def run(data, settings): if ('8ball' in data['payload']): return random.choice(ateball) Revert "Revert "Added nickname and punct, removed parens"" This reverts commit ab4e279a6866d432cd1f58a07879e219360b4911.
import random ateball = [ "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful.", ] def run(data, settings): if '8ball' in data['payload']: say = '{nick}: {fortune}'.format(nick=data['nick'], fortune=random.choice(ateball)) return say
<commit_before>import random ateball = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", ] def run(data, settings): if ('8ball' in data['payload']): return random.choice(ateball) <commit_msg>Revert "Revert "Added nickname and punct, removed parens"" This reverts commit ab4e279a6866d432cd1f58a07879e219360b4911.<commit_after>
import random ateball = [ "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful.", ] def run(data, settings): if '8ball' in data['payload']: say = '{nick}: {fortune}'.format(nick=data['nick'], fortune=random.choice(ateball)) return say
import random ateball = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", ] def run(data, settings): if ('8ball' in data['payload']): return random.choice(ateball) Revert "Revert "Added nickname and punct, removed parens"" This reverts commit ab4e279a6866d432cd1f58a07879e219360b4911.import random ateball = [ "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful.", ] def run(data, settings): if '8ball' in data['payload']: say = '{nick}: {fortune}'.format(nick=data['nick'], fortune=random.choice(ateball)) return say
<commit_before>import random ateball = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", ] def run(data, settings): if ('8ball' in data['payload']): return random.choice(ateball) <commit_msg>Revert "Revert "Added nickname and punct, removed parens"" This reverts commit ab4e279a6866d432cd1f58a07879e219360b4911.<commit_after>import random ateball = [ "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful.", ] def run(data, settings): if '8ball' in data['payload']: say = '{nick}: {fortune}'.format(nick=data['nick'], fortune=random.choice(ateball)) return say
19cc42cbaa39854131c907115548abdd2cfdfc1b
todoist/managers/generic.py
todoist/managers/generic.py
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(self.api, '%s/get' % self.object_type) return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type) , 'get') return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
Fix gettatr object and name.
Fix gettatr object and name.
Python
mit
Doist/todoist-python
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(self.api, '%s/get' % self.object_type) return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync() Fix gettatr object and name.
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type) , 'get') return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
<commit_before># -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(self.api, '%s/get' % self.object_type) return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync() <commit_msg>Fix gettatr object and name.<commit_after>
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type) , 'get') return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(self.api, '%s/get' % self.object_type) return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync() Fix gettatr object and name.# -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type) , 'get') return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
<commit_before># -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(self.api, '%s/get' % self.object_type) return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync() <commit_msg>Fix gettatr object and name.<commit_after># -*- coding: utf-8 -*- class Manager(object): # should be re-defined in a subclass state_name = None object_type = None def __init__(self, api): self.api = api # shortcuts @property def state(self): return self.api.state @property def queue(self): return self.api.queue @property def token(self): return self.api.token class AllMixin(object): def all(self, filt=None): return list(filter(filt, self.state[self.state_name])) class GetByIdMixin(object): def get_by_id(self, obj_id, only_local=False): """ Finds and returns the object based on its id. """ for obj in self.state[self.state_name]: if obj['id'] == obj_id or obj.temp_id == str(obj_id): return obj if not only_local and self.object_type is not None: getter = getattr(eval('self.api.%ss' % self.object_type) , 'get') return getter(obj_id) return None class SyncMixin(object): """ Syncs this specific type of objects. """ def sync(self): return self.api.sync()
911fa61043cb034202aacc7ca3e92ceac048265c
greengraph/graph_command.py
greengraph/graph_command.py
#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser import IPython if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): IPython.core.display.Image(GoogleMap(*location).image)
#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser from IPython.display import Image from IPython.display import display if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): display(Image(GoogleMap(*location).image))
Fix displaying multiple images command
Fix displaying multiple images command
Python
mit
manhdao/greengraph-MPHYSG001
#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser import IPython if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): IPython.core.display.Image(GoogleMap(*location).image)Fix displaying multiple images command
#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser from IPython.display import Image from IPython.display import display if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): display(Image(GoogleMap(*location).image))
<commit_before>#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser import IPython if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): IPython.core.display.Image(GoogleMap(*location).image)<commit_msg>Fix displaying multiple images command<commit_after>
#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser from IPython.display import Image from IPython.display import display if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): display(Image(GoogleMap(*location).image))
#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser import IPython if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): IPython.core.display.Image(GoogleMap(*location).image)Fix displaying multiple images command#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser from IPython.display import Image from IPython.display import display if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): display(Image(GoogleMap(*location).image))
<commit_before>#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser import IPython if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): IPython.core.display.Image(GoogleMap(*location).image)<commit_msg>Fix displaying multiple images command<commit_after>#!/usr/bin/env python from .greengraph import GreenGraph from .googlemap import GoogleMap from argparse import ArgumentParser from IPython.display import Image from IPython.display import display if __name__ == "__main__": parser = ArgumentParser(description = 'Generate pictures between 2 location') parser.add_argument('-f', '--from', required=True, help='Starting location', dest='start') parser.add_argument('-t', '--to', required=True, help='Ending location', dest='end') parser.add_argument('-s', '--steps', required=True, help='Number of steps', type=int, dest='steps', default=20) parser.add_argument('-gb', '--greenbetween', help='Count green between', dest='greenbetween', action="store_true") parser.add_argument('-o', '--out', help='Output filename', type=str, dest='filename') args = parser.parse_args() my_data = GreenGraph(args.start, args.end) if args.greenbetween: print(my_data.green_between(args.steps)) else: for location in GreenGraph.location_sequence(GreenGraph.geolocate(args.start),GreenGraph.geolocate(args.end), args.steps): display(Image(GoogleMap(*location).image))
e54b28430f7b301e04eb5b02ce667019df4434bf
chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py
chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py
# Copyright (c) 2010 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. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 def run_once(self): password_file = '%s/sync_password.txt' % self.bindir self.run_chrome_test('sync_integration_tests', ('--password-file-for-test=%s ' + '--test-terminate-timeout=300000') % password_file)
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 binary_to_run = 'sync_integration_tests' cmd_line_params = '--test-terminate-timeout=120000' def run_once(self): self.run_chrome_test(self.binary_to_run, self.cmd_line_params)
Make the sync integration tests self-contained on autotest
Make the sync integration tests self-contained on autotest In the past, the sync integration tests used to require a password file stored on every test device in order to do a gaia sign in using production gaia servers. This caused the tests to be brittle. As of today, the sync integration tests no longer rely on a password file, with gaia sign in being stubbed out locally. This patch reconfigures the tests on autotest, so that it no longer looks for a local password file. In addition, the tests run much faster now, and therefore, we reduce the max timeout to a more reasonable 2 minutes (in the extreme case). BUG=chromium-os:11294, chromium-os:9262 TEST=sync_integration_tests Review URL: http://codereview.chromium.org/6387004 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@72561 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Python
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
# Copyright (c) 2010 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. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 def run_once(self): password_file = '%s/sync_password.txt' % self.bindir self.run_chrome_test('sync_integration_tests', ('--password-file-for-test=%s ' + '--test-terminate-timeout=300000') % password_file) Make the sync integration tests self-contained on autotest In the past, the sync integration tests used to require a password file stored on every test device in order to do a gaia sign in using production gaia servers. This caused the tests to be brittle. As of today, the sync integration tests no longer rely on a password file, with gaia sign in being stubbed out locally. This patch reconfigures the tests on autotest, so that it no longer looks for a local password file. In addition, the tests run much faster now, and therefore, we reduce the max timeout to a more reasonable 2 minutes (in the extreme case). BUG=chromium-os:11294, chromium-os:9262 TEST=sync_integration_tests Review URL: http://codereview.chromium.org/6387004 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@72561 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 binary_to_run = 'sync_integration_tests' cmd_line_params = '--test-terminate-timeout=120000' def run_once(self): self.run_chrome_test(self.binary_to_run, self.cmd_line_params)
<commit_before># Copyright (c) 2010 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. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 def run_once(self): password_file = '%s/sync_password.txt' % self.bindir self.run_chrome_test('sync_integration_tests', ('--password-file-for-test=%s ' + '--test-terminate-timeout=300000') % password_file) <commit_msg>Make the sync integration tests self-contained on autotest In the past, the sync integration tests used to require a password file stored on every test device in order to do a gaia sign in using production gaia servers. This caused the tests to be brittle. As of today, the sync integration tests no longer rely on a password file, with gaia sign in being stubbed out locally. This patch reconfigures the tests on autotest, so that it no longer looks for a local password file. In addition, the tests run much faster now, and therefore, we reduce the max timeout to a more reasonable 2 minutes (in the extreme case). BUG=chromium-os:11294, chromium-os:9262 TEST=sync_integration_tests Review URL: http://codereview.chromium.org/6387004 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@72561 4ff67af0-8c30-449e-8e8b-ad334ec8d88c<commit_after>
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 binary_to_run = 'sync_integration_tests' cmd_line_params = '--test-terminate-timeout=120000' def run_once(self): self.run_chrome_test(self.binary_to_run, self.cmd_line_params)
# Copyright (c) 2010 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. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 def run_once(self): password_file = '%s/sync_password.txt' % self.bindir self.run_chrome_test('sync_integration_tests', ('--password-file-for-test=%s ' + '--test-terminate-timeout=300000') % password_file) Make the sync integration tests self-contained on autotest In the past, the sync integration tests used to require a password file stored on every test device in order to do a gaia sign in using production gaia servers. This caused the tests to be brittle. As of today, the sync integration tests no longer rely on a password file, with gaia sign in being stubbed out locally. This patch reconfigures the tests on autotest, so that it no longer looks for a local password file. In addition, the tests run much faster now, and therefore, we reduce the max timeout to a more reasonable 2 minutes (in the extreme case). BUG=chromium-os:11294, chromium-os:9262 TEST=sync_integration_tests Review URL: http://codereview.chromium.org/6387004 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@72561 4ff67af0-8c30-449e-8e8b-ad334ec8d88c# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 binary_to_run = 'sync_integration_tests' cmd_line_params = '--test-terminate-timeout=120000' def run_once(self): self.run_chrome_test(self.binary_to_run, self.cmd_line_params)
<commit_before># Copyright (c) 2010 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. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 def run_once(self): password_file = '%s/sync_password.txt' % self.bindir self.run_chrome_test('sync_integration_tests', ('--password-file-for-test=%s ' + '--test-terminate-timeout=300000') % password_file) <commit_msg>Make the sync integration tests self-contained on autotest In the past, the sync integration tests used to require a password file stored on every test device in order to do a gaia sign in using production gaia servers. This caused the tests to be brittle. As of today, the sync integration tests no longer rely on a password file, with gaia sign in being stubbed out locally. This patch reconfigures the tests on autotest, so that it no longer looks for a local password file. In addition, the tests run much faster now, and therefore, we reduce the max timeout to a more reasonable 2 minutes (in the extreme case). BUG=chromium-os:11294, chromium-os:9262 TEST=sync_integration_tests Review URL: http://codereview.chromium.org/6387004 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@72561 4ff67af0-8c30-449e-8e8b-ad334ec8d88c<commit_after># Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from autotest_lib.client.cros import chrome_test class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase): version = 1 binary_to_run = 'sync_integration_tests' cmd_line_params = '--test-terminate-timeout=120000' def run_once(self): self.run_chrome_test(self.binary_to_run, self.cmd_line_params)
1d866c7a66d0efde1b6a9beb5ecf89b9c6360b1e
spotpy/unittests/test_objectivefunctions.py
spotpy/unittests/test_objectivefunctions.py
import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) print(self.simulation) print(self.evaluation) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main()
import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_pbias(self): res = of.pbias(self.evaluation, self.simulation) self.assertAlmostEqual(res, -156.66937901878677, self.tolerance) def test_nashsutcliffe(self): res = of.nashsutcliffe(self.evaluation, self.simulation) self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main()
Add tests for pbias and nashsutcliffe
Add tests for pbias and nashsutcliffe
Python
mit
bees4ever/spotpy,thouska/spotpy,thouska/spotpy,bees4ever/spotpy,bees4ever/spotpy,thouska/spotpy
import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) print(self.simulation) print(self.evaluation) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main() Add tests for pbias and nashsutcliffe
import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_pbias(self): res = of.pbias(self.evaluation, self.simulation) self.assertAlmostEqual(res, -156.66937901878677, self.tolerance) def test_nashsutcliffe(self): res = of.nashsutcliffe(self.evaluation, self.simulation) self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main()
<commit_before>import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) print(self.simulation) print(self.evaluation) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main() <commit_msg>Add tests for pbias and nashsutcliffe<commit_after>
import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_pbias(self): res = of.pbias(self.evaluation, self.simulation) self.assertAlmostEqual(res, -156.66937901878677, self.tolerance) def test_nashsutcliffe(self): res = of.nashsutcliffe(self.evaluation, self.simulation) self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main()
import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) print(self.simulation) print(self.evaluation) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main() Add tests for pbias and nashsutcliffeimport unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_pbias(self): res = of.pbias(self.evaluation, self.simulation) self.assertAlmostEqual(res, -156.66937901878677, self.tolerance) def test_nashsutcliffe(self): res = of.nashsutcliffe(self.evaluation, self.simulation) self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main()
<commit_before>import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) print(self.simulation) print(self.evaluation) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertIs(res, np.nan, "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main() <commit_msg>Add tests for pbias and nashsutcliffe<commit_after>import unittest from spotpy import objectivefunctions as of import numpy as np #https://docs.python.org/3/library/unittest.html class TestObjectiveFunctions(unittest.TestCase): # How many digits to match in case of floating point answers tolerance = 10 def setUp(self): np.random.seed(42) self.simulation = np.random.randn(10) self.evaluation = np.random.randn(10) def test_bias(self): res = of.bias(self.evaluation, self.simulation) self.assertAlmostEqual(res, 1.2387193462811703, self.tolerance) def test_pbias(self): res = of.pbias(self.evaluation, self.simulation) self.assertAlmostEqual(res, -156.66937901878677, self.tolerance) def test_nashsutcliffe(self): res = of.nashsutcliffe(self.evaluation, self.simulation) self.assertAlmostEqual(res, -4.1162070769985508, self.tolerance) def test_length_mismatch_return_nan(self): all_funcs = of._all_functions for func in all_funcs: res = func([0], [0, 1]) self.assertTrue(np.isnan(res), "Expected np.nan in length mismatch, Got {}".format(res)) if __name__ == '__main__': unittest.main()
ff42b726c107e75f96409894b610256068add8dc
spacy/tests/test_textcat.py
spacy/tests/test_textcat.py
import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): print(doc, cat, score) if not truth[cat]: assert score < 0.5 else: assert score > 0.5
from __future__ import unicode_literals import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): if not truth[cat]: assert score < 0.5 else: assert score > 0.5
Fix unicode declaration on test
Fix unicode declaration on test
Python
mit
honnibal/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy
import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): print(doc, cat, score) if not truth[cat]: assert score < 0.5 else: assert score > 0.5 Fix unicode declaration on test
from __future__ import unicode_literals import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): if not truth[cat]: assert score < 0.5 else: assert score > 0.5
<commit_before>import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): print(doc, cat, score) if not truth[cat]: assert score < 0.5 else: assert score > 0.5 <commit_msg>Fix unicode declaration on test<commit_after>
from __future__ import unicode_literals import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): if not truth[cat]: assert score < 0.5 else: assert score > 0.5
import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): print(doc, cat, score) if not truth[cat]: assert score < 0.5 else: assert score > 0.5 Fix unicode declaration on testfrom __future__ import unicode_literals import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): if not truth[cat]: assert score < 0.5 else: assert score > 0.5
<commit_before>import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): print(doc, cat, score) if not truth[cat]: assert score < 0.5 else: assert score > 0.5 <commit_msg>Fix unicode declaration on test<commit_after>from __future__ import unicode_literals import random from ..pipeline import TextCategorizer from ..lang.en import English from ..vocab import Vocab from ..tokens import Doc from ..gold import GoldParse def test_textcat_learns_multilabel(): docs = [] nlp = English() vocab = nlp.vocab letters = ['a', 'b', 'c'] for w1 in letters: for w2 in letters: cats = {letter: float(w2==letter) for letter in letters} docs.append((Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3), cats)) random.shuffle(docs) model = TextCategorizer(vocab, width=8) for letter in letters: model.add_label(letter) optimizer = model.begin_training() for i in range(20): losses = {} Ys = [GoldParse(doc, cats=cats) for doc, cats in docs] Xs = [doc for doc, cats in docs] model.update(Xs, Ys, sgd=optimizer, losses=losses) random.shuffle(docs) for w1 in letters: for w2 in letters: doc = Doc(vocab, words=['d']*3 + [w1, w2] + ['d']*3) truth = {letter: w2==letter for letter in letters} model(doc) for cat, score in doc.cats.items(): if not truth[cat]: assert score < 0.5 else: assert score > 0.5
954cd7378c70ef433f5f2dc220991905fd779dc6
allauth/socialaccount/providers/eventbrite/provider.py
allauth/socialaccount/providers/eventbrite/provider.py
"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider]
"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) <<<<<<< HEAD ======= def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] >>>>>>> c32ec1de9b8af42147d2977fe173d25643be447a def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider]
Remove unneeded get_default_scope from EventbriteProvider
Remove unneeded get_default_scope from EventbriteProvider
Python
mit
spool/django-allauth,spool/django-allauth,spool/django-allauth
"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider] Remove unneeded get_default_scope from EventbriteProvider
"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) <<<<<<< HEAD ======= def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] >>>>>>> c32ec1de9b8af42147d2977fe173d25643be447a def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider]
<commit_before>"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider] <commit_msg>Remove unneeded get_default_scope from EventbriteProvider<commit_after>
"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) <<<<<<< HEAD ======= def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] >>>>>>> c32ec1de9b8af42147d2977fe173d25643be447a def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider]
"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider] Remove unneeded get_default_scope from EventbriteProvider"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) <<<<<<< HEAD ======= def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] >>>>>>> c32ec1de9b8af42147d2977fe173d25643be447a def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider]
<commit_before>"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider] <commit_msg>Remove unneeded get_default_scope from EventbriteProvider<commit_after>"""Customise Provider classes for Eventbrite API v3.""" from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class EventbriteAccount(ProviderAccount): """ProviderAccount subclass for Eventbrite.""" def get_avatar_url(self): """Return avatar url.""" return self.account.extra_data['image_id'] class EventbriteProvider(OAuth2Provider): """OAuth2Provider subclass for Eventbrite.""" id = 'eventbrite' name = 'Eventbrite' account_class = EventbriteAccount def extract_uid(self, data): """Extract uid ('id') and ensure it's a str.""" return str(data['id']) <<<<<<< HEAD ======= def get_default_scope(self): """Ensure scope is null to fit their API.""" return [''] >>>>>>> c32ec1de9b8af42147d2977fe173d25643be447a def extract_common_fields(self, data): """Extract fields from a basic user query.""" return dict( emails=data.get('emails'), id=data.get('id'), name=data.get('name'), first_name=data.get('first_name'), last_name=data.get('last_name'), image_url=data.get('image_url') ) provider_classes = [EventbriteProvider]
73f9e0e3abd49746fd246f861f2897a8cd711d90
splunk_handler/__init__.py
splunk_handler/__init__.py
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: params = { 'host': socket.gethostname(), 'index': self.index, 'source': record.pathname, 'sourcetype': 'json' } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index, hostname=None, source=None, sourcetype='json'): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index self.source = source self.sourcetype = sourcetype if hostname is None: self.hostname = socket.gethostname() else: self.hostname = hostname # prevent infinite recursion by silencing requests logger requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: if self.source is None: source = record.pathname else: source = self.source params = { 'host': self.hostname, 'index': self.index, 'source': source, 'sourcetype': self.sourcetype } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
Add code to allow user to configure their own hostname, source, and sourcetype (with defaults)
Add code to allow user to configure their own hostname, source, and sourcetype (with defaults)
Python
mit
zach-taylor/splunk_handler,sullivanmatt/splunk_handler
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: params = { 'host': socket.gethostname(), 'index': self.index, 'source': record.pathname, 'sourcetype': 'json' } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e) Add code to allow user to configure their own hostname, source, and sourcetype (with defaults)
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index, hostname=None, source=None, sourcetype='json'): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index self.source = source self.sourcetype = sourcetype if hostname is None: self.hostname = socket.gethostname() else: self.hostname = hostname # prevent infinite recursion by silencing requests logger requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: if self.source is None: source = record.pathname else: source = self.source params = { 'host': self.hostname, 'index': self.index, 'source': source, 'sourcetype': self.sourcetype } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
<commit_before>import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: params = { 'host': socket.gethostname(), 'index': self.index, 'source': record.pathname, 'sourcetype': 'json' } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e) <commit_msg>Add code to allow user to configure their own hostname, source, and sourcetype (with defaults)<commit_after>
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index, hostname=None, source=None, sourcetype='json'): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index self.source = source self.sourcetype = sourcetype if hostname is None: self.hostname = socket.gethostname() else: self.hostname = hostname # prevent infinite recursion by silencing requests logger requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: if self.source is None: source = record.pathname else: source = self.source params = { 'host': self.hostname, 'index': self.index, 'source': source, 'sourcetype': self.sourcetype } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: params = { 'host': socket.gethostname(), 'index': self.index, 'source': record.pathname, 'sourcetype': 'json' } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e) Add code to allow user to configure their own hostname, source, and sourcetype (with defaults)import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index, hostname=None, source=None, sourcetype='json'): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index self.source = source self.sourcetype = sourcetype if hostname is None: self.hostname = socket.gethostname() else: self.hostname = hostname # prevent infinite recursion by silencing requests logger requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: if self.source is None: source = record.pathname else: source = self.source params = { 'host': self.hostname, 'index': self.index, 'source': source, 'sourcetype': self.sourcetype } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
<commit_before>import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: params = { 'host': socket.gethostname(), 'index': self.index, 'source': record.pathname, 'sourcetype': 'json' } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e) <commit_msg>Add code to allow user to configure their own hostname, source, and sourcetype (with defaults)<commit_after>import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index, hostname=None, source=None, sourcetype='json'): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index self.source = source self.sourcetype = sourcetype if hostname is None: self.hostname = socket.gethostname() else: self.hostname = hostname # prevent infinite recursion by silencing requests logger requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: if self.source is None: source = record.pathname else: source = self.source params = { 'host': self.hostname, 'index': self.index, 'source': source, 'sourcetype': self.sourcetype } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
a3103605f1d6b3979ad3c7fc4cdcb3ef71e0886f
fabfile/eg.py
fabfile/eg.py
from fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py')
from fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist_mlp.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py')
Update fabfile for moved mnist example
Update fabfile for moved mnist example
Python
mit
explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc
from fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py') Update fabfile for moved mnist example
from fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist_mlp.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py')
<commit_before>from fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py') <commit_msg>Update fabfile for moved mnist example<commit_after>
from fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist_mlp.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py')
from fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py') Update fabfile for moved mnist examplefrom fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist_mlp.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py')
<commit_before>from fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py') <commit_msg>Update fabfile for moved mnist example<commit_after>from fabric.api import task, local, run, lcd, cd, env, shell_env from os.path import exists as file_exists from fabtools.python import virtualenv from os import path PWD = path.join(path.dirname(__file__), '..') VENV_DIR = path.join(PWD, '.env') @task def mnist(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/mnist_mlp.py') @task def basic_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/basic_tagger.py') @task def cnn_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/cnn_tagger.py') @task def spacy_tagger(): with virtualenv(VENV_DIR), lcd(PWD), shell_env(PYTHONPATH=PWD): local('python examples/spacy_tagger.py')
8d316e6c29f0a65b038bceeb0d93aeca379b76cb
grid/views.py
grid/views.py
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.games_set(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript")
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript")
Use the correct syntax when iterating a week's games.
Use the correct syntax when iterating a week's games.
Python
mit
bschmeck/gnarl,bschmeck/gnarl,bschmeck/gnarl
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.games_set(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript") Use the correct syntax when iterating a week's games.
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript")
<commit_before>from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.games_set(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript") <commit_msg>Use the correct syntax when iterating a week's games.<commit_after>
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript")
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.games_set(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript") Use the correct syntax when iterating a week's games.from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript")
<commit_before>from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.games_set(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript") <commit_msg>Use the correct syntax when iterating a week's games.<commit_after>from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.all()[0]; for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): ret = [] return HttpResponse(json.dumps(ret), "application/javascript")
24b8de9cfdcc36b1cc6001b84430411d32ac58a6
setup.py
setup.py
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', 'pdbpp' ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
Add pdbpp to dev dependencies
Add pdbpp to dev dependencies
Python
mit
awdeorio/mailmerge
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, ) Add pdbpp to dev dependencies
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', 'pdbpp' ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
<commit_before>"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, ) <commit_msg>Add pdbpp to dev dependencies<commit_after>
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', 'pdbpp' ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, ) Add pdbpp to dev dependencies"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', 'pdbpp' ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
<commit_before>"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, ) <commit_msg>Add pdbpp to dev dependencies<commit_after>"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="awdeorio@umich.edu", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', 'pdbpp' ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
56bebcab933bbac89150937fe0b6b5adfdc0db26
setup.py
setup.py
import os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A django template loader that looks for a right to left version of a template if the activated language is a right to left language (e.g Arabic, Hebrew)', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )
import os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A Django template loader that looks for an alternative right to left version of a template file if the activated language is a right to left language such as Arabic or Hebrew.', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )
Update description for consistency with readme
Update description for consistency with readme
Python
bsd-3-clause
abbas123456/django-right-to-left
import os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A django template loader that looks for a right to left version of a template if the activated language is a right to left language (e.g Arabic, Hebrew)', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )Update description for consistency with readme
import os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A Django template loader that looks for an alternative right to left version of a template file if the activated language is a right to left language such as Arabic or Hebrew.', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )
<commit_before>import os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A django template loader that looks for a right to left version of a template if the activated language is a right to left language (e.g Arabic, Hebrew)', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )<commit_msg>Update description for consistency with readme<commit_after>
import os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A Django template loader that looks for an alternative right to left version of a template file if the activated language is a right to left language such as Arabic or Hebrew.', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )
import os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A django template loader that looks for a right to left version of a template if the activated language is a right to left language (e.g Arabic, Hebrew)', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )Update description for consistency with readmeimport os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A Django template loader that looks for an alternative right to left version of a template file if the activated language is a right to left language such as Arabic or Hebrew.', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )
<commit_before>import os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A django template loader that looks for a right to left version of a template if the activated language is a right to left language (e.g Arabic, Hebrew)', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )<commit_msg>Update description for consistency with readme<commit_after>import os from setuptools import setup PROJECT_DIR = os.path.dirname(__file__) setup( name = 'django-right-to-left', packages = ['rtl'], version = '0.1', license = 'BSD', keywords = 'Django, translation, internationalization, righ to left, bidi', description = 'A Django template loader that looks for an alternative right to left version of a template file if the activated language is a right to left language such as Arabic or Hebrew.', long_description=open(os.path.join(PROJECT_DIR, 'README.rst')).read(), author='Mohammad Abbas', author_email='mohammad.abbas86@gmail.com', url='https://github.com/abbas123456/django-right-to-left', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internationalization'], )
952704b93004e5763231ad3e64f32135474651b2
common/templatetags/uqam.py
common/templatetags/uqam.py
from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all() places = Country.objects.all() return { 'categories': categories, 'places': places, }
from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all().order_by('name') places = Country.objects.all() return { 'categories': categories, 'places': places, }
Order categories in search fields
Order categories in search fields
Python
bsd-3-clause
uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam
from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all() places = Country.objects.all() return { 'categories': categories, 'places': places, } Order categories in search fields
from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all().order_by('name') places = Country.objects.all() return { 'categories': categories, 'places': places, }
<commit_before>from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all() places = Country.objects.all() return { 'categories': categories, 'places': places, } <commit_msg>Order categories in search fields<commit_after>
from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all().order_by('name') places = Country.objects.all() return { 'categories': categories, 'places': places, }
from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all() places = Country.objects.all() return { 'categories': categories, 'places': places, } Order categories in search fieldsfrom django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all().order_by('name') places = Country.objects.all() return { 'categories': categories, 'places': places, }
<commit_before>from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all() places = Country.objects.all() return { 'categories': categories, 'places': places, } <commit_msg>Order categories in search fields<commit_after>from django import template register = template.Library() @register.filter def dimension(value, arg): """ Dimension integers If value, append arg, otherwise output nothing """ if value: return str(value) + " " + arg return "" @register.filter def verbose_name(obj): """ Return the verbose name of a model """ return obj._meta.verbose_name @register.filter def pdb(element): """ Inside a template do {{ template_var|pdb }} """ import ipdb ipdb.set_trace() return element from cat.models import Category from location.models import Country @register.inclusion_tag('snippets/advanced_search_fields.html') def advanced_search_fields(): categories = Category.objects.all().order_by('name') places = Country.objects.all() return { 'categories': categories, 'places': places, }
38669acc445dc4376968bf1bb885b8b205688a6e
syncplay/ui/sound.py
syncplay/ui/sound.py
try: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close()
try: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" print buzzPath try: buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close() except IOError: pass
Fix for exception due to missing buzzer.wav
Fix for exception due to missing buzzer.wav
Python
apache-2.0
NeverDecaf/syncplay,alby128/syncplay,Syncplay/syncplay,alby128/syncplay,NeverDecaf/syncplay,Syncplay/syncplay
try: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close() Fix for exception due to missing buzzer.wav
try: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" print buzzPath try: buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close() except IOError: pass
<commit_before>try: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close() <commit_msg>Fix for exception due to missing buzzer.wav<commit_after>
try: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" print buzzPath try: buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close() except IOError: pass
try: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close() Fix for exception due to missing buzzer.wavtry: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" print buzzPath try: buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close() except IOError: pass
<commit_before>try: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close() <commit_msg>Fix for exception due to missing buzzer.wav<commit_after>try: import winsound except ImportError: winsound = None try: import alsaaudio import wave except ImportError: alsaaudio = None from syncplay import utils def doBuzz(): if(winsound): buzzPath = utils.findWorkingDir() + "\\resources\\buzzer.wav" winsound.PlaySound(buzzPath, winsound.SND_FILENAME|winsound.SND_ASYNC) elif(alsaaudio): buzzPath = utils.findWorkingDir() + "/resources/buzzer.wav" print buzzPath try: buzz = wave.open(buzzPath, 'rb') device = alsaaudio.PCM(0) device.setchannels(buzz.getnchannels()) device.setrate(buzz.getframerate()) if buzz.getsampwidth() == 1: device.setformat(alsaaudio.PCM_FORMAT_U8) elif buzz.getsampwidth() == 2: device.setformat(alsaaudio.PCM_FORMAT_S16_LE) else: raise ValueError('Unsupported buzzer format') device.setperiodsize(640) data = buzz.readframes(640) while data: device.write(data) data = buzz.readframes(640) buzz.close() except IOError: pass
da0ee7c58d4d21037bc73951591bcede9efa23da
setup.py
setup.py
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'pynacl', 'twisted'), tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False )
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'twisted'), extras_require={ 'crypto': ('pynacl',) }, tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False )
Set pynacl as an optional requirement.
Set pynacl as an optional requirement.
Python
mit
Renelvon/txrudp,OpenBazaar/txrudp
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'pynacl', 'twisted'), tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False ) Set pynacl as an optional requirement.
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'twisted'), extras_require={ 'crypto': ('pynacl',) }, tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False )
<commit_before>"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'pynacl', 'twisted'), tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False ) <commit_msg>Set pynacl as an optional requirement.<commit_after>
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'twisted'), extras_require={ 'crypto': ('pynacl',) }, tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False )
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'pynacl', 'twisted'), tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False ) Set pynacl as an optional requirement."""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'twisted'), extras_require={ 'crypto': ('pynacl',) }, tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False )
<commit_before>"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'pynacl', 'twisted'), tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False ) <commit_msg>Set pynacl as an optional requirement.<commit_after>"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.rst'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.4.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='renelvon@gmail.com', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp', 'tests'), install_requires=('enum34', 'protobuf', 'twisted'), extras_require={ 'crypto': ('pynacl',) }, tests_require=('coverage', 'nose', 'mock'), test_suite='nose.collector', include_package_data=True, zip_safe=False )
bb96586af0aa0fcf6ca5b1891740fbc02f3758c8
setup.py
setup.py
from setuptools import setup, find_packages VERSION = '1.1.4' setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open("README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
from setuptools import setup, find_packages from os.path import dirname, abspath HERE = abspath(dirname(__file__)) VERSION = open(HERE + '/puresnmp/version.txt').read().strip() setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open(HERE + "/README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
Revert "Another attempt to fix the RTD build."
Revert "Another attempt to fix the RTD build." This reverts commit 43807c085493962ca0f79105b64b3be8ddc6fc39. References #25
Python
mit
exhuma/puresnmp,exhuma/puresnmp
from setuptools import setup, find_packages VERSION = '1.1.4' setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open("README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] ) Revert "Another attempt to fix the RTD build." This reverts commit 43807c085493962ca0f79105b64b3be8ddc6fc39. References #25
from setuptools import setup, find_packages from os.path import dirname, abspath HERE = abspath(dirname(__file__)) VERSION = open(HERE + '/puresnmp/version.txt').read().strip() setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open(HERE + "/README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
<commit_before>from setuptools import setup, find_packages VERSION = '1.1.4' setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open("README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] ) <commit_msg>Revert "Another attempt to fix the RTD build." This reverts commit 43807c085493962ca0f79105b64b3be8ddc6fc39. References #25<commit_after>
from setuptools import setup, find_packages from os.path import dirname, abspath HERE = abspath(dirname(__file__)) VERSION = open(HERE + '/puresnmp/version.txt').read().strip() setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open(HERE + "/README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
from setuptools import setup, find_packages VERSION = '1.1.4' setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open("README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] ) Revert "Another attempt to fix the RTD build." This reverts commit 43807c085493962ca0f79105b64b3be8ddc6fc39. References #25from setuptools import setup, find_packages from os.path import dirname, abspath HERE = abspath(dirname(__file__)) VERSION = open(HERE + '/puresnmp/version.txt').read().strip() setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open(HERE + "/README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
<commit_before>from setuptools import setup, find_packages VERSION = '1.1.4' setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open("README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] ) <commit_msg>Revert "Another attempt to fix the RTD build." This reverts commit 43807c085493962ca0f79105b64b3be8ddc6fc39. References #25<commit_after>from setuptools import setup, find_packages from os.path import dirname, abspath HERE = abspath(dirname(__file__)) VERSION = open(HERE + '/puresnmp/version.txt').read().strip() setup( name="puresnmp", version=VERSION, description="Pure Python SNMP implementation", long_description=open(HERE + "/README.rst").read(), author="Michel Albert", author_email="michel@albert.lu", provides=['puresnmp'], license="MIT", include_package_data=True, install_requires=[ 'typing', ], extras_require={ 'dev': [], 'test': ['pytest-xdist', 'pytest', 'pytest-coverage'] }, packages=find_packages(exclude=["tests.*", "tests", "docs"]), url="https://github.com/exhuma/puresnmp", keywords="networking snmp", classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Topic :: System :: Networking', 'Topic :: System :: Networking :: Monitoring', 'Topic :: System :: Systems Administration', ] )
41bbcab67e691cf328b47bd23b91f841078a0c4c
setup.py
setup.py
#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[], )
#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', download_url='https://github.com/fatboystring/csv_generator/tarball/0.5.0', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[] )
Remove install requires and added download_url
Remove install requires and added download_url
Python
mit
fatboystring/csv_generator,fatboystring/csv_generator
#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[], ) Remove install requires and added download_url
#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', download_url='https://github.com/fatboystring/csv_generator/tarball/0.5.0', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[] )
<commit_before>#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[], ) <commit_msg>Remove install requires and added download_url<commit_after>
#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', download_url='https://github.com/fatboystring/csv_generator/tarball/0.5.0', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[] )
#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[], ) Remove install requires and added download_url#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', download_url='https://github.com/fatboystring/csv_generator/tarball/0.5.0', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[] )
<commit_before>#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[], ) <commit_msg>Remove install requires and added download_url<commit_after>#!/usr/bin/env python from __future__ import unicode_literals from csv_generator import __version__ from setuptools import setup, find_packages setup( name='csv_generator', version=__version__, description='Configurable CSV Generator for Django', author='Dan Stringer', author_email='dan.stringer1983@googlemail.com', url='https://github.com/fatboystring/csv_generator/', download_url='https://github.com/fatboystring/csv_generator/tarball/0.5.0', packages=find_packages(exclude=['app']), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], include_package_data=True, keywords=['csv generator', 'queryset', 'django'], install_requires=[] )
8e2fe6bd486e7c105ef7cd6f061b41efd3e42b08
tasks/base.py
tasks/base.py
import os import invoke invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
import os import invoke if os.environ.get('TRAVIS_OS_NAME') == 'osx': invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
Use dirty macOS workaround only on OSX on Travis
Use dirty macOS workaround only on OSX on Travis
Python
bsd-3-clause
topazproject/topaz,topazproject/topaz,topazproject/topaz,topazproject/topaz
import os import invoke invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec") Use dirty macOS workaround only on OSX on Travis
import os import invoke if os.environ.get('TRAVIS_OS_NAME') == 'osx': invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
<commit_before>import os import invoke invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec") <commit_msg>Use dirty macOS workaround only on OSX on Travis<commit_after>
import os import invoke if os.environ.get('TRAVIS_OS_NAME') == 'osx': invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
import os import invoke invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec") Use dirty macOS workaround only on OSX on Travisimport os import invoke if os.environ.get('TRAVIS_OS_NAME') == 'osx': invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
<commit_before>import os import invoke invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec") <commit_msg>Use dirty macOS workaround only on OSX on Travis<commit_after>import os import invoke if os.environ.get('TRAVIS_OS_NAME') == 'osx': invoke.run = os.system class BaseTest(object): def download_mspec(self): if not os.path.isdir("../mspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/mspec") def download_rubyspec(self): if not os.path.isdir("../rubyspec"): invoke.run("cd .. && git clone --depth=100 --quiet https://github.com/ruby/spec rubyspec")
5f3ebbf3216144a79581e70f5397886b527339f1
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="1.0", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] )
#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="0.0.2", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] )
Decrease version to bare minimum plus 0.0.1
Decrease version to bare minimum plus 0.0.1
Python
mit
UseAlloy/psycho
#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="1.0", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] ) Decrease version to bare minimum plus 0.0.1
#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="0.0.2", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] )
<commit_before>#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="1.0", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] ) <commit_msg>Decrease version to bare minimum plus 0.0.1<commit_after>
#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="0.0.2", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] )
#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="1.0", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] ) Decrease version to bare minimum plus 0.0.1#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="0.0.2", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] )
<commit_before>#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="1.0", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] ) <commit_msg>Decrease version to bare minimum plus 0.0.1<commit_after>#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="0.0.2", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] )
c16ce741af385497a2629fe41341c5a12a649672
helper/url.py
helper/url.py
import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message
import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.)]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message
Exclude more characters at the end of a link.
Exclude more characters at the end of a link.
Python
bsd-2-clause
sushi-irc/tekka
import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message Exclude more characters at the end of a link.
import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.)]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message
<commit_before>import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message <commit_msg>Exclude more characters at the end of a link.<commit_after>
import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.)]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message
import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message Exclude more characters at the end of a link.import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.)]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message
<commit_before>import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message <commit_msg>Exclude more characters at the end of a link.<commit_after>import re urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.)]") def URLToTag(message): """ searches for an URL in message and sets an <a>-tag arround it, then returns the new string """ lastEnd = 0 while True: match = urlExp.search(message, lastEnd) if not match: break mStart = match.start() mEnd = match.end() lastEnd = mStart url = message[mStart:mEnd] tagStart="<a href='%s'>" % url tagEnd = "</a>" msgStart = message[0:mStart] msgEnd = message[mEnd:] newUrl = tagStart + url + tagEnd message = msgStart + newUrl + msgEnd lastEnd += len(tagStart)+len(tagEnd)+len(url) return message
08b6c18dd92df542140dc0962cf0ddbbb2acb3df
setup.py
setup.py
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.1', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] )
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.2', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] )
Bump minor release number, thanks to @lanjelot's fixes
Bump minor release number, thanks to @lanjelot's fixes
Python
bsd-2-clause
mwielgoszewski/python-paddingoracle
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.1', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] ) Bump minor release number, thanks to @lanjelot's fixes
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.2', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] )
<commit_before>try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.1', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] ) <commit_msg>Bump minor release number, thanks to @lanjelot's fixes<commit_after>
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.2', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] )
try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.1', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] ) Bump minor release number, thanks to @lanjelot's fixestry: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.2', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] )
<commit_before>try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.1', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] ) <commit_msg>Bump minor release number, thanks to @lanjelot's fixes<commit_after>try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='paddingoracle', author='Marcin Wielgoszewski', author_email='marcin.wielgoszewski@gmail.com', version='0.2.2', url='https://github.com/mwielgoszewski/python-paddingoracle', py_modules=['paddingoracle'], description='A portable, padding oracle exploit API', zip_safe=False, classifiers=[ 'License :: OSI Approved :: BSD License', 'Programming Language :: Python' ] )
bf7a6eb0e63eb323bed223af4adca793ea5e0f92
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/tryggvib/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/trickvi/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], )
Update project url after github maintainer renaming
Update project url after github maintainer renaming
Python
mit
okfn/datapackage-py,datapackages/datapackage-py,okfn/datapackage-model-py,sirex/datapackage-py,okfn/datapackage-model-py,datapackages/datapackage-py,sirex/datapackage-py,okfn/datapackage-py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/tryggvib/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], ) Update project url after github maintainer renaming
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/trickvi/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/tryggvib/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], ) <commit_msg>Update project url after github maintainer renaming<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/trickvi/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/tryggvib/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], ) Update project url after github maintainer renaming#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/trickvi/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/tryggvib/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], ) <commit_msg>Update project url after github maintainer renaming<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import io try: from setuptools import setup except ImportError: from distutils.core import setup description = "Manage and load dataprotocols.org Data Packages" with io.open('README.rst') as readme: long_description = readme.read() setup( name = 'datapackage', version = '0.5.2', url = 'https://github.com/trickvi/datapackage', license = 'GPLv3', description = description, long_description = long_description, maintainer = 'Tryggvi Björgvinsson', maintainer_email = 'tryggvi.bjorgvinsson@okfn.org', packages = ['datapackage'], package_dir={'datapackage': 'datapackage'}, package_data={'datapackage': ['data/*.json']}, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], )
e29f250286411c0e1c6f084f9e3f1ab4cbdfa6ec
setup.py
setup.py
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},)
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], depends=['quaternion.c', 'quaternion.h', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},)
Make sure the code is rebuilt if quaternion.h changes
Make sure the code is rebuilt if quaternion.h changes
Python
mit
moble/quaternion,moble/quaternion
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},) Make sure the code is rebuilt if quaternion.h changes
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], depends=['quaternion.c', 'quaternion.h', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},)
<commit_before>#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},) <commit_msg>Make sure the code is rebuilt if quaternion.h changes<commit_after>
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], depends=['quaternion.c', 'quaternion.h', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},)
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},) Make sure the code is rebuilt if quaternion.h changes#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], depends=['quaternion.c', 'quaternion.h', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},)
<commit_before>#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},) <commit_msg>Make sure the code is rebuilt if quaternion.h changes<commit_after>#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE> from auto_version import calculate_version, build_py_copy_version def configuration(parent_package='', top_path=None): import numpy from distutils.errors import DistutilsError if numpy.__dict__.get('quaternion') is not None: raise DistutilsError('The target NumPy already has a quaternion type') from numpy.distutils.misc_util import Configuration # if(os.environ.get('THIS_IS_TRAVIS') is not None): # print("This appears to be Travis!") # compile_args = ['-O3'] # else: # compile_args = ['-ffast-math', '-O3'] compile_args = ['-O3'] config = Configuration('quaternion', parent_package, top_path) config.add_extension('numpy_quaternion', ['quaternion.c', 'numpy_quaternion.c'], depends=['quaternion.c', 'quaternion.h', 'numpy_quaternion.c'], extra_compile_args=compile_args, ) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration, version=calculate_version(), cmdclass={'build_py': build_py_copy_version},)
730c1050c66940ac935db098fdcaa55ac5be7026
setup.py
setup.py
#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] )
#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, options={'easy_install': {'allow_hosts': 'pypi.python.org'}}, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] )
Make sure protobuf comes from pypi
Make sure protobuf comes from pypi Without this, it gets the outdated zip package from googlecode and fail.
Python
apache-2.0
bmess/riak-python-client,basho/riak-python-client,bmess/riak-python-client,basho/riak-python-client,basho/riak-python-client,GabrielNicolasAvellaneda/riak-python-client,GabrielNicolasAvellaneda/riak-python-client
#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] ) Make sure protobuf comes from pypi Without this, it gets the outdated zip package from googlecode and fail.
#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, options={'easy_install': {'allow_hosts': 'pypi.python.org'}}, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] )
<commit_before>#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] ) <commit_msg>Make sure protobuf comes from pypi Without this, it gets the outdated zip package from googlecode and fail.<commit_after>
#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, options={'easy_install': {'allow_hosts': 'pypi.python.org'}}, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] )
#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] ) Make sure protobuf comes from pypi Without this, it gets the outdated zip package from googlecode and fail.#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, options={'easy_install': {'allow_hosts': 'pypi.python.org'}}, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] )
<commit_before>#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] ) <commit_msg>Make sure protobuf comes from pypi Without this, it gets the outdated zip package from googlecode and fail.<commit_after>#!/usr/bin/env python import glob import os import subprocess import platform from setuptools import setup, find_packages def make_docs(): if not os.path.exists('docs'): os.mkdir('docs') subprocess.call(['pydoc', '-w', 'riak']) for name in glob.glob('*.html'): os.rename(name, 'docs/%s' % name) install_requires = ["riak_pb >=1.2.0, < 1.3.0"] requires = ["riak_pb(>=1.2.0,<1.3.0)"] tests_require = [] if platform.python_version() < '2.7': tests_require.append("unittest2") setup( name='riak', version='1.5.1', packages = find_packages(), requires = requires, install_requires = install_requires, tests_require = tests_require, package_data = {'riak' : ['erl_src/*']}, description='Python client for Riak', zip_safe=True, options={'easy_install': {'allow_hosts': 'pypi.python.org'}}, include_package_data=True, license='Apache 2', platforms='Platform Independent', author='Basho Technologies', author_email='clients@basho.com', test_suite='riak.tests.suite', url='https://github.com/basho/riak-python-client', classifiers = ['License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Database'] )
60b9273042d1448c07345c4032f52c224803af9d
setup.py
setup.py
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'Python-AD', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] )
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'python-ad', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] )
Tweak output file name of source distribution.
Tweak output file name of source distribution.
Python
mit
sfu-rcg/python-ad,sfu-rcg/python-ad,geertj/python-ad,geertj/python-ad,theatlantic/python-active-directory,theatlantic/python-active-directory
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'Python-AD', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] ) Tweak output file name of source distribution.
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'python-ad', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] )
<commit_before># # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'Python-AD', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] ) <commit_msg>Tweak output file name of source distribution.<commit_after>
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'python-ad', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] )
# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'Python-AD', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] ) Tweak output file name of source distribution.# # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'python-ad', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] )
<commit_before># # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'Python-AD', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] ) <commit_msg>Tweak output file name of source distribution.<commit_after># # This file is part of Python-AD. Python-AD is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # Python-AD is copyright (c) 2007 by the Python-AD authors. See the file # "AUTHORS" for a complete overview. from distutils.core import setup, Extension setup( name = 'python-ad', version = '0.8', description = 'An AD client library for Python', author = 'Geert Jansen', author_email = 'geert@boskant.nl', url = 'http://www.boskant.nl/trac/python-ad', package_dir = {'': 'lib'}, packages = ['ad', 'ad.core', 'ad.protocol', 'ad.util', 'ad.test'], ext_modules = [Extension('ad.protocol.krb5', ['lib/ad/protocol/krb5.c'], libraries=['krb5'])] )
bd823c76c5ada266060c93e45e470e35b0069806
setup.py
setup.py
from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click==6.6', 'pandas==0.18.1', 'scipy==0.17.1', ], extras_require={ 'test': ['pytest==2.9.1'], 'dev': ['pytest==2.9.1', 'sphinx==1.4.1', 'pylint==1.5.4', 'git-pylint-commit-hook==2.1.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ )
from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click>=6.6', 'pandas>=0.18.1', 'scipy>=0.17.1', ], extras_require={ 'test': ['pytest>=2.9.1'], 'dev': ['pytest>=2.9.1', 'sphinx>=1.4.1', 'pylint>=1.5.4', 'git-pylint-commit-hook>=2.1.1', 'pytest-cov>=2.3.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ )
Add pytest-cov and fix change requirements to >=
Add pytest-cov and fix change requirements to >=
Python
mit
tesera/pygypsy,tesera/pygypsy
from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click==6.6', 'pandas==0.18.1', 'scipy==0.17.1', ], extras_require={ 'test': ['pytest==2.9.1'], 'dev': ['pytest==2.9.1', 'sphinx==1.4.1', 'pylint==1.5.4', 'git-pylint-commit-hook==2.1.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ ) Add pytest-cov and fix change requirements to >=
from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click>=6.6', 'pandas>=0.18.1', 'scipy>=0.17.1', ], extras_require={ 'test': ['pytest>=2.9.1'], 'dev': ['pytest>=2.9.1', 'sphinx>=1.4.1', 'pylint>=1.5.4', 'git-pylint-commit-hook>=2.1.1', 'pytest-cov>=2.3.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ )
<commit_before>from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click==6.6', 'pandas==0.18.1', 'scipy==0.17.1', ], extras_require={ 'test': ['pytest==2.9.1'], 'dev': ['pytest==2.9.1', 'sphinx==1.4.1', 'pylint==1.5.4', 'git-pylint-commit-hook==2.1.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ ) <commit_msg>Add pytest-cov and fix change requirements to >=<commit_after>
from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click>=6.6', 'pandas>=0.18.1', 'scipy>=0.17.1', ], extras_require={ 'test': ['pytest>=2.9.1'], 'dev': ['pytest>=2.9.1', 'sphinx>=1.4.1', 'pylint>=1.5.4', 'git-pylint-commit-hook>=2.1.1', 'pytest-cov>=2.3.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ )
from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click==6.6', 'pandas==0.18.1', 'scipy==0.17.1', ], extras_require={ 'test': ['pytest==2.9.1'], 'dev': ['pytest==2.9.1', 'sphinx==1.4.1', 'pylint==1.5.4', 'git-pylint-commit-hook==2.1.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ ) Add pytest-cov and fix change requirements to >=from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click>=6.6', 'pandas>=0.18.1', 'scipy>=0.17.1', ], extras_require={ 'test': ['pytest>=2.9.1'], 'dev': ['pytest>=2.9.1', 'sphinx>=1.4.1', 'pylint>=1.5.4', 'git-pylint-commit-hook>=2.1.1', 'pytest-cov>=2.3.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ )
<commit_before>from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click==6.6', 'pandas==0.18.1', 'scipy==0.17.1', ], extras_require={ 'test': ['pytest==2.9.1'], 'dev': ['pytest==2.9.1', 'sphinx==1.4.1', 'pylint==1.5.4', 'git-pylint-commit-hook==2.1.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ ) <commit_msg>Add pytest-cov and fix change requirements to >=<commit_after>from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.md', encoding='utf-8') as f: long_description = f.read() setup(name='gypsy', version='0.0.1', description=u"Controlling Gypsy modules, and outputs", long_description=long_description, classifiers=[], keywords='', author=u"Julianno Sambatti", author_email='julianno.sambatti@tesera.com', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), zip_safe=False, include_package_data=True, package_data={ 'gypsy': ['data/*'], }, install_requires=[ 'click>=6.6', 'pandas>=0.18.1', 'scipy>=0.17.1', ], extras_require={ 'test': ['pytest>=2.9.1'], 'dev': ['pytest>=2.9.1', 'sphinx>=1.4.1', 'pylint>=1.5.4', 'git-pylint-commit-hook>=2.1.1', 'pytest-cov>=2.3.1'] }, entry_points=""" [console_scripts] gypsy=gypsy.scripts.cli:cli """ )
a372416f846ab3b20b97c87f43bf1827a9b60136
setup.py
setup.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except: kwargs = { 'tests_require': 'mock', 'extras_require': { 'mock': 'mock' } } else: kwargs = {} with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], test_suite='tests', zip_safe=True, **kwargs)
#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except ImportError: tests_require = ['mock'] else: tests_require = [] with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], extras_require={ 'mock:"2" in python_version': ['mock'] }, tests_require = tests_require, test_suite='tests', zip_safe=True)
Implement PEP 246 compliant environment markers
Implement PEP 246 compliant environment markers
Python
mit
remcohaszing/python-syringe
#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except: kwargs = { 'tests_require': 'mock', 'extras_require': { 'mock': 'mock' } } else: kwargs = {} with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], test_suite='tests', zip_safe=True, **kwargs) Implement PEP 246 compliant environment markers
#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except ImportError: tests_require = ['mock'] else: tests_require = [] with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], extras_require={ 'mock:"2" in python_version': ['mock'] }, tests_require = tests_require, test_suite='tests', zip_safe=True)
<commit_before>#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except: kwargs = { 'tests_require': 'mock', 'extras_require': { 'mock': 'mock' } } else: kwargs = {} with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], test_suite='tests', zip_safe=True, **kwargs) <commit_msg>Implement PEP 246 compliant environment markers<commit_after>
#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except ImportError: tests_require = ['mock'] else: tests_require = [] with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], extras_require={ 'mock:"2" in python_version': ['mock'] }, tests_require = tests_require, test_suite='tests', zip_safe=True)
#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except: kwargs = { 'tests_require': 'mock', 'extras_require': { 'mock': 'mock' } } else: kwargs = {} with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], test_suite='tests', zip_safe=True, **kwargs) Implement PEP 246 compliant environment markers#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except ImportError: tests_require = ['mock'] else: tests_require = [] with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], extras_require={ 'mock:"2" in python_version': ['mock'] }, tests_require = tests_require, test_suite='tests', zip_safe=True)
<commit_before>#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except: kwargs = { 'tests_require': 'mock', 'extras_require': { 'mock': 'mock' } } else: kwargs = {} with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], test_suite='tests', zip_safe=True, **kwargs) <commit_msg>Implement PEP 246 compliant environment markers<commit_after>#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except ImportError: tests_require = ['mock'] else: tests_require = [] with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], extras_require={ 'mock:"2" in python_version': ['mock'] }, tests_require = tests_require, test_suite='tests', zip_safe=True)
b912181a35ed7c79fec34cd246aa527e5709e595
setup.py
setup.py
from setuptools import setup, find_packages requires = [ 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
from setuptools import setup, find_packages requires = [ 'configparser', 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
Add configparser to the install_requires list.
Add configparser to the install_requires list.
Python
apache-2.0
nedlowe/amaas-core-sdk-python,paul-rs/amaas-core-sdk-python,amaas-fintech/amaas-core-sdk-python,nedlowe/amaas-core-sdk-python,amaas-fintech/amaas-core-sdk-python,paul-rs/amaas-core-sdk-python
from setuptools import setup, find_packages requires = [ 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, ) Add configparser to the install_requires list.
from setuptools import setup, find_packages requires = [ 'configparser', 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
<commit_before>from setuptools import setup, find_packages requires = [ 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, ) <commit_msg>Add configparser to the install_requires list.<commit_after>
from setuptools import setup, find_packages requires = [ 'configparser', 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
from setuptools import setup, find_packages requires = [ 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, ) Add configparser to the install_requires list.from setuptools import setup, find_packages requires = [ 'configparser', 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
<commit_before>from setuptools import setup, find_packages requires = [ 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, ) <commit_msg>Add configparser to the install_requires list.<commit_after>from setuptools import setup, find_packages requires = [ 'configparser', 'python-dateutil', 'pytz', 'requests', 'simplejson' ] setup( name='amaascore', version='0.1.7', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
8c584840faacbd1409bda4b1be5525c297a72590
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.5', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], )
#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.6', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml', 'copy', 'json'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], )
Fix having special characters in login/password field.
Fix having special characters in login/password field. Signed-off-by: thomnico <5d7b651831a7f5cf7c72a23146042589c88b16b7@googlemail.com>
Python
apache-2.0
thomnico/fortigateconf
#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.5', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], ) Fix having special characters in login/password field. Signed-off-by: thomnico <5d7b651831a7f5cf7c72a23146042589c88b16b7@googlemail.com>
#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.6', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml', 'copy', 'json'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], )
<commit_before>#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.5', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], ) <commit_msg>Fix having special characters in login/password field. Signed-off-by: thomnico <5d7b651831a7f5cf7c72a23146042589c88b16b7@googlemail.com><commit_after>
#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.6', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml', 'copy', 'json'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], )
#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.5', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], ) Fix having special characters in login/password field. Signed-off-by: thomnico <5d7b651831a7f5cf7c72a23146042589c88b16b7@googlemail.com>#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.6', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml', 'copy', 'json'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], )
<commit_before>#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.5', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], ) <commit_msg>Fix having special characters in login/password field. Signed-off-by: thomnico <5d7b651831a7f5cf7c72a23146042589c88b16b7@googlemail.com><commit_after>#!/usr/bin/env python from setuptools import setup def readme(): with open('README.md') as f: return f.read() setup( name='fortiosapi', version='0.10.6', description=('Python modules to use Fortigate APIs' 'full configuration, monitoring, lifecycle rest and ssh'), long_description=readme(), # Valid Classifiers are here: # https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python ', 'Topic :: Security', ], keywords='Fortinet fortigate fortios rest api', install_requires=['requests', 'paramiko', 'oyaml', 'copy', 'json'], author='Nicolas Thomas', author_email='nthomas@fortinet.com', url='https://github.com/fortinet-solutions-cse/fortiosapi', include_package_data=True, packages=['fortiosapi'], )
aa7c1fce28cbfcc8face1abeeeaa1ee6d8421640
setup.py
setup.py
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.0', 'pylint>=2.0.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], )
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.4', 'pylint>=2.3.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], )
Fix install versions of pytest and pylint
Fix install versions of pytest and pylint
Python
mit
carsongee/pytest-pylint
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.0', 'pylint>=2.0.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], ) Fix install versions of pytest and pylint
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.4', 'pylint>=2.3.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], )
<commit_before># -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.0', 'pylint>=2.0.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], ) <commit_msg>Fix install versions of pytest and pylint<commit_after>
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.4', 'pylint>=2.3.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], )
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.0', 'pylint>=2.0.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], ) Fix install versions of pytest and pylint# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.4', 'pylint>=2.3.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], )
<commit_before># -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.0', 'pylint>=2.0.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], ) <commit_msg>Fix install versions of pytest and pylint<commit_after># -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.16.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', packages=['pytest_pylint'], entry_points={'pytest11': ['pylint = pytest_pylint.plugin']}, python_requires=">=3.5", install_requires=['pytest>=5.4', 'pylint>=2.3.0', 'toml>=0.7.1'], setup_requires=['pytest-runner'], tests_require=['coverage', 'pytest-flake8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], )
ed09ed41e2b9486f55f801eee47f08e2a9679b6c
tests/sequence/test_alignment.py
tests/sequence/test_alignment.py
import unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1]) def test_blast_web(self): blast = Blast() with mock.patch('cref.sequence.alignment.NCBIWWW.qblast') as qblast: with open('tests/samples/web_blast.xml') as qblast_results: qblast.return_value = StringIO(qblast_results.read()) results = blast.align('AASSF') self.assertIn('1o61', str(results)) self.assertEqual(len(results), 493) pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs)
import unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1])
Fix broken test after blast web removal
Fix broken test after blast web removal
Python
mit
mchelem/cref2,mchelem/cref2,mchelem/cref2
import unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1]) def test_blast_web(self): blast = Blast() with mock.patch('cref.sequence.alignment.NCBIWWW.qblast') as qblast: with open('tests/samples/web_blast.xml') as qblast_results: qblast.return_value = StringIO(qblast_results.read()) results = blast.align('AASSF') self.assertIn('1o61', str(results)) self.assertEqual(len(results), 493) pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) Fix broken test after blast web removal
import unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1])
<commit_before>import unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1]) def test_blast_web(self): blast = Blast() with mock.patch('cref.sequence.alignment.NCBIWWW.qblast') as qblast: with open('tests/samples/web_blast.xml') as qblast_results: qblast.return_value = StringIO(qblast_results.read()) results = blast.align('AASSF') self.assertIn('1o61', str(results)) self.assertEqual(len(results), 493) pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) <commit_msg>Fix broken test after blast web removal<commit_after>
import unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1])
import unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1]) def test_blast_web(self): blast = Blast() with mock.patch('cref.sequence.alignment.NCBIWWW.qblast') as qblast: with open('tests/samples/web_blast.xml') as qblast_results: qblast.return_value = StringIO(qblast_results.read()) results = blast.align('AASSF') self.assertIn('1o61', str(results)) self.assertEqual(len(results), 493) pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) Fix broken test after blast web removalimport unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1])
<commit_before>import unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1]) def test_blast_web(self): blast = Blast() with mock.patch('cref.sequence.alignment.NCBIWWW.qblast') as qblast: with open('tests/samples/web_blast.xml') as qblast_results: qblast.return_value = StringIO(qblast_results.read()) results = blast.align('AASSF') self.assertIn('1o61', str(results)) self.assertEqual(len(results), 493) pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) <commit_msg>Fix broken test after blast web removal<commit_after>import unittest from unittest import mock from io import StringIO from cref.sequence.alignment import Blast class AlignmentTestCase(unittest.TestCase): def test_blast_local(self): blast = Blast('data/blastdb/pdbseqres') results = blast.align('AASSF') pdbs = {result.pdb_code for result in results} self.assertIn('1o61', pdbs) def test_blast_local_error(self): blast = Blast('db') with self.assertRaises(Exception) as cm: blast.align('AASSF') self.assertIn('Database error', cm.exception.args[-1])
a6ac5c901a1b677992599d6aac231e01c5e7a39d
tests/test_thread_concurrency.py
tests/test_thread_concurrency.py
''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' import json from tests.test_base import TestBase from batch_requests.settings import br_settings from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBase): ''' Tests sequential and concurrent execution. ''' # FIXME: Find the better way to manage / update settings. def setUp(self): ''' Change the concurrency settings. ''' self.number_workers = 10 self.orig_executor = br_settings.executor def tearDown(self): # Restore the original batch requests settings. br_settings.executor = self.orig_executor def test_thread_concurrency_response(self): ''' Make a request with sequential and thread based executor and compare the response. ''' data = json.dumps({"text": "Batch"}) # Make a batch call for GET, POST and PUT request. get_req = ("get", "/views/", '', {}) post_req = ("post", "/views/", data, {"content_type": "text/plain"}) put_req = ("put", "/views/", data, {"content_type": "text/plain"}) # Get the response for a batch request. batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) # FIXME: Find the better way to manage / update settings. # Update the settings. br_settings.executor = ThreadBasedExecutor(self.number_workers) threaded_batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) self.assertEqual(batch_requests.content, threaded_batch_requests.content, "Sequential and concurrent response not same!")
''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' from tests.test_concurrency_base import TestBaseConcurrency from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBaseConcurrency): ''' Tests sequential and concurrent execution. ''' def get_executor(self): ''' Returns the executor to use for running tests defined in this suite. ''' return ThreadBasedExecutor(self.number_workers) def test_thread_concurrency_response(self): ''' Make a request with sequential and concurrency based executor and compare the response. ''' self.compare_seq_and_concurrent_req()
Refactor thread based concurrency tests
Refactor thread based concurrency tests
Python
mit
tanwanirahul/django-batch-requests
''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' import json from tests.test_base import TestBase from batch_requests.settings import br_settings from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBase): ''' Tests sequential and concurrent execution. ''' # FIXME: Find the better way to manage / update settings. def setUp(self): ''' Change the concurrency settings. ''' self.number_workers = 10 self.orig_executor = br_settings.executor def tearDown(self): # Restore the original batch requests settings. br_settings.executor = self.orig_executor def test_thread_concurrency_response(self): ''' Make a request with sequential and thread based executor and compare the response. ''' data = json.dumps({"text": "Batch"}) # Make a batch call for GET, POST and PUT request. get_req = ("get", "/views/", '', {}) post_req = ("post", "/views/", data, {"content_type": "text/plain"}) put_req = ("put", "/views/", data, {"content_type": "text/plain"}) # Get the response for a batch request. batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) # FIXME: Find the better way to manage / update settings. # Update the settings. br_settings.executor = ThreadBasedExecutor(self.number_workers) threaded_batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) self.assertEqual(batch_requests.content, threaded_batch_requests.content, "Sequential and concurrent response not same!") Refactor thread based concurrency tests
''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' from tests.test_concurrency_base import TestBaseConcurrency from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBaseConcurrency): ''' Tests sequential and concurrent execution. ''' def get_executor(self): ''' Returns the executor to use for running tests defined in this suite. ''' return ThreadBasedExecutor(self.number_workers) def test_thread_concurrency_response(self): ''' Make a request with sequential and concurrency based executor and compare the response. ''' self.compare_seq_and_concurrent_req()
<commit_before>''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' import json from tests.test_base import TestBase from batch_requests.settings import br_settings from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBase): ''' Tests sequential and concurrent execution. ''' # FIXME: Find the better way to manage / update settings. def setUp(self): ''' Change the concurrency settings. ''' self.number_workers = 10 self.orig_executor = br_settings.executor def tearDown(self): # Restore the original batch requests settings. br_settings.executor = self.orig_executor def test_thread_concurrency_response(self): ''' Make a request with sequential and thread based executor and compare the response. ''' data = json.dumps({"text": "Batch"}) # Make a batch call for GET, POST and PUT request. get_req = ("get", "/views/", '', {}) post_req = ("post", "/views/", data, {"content_type": "text/plain"}) put_req = ("put", "/views/", data, {"content_type": "text/plain"}) # Get the response for a batch request. batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) # FIXME: Find the better way to manage / update settings. # Update the settings. br_settings.executor = ThreadBasedExecutor(self.number_workers) threaded_batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) self.assertEqual(batch_requests.content, threaded_batch_requests.content, "Sequential and concurrent response not same!") <commit_msg>Refactor thread based concurrency tests<commit_after>
''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' from tests.test_concurrency_base import TestBaseConcurrency from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBaseConcurrency): ''' Tests sequential and concurrent execution. ''' def get_executor(self): ''' Returns the executor to use for running tests defined in this suite. ''' return ThreadBasedExecutor(self.number_workers) def test_thread_concurrency_response(self): ''' Make a request with sequential and concurrency based executor and compare the response. ''' self.compare_seq_and_concurrent_req()
''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' import json from tests.test_base import TestBase from batch_requests.settings import br_settings from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBase): ''' Tests sequential and concurrent execution. ''' # FIXME: Find the better way to manage / update settings. def setUp(self): ''' Change the concurrency settings. ''' self.number_workers = 10 self.orig_executor = br_settings.executor def tearDown(self): # Restore the original batch requests settings. br_settings.executor = self.orig_executor def test_thread_concurrency_response(self): ''' Make a request with sequential and thread based executor and compare the response. ''' data = json.dumps({"text": "Batch"}) # Make a batch call for GET, POST and PUT request. get_req = ("get", "/views/", '', {}) post_req = ("post", "/views/", data, {"content_type": "text/plain"}) put_req = ("put", "/views/", data, {"content_type": "text/plain"}) # Get the response for a batch request. batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) # FIXME: Find the better way to manage / update settings. # Update the settings. br_settings.executor = ThreadBasedExecutor(self.number_workers) threaded_batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) self.assertEqual(batch_requests.content, threaded_batch_requests.content, "Sequential and concurrent response not same!") Refactor thread based concurrency tests''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' from tests.test_concurrency_base import TestBaseConcurrency from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBaseConcurrency): ''' Tests sequential and concurrent execution. ''' def get_executor(self): ''' Returns the executor to use for running tests defined in this suite. ''' return ThreadBasedExecutor(self.number_workers) def test_thread_concurrency_response(self): ''' Make a request with sequential and concurrency based executor and compare the response. ''' self.compare_seq_and_concurrent_req()
<commit_before>''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' import json from tests.test_base import TestBase from batch_requests.settings import br_settings from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBase): ''' Tests sequential and concurrent execution. ''' # FIXME: Find the better way to manage / update settings. def setUp(self): ''' Change the concurrency settings. ''' self.number_workers = 10 self.orig_executor = br_settings.executor def tearDown(self): # Restore the original batch requests settings. br_settings.executor = self.orig_executor def test_thread_concurrency_response(self): ''' Make a request with sequential and thread based executor and compare the response. ''' data = json.dumps({"text": "Batch"}) # Make a batch call for GET, POST and PUT request. get_req = ("get", "/views/", '', {}) post_req = ("post", "/views/", data, {"content_type": "text/plain"}) put_req = ("put", "/views/", data, {"content_type": "text/plain"}) # Get the response for a batch request. batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) # FIXME: Find the better way to manage / update settings. # Update the settings. br_settings.executor = ThreadBasedExecutor(self.number_workers) threaded_batch_requests = self.make_multiple_batch_request([get_req, post_req, put_req]) self.assertEqual(batch_requests.content, threaded_batch_requests.content, "Sequential and concurrent response not same!") <commit_msg>Refactor thread based concurrency tests<commit_after>''' @author: Rahul Tanwani @summary: Test cases to make sure sequential execution and concurrent execution return the same response. ''' from tests.test_concurrency_base import TestBaseConcurrency from batch_requests.concurrent.executor import ThreadBasedExecutor class TestThreadConcurrency(TestBaseConcurrency): ''' Tests sequential and concurrent execution. ''' def get_executor(self): ''' Returns the executor to use for running tests defined in this suite. ''' return ThreadBasedExecutor(self.number_workers) def test_thread_concurrency_response(self): ''' Make a request with sequential and concurrency based executor and compare the response. ''' self.compare_seq_and_concurrent_req()
966f761a5dd971ecbdd15771091fdedb6299c3f4
setup.py
setup.py
import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], )
import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], )
Support for Python 2.7 and PyPy in the classifiers!
Support for Python 2.7 and PyPy in the classifiers! ✨
Python
mit
njsmith/h11,python-hyper/h11
import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], ) Support for Python 2.7 and PyPy in the classifiers! ✨
import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], )
<commit_before>import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], ) <commit_msg>Support for Python 2.7 and PyPy in the classifiers! ✨<commit_after>
import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], )
import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], ) Support for Python 2.7 and PyPy in the classifiers! ✨import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], )
<commit_before>import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], ) <commit_msg>Support for Python 2.7 and PyPy in the classifiers! ✨<commit_after>import sys from setuptools import setup, find_packages # defines __version__ exec(open("h11/_version.py").read()) setup( name="h11", version=__version__, description= "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1", long_description=open("README.rst").read(), author="Nathaniel J. Smith", author_email="njs@pobox.com", license="MIT", packages=find_packages(), url="https://github.com/njsmith/h11", # This means, just install *everything* you see under zs/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: include_package_data=True, classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Internet :: WWW/HTTP", "Topic :: System :: Networking", ], )
c4b4d1f81b5536e87db0698c9f0418b56121ae7d
setup.py
setup.py
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.3', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), )
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.4', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), )
Increment version to trigger release of previous changes
Increment version to trigger release of previous changes
Python
mit
slank/awsgi
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.3', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), ) Increment version to trigger release of previous changes
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.4', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), )
<commit_before>from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.3', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), ) <commit_msg>Increment version to trigger release of previous changes<commit_after>
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.4', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), )
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.3', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), ) Increment version to trigger release of previous changesfrom setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.4', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), )
<commit_before>from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.3', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), ) <commit_msg>Increment version to trigger release of previous changes<commit_after>from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='aws-wsgi', version='0.2.4', description='WSGI adapter for AWS API Gateway/Lambda Proxy Integration', long_description=long_description, url='https://github.com/slank/awsgi', author='Matthew Wedgwood', author_email='github+awsgi@smacky.org', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='wsgi aws lambda api gateway', packages=find_packages(exclude=['contrib', 'docs', 'tests']), )
1096bc339caf0ba329332633d8b9170fb8940f6f
start.py
start.py
import cursingspock from spockbot import Client from spockbot.plugins import default_plugins as plugins from bat import bat, command plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565)
import cursingspock from spockbot import Client from spockbot.plugins import default_plugins from bat import bat, command plugins = default_plugins.copy() plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565)
Copy default plugins and extend
Copy default plugins and extend
Python
mit
Gjum/Bat
import cursingspock from spockbot import Client from spockbot.plugins import default_plugins as plugins from bat import bat, command plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565) Copy default plugins and extend
import cursingspock from spockbot import Client from spockbot.plugins import default_plugins from bat import bat, command plugins = default_plugins.copy() plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565)
<commit_before>import cursingspock from spockbot import Client from spockbot.plugins import default_plugins as plugins from bat import bat, command plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565) <commit_msg>Copy default plugins and extend<commit_after>
import cursingspock from spockbot import Client from spockbot.plugins import default_plugins from bat import bat, command plugins = default_plugins.copy() plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565)
import cursingspock from spockbot import Client from spockbot.plugins import default_plugins as plugins from bat import bat, command plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565) Copy default plugins and extendimport cursingspock from spockbot import Client from spockbot.plugins import default_plugins from bat import bat, command plugins = default_plugins.copy() plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565)
<commit_before>import cursingspock from spockbot import Client from spockbot.plugins import default_plugins as plugins from bat import bat, command plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565) <commit_msg>Copy default plugins and extend<commit_after>import cursingspock from spockbot import Client from spockbot.plugins import default_plugins from bat import bat, command plugins = default_plugins.copy() plugins.extend([ ('bat', bat.BatPlugin), ('commands', command.CommandPlugin), ('curses', cursingspock.CursesPlugin), ]) # login_credentials should contain a dict with 'username' and 'password' #from login_credentials import settings settings = { 'start': {'username': 'Bat'}, 'auth': {'online_mode': False}, } client = Client(plugins=plugins, settings=settings) client.start('localhost', 25565)
d1e3bfe83fb2a06ed6ff71c3b7c4242296f90f76
blog/views.py
blog/views.py
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries})
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created')[:5] return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries})
Reduce number of entries shown on index
Reduce number of entries shown on index
Python
mit
n2o/labbook,n2o/labbook,n2o/labbook
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries}) Reduce number of entries shown on index
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created')[:5] return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries})
<commit_before>from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries}) <commit_msg>Reduce number of entries shown on index<commit_after>
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created')[:5] return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries})
from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries}) Reduce number of entries shown on indexfrom django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created')[:5] return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries})
<commit_before>from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries}) <commit_msg>Reduce number of entries shown on index<commit_after>from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, get_list_or_404 from django.db.models import Q from .models import Entry @login_required def overview(request, category="Allgemein"): entries = Entry.objects.all().order_by('-created')[:5] return render(request, 'blog/list.html', {'entries': entries}) def year(request, year): entries = Entry.objects.filter(created__year=year).order_by('-created') return render(request, 'blog/list.html', {'entries': entries}) def month(request, year, month): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month) return render(request, 'blog/list.html', {'entries': entries}) def day(request, year, month, day): entries = get_list_or_404(Entry.objects.order_by('-created'), created__year=year, created__month=month, created__day=day) return render(request, 'blog/list.html', {'entries': entries}) def tag(request, tag): try: entries = Entry.objects.filter(Q(tags=tag)).order_by('-created') except Entry.DoesNotExist: raise Http404("Dieser Beitrag konnte leider nicht gefunden werden.") return render(request, 'blog/list.html', {'entries': entries})
0f1d10f452066fb304f24006ac641860f4f6b7d9
bluebottle/utils/migrations/0007_auto_20210825_1018.py
bluebottle/utils/migrations/0007_auto_20210825_1018.py
# Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: language = Language.objects.first() language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ]
# Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: try: language = Language.objects.get() except Language.DoesNotExist: return language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ]
Fix migration if no language exists
Fix migration if no language exists
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
# Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: language = Language.objects.first() language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ] Fix migration if no language exists
# Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: try: language = Language.objects.get() except Language.DoesNotExist: return language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ]
<commit_before># Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: language = Language.objects.first() language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ] <commit_msg>Fix migration if no language exists<commit_after>
# Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: try: language = Language.objects.get() except Language.DoesNotExist: return language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ]
# Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: language = Language.objects.first() language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ] Fix migration if no language exists# Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: try: language = Language.objects.get() except Language.DoesNotExist: return language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ]
<commit_before># Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: language = Language.objects.first() language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ] <commit_msg>Fix migration if no language exists<commit_after># Generated by Django 2.2.20 on 2021-08-25 08:18 from django.db import migrations from bluebottle.clients import properties def set_default(apps, schema_editor): try: Language = apps.get_model('utils', 'Language') language = Language.objects.get(code=properties.LANGUAGE_CODE) except Language.DoesNotExist: try: language = Language.objects.get() except Language.DoesNotExist: return language.default = True language.save() class Migration(migrations.Migration): dependencies = [ ('utils', '0006_auto_20210825_1018'), ] operations = [ migrations.RunPython(set_default, migrations.RunPython.noop) ]
d82b908721a9eaedee119f8cceab7eec1bec5f84
src/chime_dash/__init__.py
src/chime_dash/__init__.py
""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.components import Body from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Body(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App
""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.pages.root import Root from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Root(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App
Fix to use Root Page vs Body Component
Fix to use Root Page vs Body Component
Python
mit
CodeForPhilly/chime,CodeForPhilly/chime,CodeForPhilly/chime
""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.components import Body from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Body(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App Fix to use Root Page vs Body Component
""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.pages.root import Root from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Root(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App
<commit_before>""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.components import Body from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Body(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App <commit_msg>Fix to use Root Page vs Body Component<commit_after>
""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.pages.root import Root from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Root(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App
""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.components import Body from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Body(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App Fix to use Root Page vs Body Component""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.pages.root import Root from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Root(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App
<commit_before>""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.components import Body from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Body(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App <commit_msg>Fix to use Root Page vs Body Component<commit_after>""" chime_dash/app dash instance defined here """ from dash import Dash from typing import TypeVar from chime_dash.app.config import from_object from penn_chime.settings import get_defaults from chime_dash.app.pages.root import Root from chime_dash.app.utils.callbacks import wrap_callbacks DashAppInstance = TypeVar('DashAppInstance') DEFAULTS = get_defaults() def create_app(context: str = 'prod') -> DashAppInstance: """ create_app initializes the app instance Args: context (str, optional): One of either 'prod', 'dev', 'testing. Defaults to 'prod' where dash.Dash.run_server(debug=False). Change to 'dev' or 'test' to set debug to true. Returns: Env: Config variables based on context argument received DashAppInstance: Dash instance with appropriate configuration settings """ Env = from_object(context) LANGUAGE = Env.LANG body = Root(LANGUAGE, DEFAULTS) App = Dash( __name__, external_stylesheets=body.external_stylesheets, external_scripts=body.external_scripts, ) App.title = Env.CHIME_TITLE App.layout = body.html wrap_callbacks(App) return Env, App
1bc1c62b5d2bd5edd6c375c91540a6597b3c47cc
lc226_invert_binary_tree.py
lc226_invert_binary_tree.py
"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ pass def main(): pass if __name__ == '__main__': main()
"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class SolutionRecur(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode Time complexity: O(n). Space complexity: O(n). """ if not root: return None left = self.invertTree(root.left) right = self.invertTree(root.right) root.left = right root.right = left return root def main(): root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(7) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.left = TreeNode(6) root.right.right = TreeNode(9) root = SolutionRecur().invertTree(root) print root.val # Should be 4. print root.left.val # Should be 7. print root.right.val # Should be 2. print root.left.left.val # Should be 9. print root.left.right.val # Should be 6. print root.right.left.val # Should be 3. print root.right.right.val # Should be 1. if __name__ == '__main__': main()
Complete recur w/ time/space complexity
Complete recur w/ time/space complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ pass def main(): pass if __name__ == '__main__': main() Complete recur w/ time/space complexity
"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class SolutionRecur(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode Time complexity: O(n). Space complexity: O(n). """ if not root: return None left = self.invertTree(root.left) right = self.invertTree(root.right) root.left = right root.right = left return root def main(): root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(7) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.left = TreeNode(6) root.right.right = TreeNode(9) root = SolutionRecur().invertTree(root) print root.val # Should be 4. print root.left.val # Should be 7. print root.right.val # Should be 2. print root.left.left.val # Should be 9. print root.left.right.val # Should be 6. print root.right.left.val # Should be 3. print root.right.right.val # Should be 1. if __name__ == '__main__': main()
<commit_before>"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ pass def main(): pass if __name__ == '__main__': main() <commit_msg>Complete recur w/ time/space complexity<commit_after>
"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class SolutionRecur(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode Time complexity: O(n). Space complexity: O(n). """ if not root: return None left = self.invertTree(root.left) right = self.invertTree(root.right) root.left = right root.right = left return root def main(): root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(7) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.left = TreeNode(6) root.right.right = TreeNode(9) root = SolutionRecur().invertTree(root) print root.val # Should be 4. print root.left.val # Should be 7. print root.right.val # Should be 2. print root.left.left.val # Should be 9. print root.left.right.val # Should be 6. print root.right.left.val # Should be 3. print root.right.right.val # Should be 1. if __name__ == '__main__': main()
"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ pass def main(): pass if __name__ == '__main__': main() Complete recur w/ time/space complexity"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class SolutionRecur(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode Time complexity: O(n). Space complexity: O(n). """ if not root: return None left = self.invertTree(root.left) right = self.invertTree(root.right) root.left = right root.right = left return root def main(): root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(7) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.left = TreeNode(6) root.right.right = TreeNode(9) root = SolutionRecur().invertTree(root) print root.val # Should be 4. print root.left.val # Should be 7. print root.right.val # Should be 2. print root.left.left.val # Should be 9. print root.left.right.val # Should be 6. print root.right.left.val # Should be 3. print root.right.right.val # Should be 1. if __name__ == '__main__': main()
<commit_before>"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ pass def main(): pass if __name__ == '__main__': main() <commit_msg>Complete recur w/ time/space complexity<commit_after>"""Leetcode 226. Invert Binary Tree Easy URL: https://leetcode.com/problems/invert-binary-tree/ Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class SolutionRecur(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode Time complexity: O(n). Space complexity: O(n). """ if not root: return None left = self.invertTree(root.left) right = self.invertTree(root.right) root.left = right root.right = left return root def main(): root = TreeNode(4) root.left = TreeNode(2) root.right = TreeNode(7) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right.left = TreeNode(6) root.right.right = TreeNode(9) root = SolutionRecur().invertTree(root) print root.val # Should be 4. print root.left.val # Should be 7. print root.right.val # Should be 2. print root.left.left.val # Should be 9. print root.left.right.val # Should be 6. print root.right.left.val # Should be 3. print root.right.right.val # Should be 1. if __name__ == '__main__': main()
15479b3baea8d0f5cb58bf7d22321646ac4513bc
spacy/lang/nl/lex_attrs.py
spacy/lang/nl/lex_attrs.py
# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): # This only does the most basic check for whether a token is a digit # or matches one of the number words. In order to handle numbers like # "drieëntwintig", more work is required. # See this discussion: https://github.com/explosion/spaCy/pull/1177 text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
Add comment to like_num re: future work
Add comment to like_num re: future work
Python
mit
spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy
# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num } Add comment to like_num re: future work
# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): # This only does the most basic check for whether a token is a digit # or matches one of the number words. In order to handle numbers like # "drieëntwintig", more work is required. # See this discussion: https://github.com/explosion/spaCy/pull/1177 text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
<commit_before># coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num } <commit_msg>Add comment to like_num re: future work<commit_after>
# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): # This only does the most basic check for whether a token is a digit # or matches one of the number words. In order to handle numbers like # "drieëntwintig", more work is required. # See this discussion: https://github.com/explosion/spaCy/pull/1177 text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num } Add comment to like_num re: future work# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): # This only does the most basic check for whether a token is a digit # or matches one of the number words. In order to handle numbers like # "drieëntwintig", more work is required. # See this discussion: https://github.com/explosion/spaCy/pull/1177 text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
<commit_before># coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num } <commit_msg>Add comment to like_num re: future work<commit_after># coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = set(""" nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd duizend miljoen miljard biljoen biljard triljoen triljard """.split()) _ordinal_words = set(""" eerste tweede derde vierde vijfde zesde zevende achtste negende tiende elfde twaalfde dertiende veertiende twintigste dertigste veertigste vijftigste zestigste zeventigste tachtigste negentigste honderdste duizendste miljoenste miljardste biljoenste biljardste triljoenste triljardste """.split()) def like_num(text): # This only does the most basic check for whether a token is a digit # or matches one of the number words. In order to handle numbers like # "drieëntwintig", more work is required. # See this discussion: https://github.com/explosion/spaCy/pull/1177 text = text.replace(',', '').replace('.', '') if text.isdigit(): return True if text.count('/') == 1: num, denom = text.split('/') if num.isdigit() and denom.isdigit(): return True if text in _num_words: return True return False LEX_ATTRS = { LIKE_NUM: like_num }
f23a3bbddaf3ab650b8833bbb23fb9666819567c
project/project_name/settings/staticmedia.py
project/project_name/settings/staticmedia.py
from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, 'assets')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/'
from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, '.collectedstatic')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/'
Call a spade a spade.
Call a spade a spade.
Python
mit
bretth/django-pavlova-project,bretth/django-pavlova-project,bretth/django-pavlova-project
from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, 'assets')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' Call a spade a spade.
from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, '.collectedstatic')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/'
<commit_before>from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, 'assets')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' <commit_msg>Call a spade a spade.<commit_after>
from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, '.collectedstatic')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/'
from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, 'assets')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' Call a spade a spade.from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, '.collectedstatic')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/'
<commit_before>from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, 'assets')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' <commit_msg>Call a spade a spade.<commit_after>from os.path import join, normpath from .base import SITE_ROOT class LocalStatic(object): """ Static File Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = normpath(join(SITE_ROOT, '.collectedstatic')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( normpath(join(SITE_ROOT, 'static')), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) class LocalMedia(object): """ Media Configuration """ # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/'
dad7508aa6fc3f0b97975f0985c666fdfc191035
api/__init__.py
api/__init__.py
from flask import Flask DB_CONNECTION = "host='localhost' port=5432 user='postgres' password='secret' dbname='antismash'" SQLALCHEMY_DATABASE_URI = 'postgres://postgres:secret@localhost:5432/antismash' app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers
import os from flask import Flask SQLALCHEMY_DATABASE_URI = os.getenv('AS_DB_URI', 'postgres://postgres:secret@localhost:5432/antismash') app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers
Allow overriding database URI from command line
api: Allow overriding database URI from command line Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk>
Python
agpl-3.0
antismash/db-api,antismash/db-api
from flask import Flask DB_CONNECTION = "host='localhost' port=5432 user='postgres' password='secret' dbname='antismash'" SQLALCHEMY_DATABASE_URI = 'postgres://postgres:secret@localhost:5432/antismash' app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers api: Allow overriding database URI from command line Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk>
import os from flask import Flask SQLALCHEMY_DATABASE_URI = os.getenv('AS_DB_URI', 'postgres://postgres:secret@localhost:5432/antismash') app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers
<commit_before>from flask import Flask DB_CONNECTION = "host='localhost' port=5432 user='postgres' password='secret' dbname='antismash'" SQLALCHEMY_DATABASE_URI = 'postgres://postgres:secret@localhost:5432/antismash' app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers <commit_msg>api: Allow overriding database URI from command line Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk><commit_after>
import os from flask import Flask SQLALCHEMY_DATABASE_URI = os.getenv('AS_DB_URI', 'postgres://postgres:secret@localhost:5432/antismash') app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers
from flask import Flask DB_CONNECTION = "host='localhost' port=5432 user='postgres' password='secret' dbname='antismash'" SQLALCHEMY_DATABASE_URI = 'postgres://postgres:secret@localhost:5432/antismash' app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers api: Allow overriding database URI from command line Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk>import os from flask import Flask SQLALCHEMY_DATABASE_URI = os.getenv('AS_DB_URI', 'postgres://postgres:secret@localhost:5432/antismash') app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers
<commit_before>from flask import Flask DB_CONNECTION = "host='localhost' port=5432 user='postgres' password='secret' dbname='antismash'" SQLALCHEMY_DATABASE_URI = 'postgres://postgres:secret@localhost:5432/antismash' app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers <commit_msg>api: Allow overriding database URI from command line Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk><commit_after>import os from flask import Flask SQLALCHEMY_DATABASE_URI = os.getenv('AS_DB_URI', 'postgres://postgres:secret@localhost:5432/antismash') app = Flask(__name__) app.config.from_object(__name__) from .models import db db.init_app(app) from . import api from . import error_handlers
c08d322362fed3575033a438fc42fe9c3ee29145
vesper/external_urls.py
vesper/external_urls.py
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = True """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = False """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
Configure documentation version for release.
Configure documentation version for release.
Python
mit
HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = True """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper' Configure documentation version for release.
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = False """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
<commit_before>""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = True """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper' <commit_msg>Configure documentation version for release.<commit_after>
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = False """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = True """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper' Configure documentation version for release.""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = False """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
<commit_before>""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = True """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper' <commit_msg>Configure documentation version for release.<commit_after>""" Functions that return external URLs, for example for the Vesper documentation. """ import vesper.version as vesper_version _USE_LATEST_DOCUMENTATION_VERSION = False """Set this `True` during development, `False` for release.""" def _create_documentation_url(): if _USE_LATEST_DOCUMENTATION_VERSION: doc_version = 'latest' else: doc_version = vesper_version.full_version return 'https://vesper.readthedocs.io/en/' + doc_version + '/' def _create_tutorial_url(): return _create_documentation_url() + 'tutorial.html' documentation_url = _create_documentation_url() tutorial_url = _create_tutorial_url() source_code_url = 'https://github.com/HaroldMills/Vesper'
a264754c177237e2cfd10a1eb96994a3d4b8fd4a
quizzes.py
quizzes.py
from database import QuizDB db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz(Base): def __init__(self, id): self.id = id QUESTION_HASH = "{0}:question".format(self.id) ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(QUESTION_HASH) == db.hlen(ANSWER_HASH) q_id = max([int(i) for i in db.hkeys(QUESTION_HASH)]) + 1 db.hset(QUESTION_HASH, q_id, question) db.hset(ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(QUESTION_HASH, q_id) db.hdel(ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(ANSWER_HASH, q_id, updated_answer)
from database import QuizDB import config db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz: QUESTION_HASH = '' ANSWER_HASH = '' def __init__(self, id): self.id = id self.QUESTION_HASH = "{0}:question".format(self.id) self.ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(self.QUESTION_HASH) == db.hlen(self.ANSWER_HASH) questions = db.hkeys(self.QUESTION_HASH) if len(questions) > 0: q_id = max([int(i) for i in db.hkeys(self.QUESTION_HASH)]) + 1 else: q_id = 0 db.hset(self.QUESTION_HASH, q_id, question) db.hset(self.ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(self.QUESTION_HASH, q_id) db.hdel(self.ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(self.QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(self.ANSWER_HASH, q_id, updated_answer)
Fix problems w/ class variables and fix bug with max function on an empty set
Fix problems w/ class variables and fix bug with max function on an empty set
Python
bsd-2-clause
estreeper/quizalicious,estreeper/quizalicious,estreeper/quizalicious
from database import QuizDB db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz(Base): def __init__(self, id): self.id = id QUESTION_HASH = "{0}:question".format(self.id) ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(QUESTION_HASH) == db.hlen(ANSWER_HASH) q_id = max([int(i) for i in db.hkeys(QUESTION_HASH)]) + 1 db.hset(QUESTION_HASH, q_id, question) db.hset(ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(QUESTION_HASH, q_id) db.hdel(ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(ANSWER_HASH, q_id, updated_answer) Fix problems w/ class variables and fix bug with max function on an empty set
from database import QuizDB import config db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz: QUESTION_HASH = '' ANSWER_HASH = '' def __init__(self, id): self.id = id self.QUESTION_HASH = "{0}:question".format(self.id) self.ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(self.QUESTION_HASH) == db.hlen(self.ANSWER_HASH) questions = db.hkeys(self.QUESTION_HASH) if len(questions) > 0: q_id = max([int(i) for i in db.hkeys(self.QUESTION_HASH)]) + 1 else: q_id = 0 db.hset(self.QUESTION_HASH, q_id, question) db.hset(self.ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(self.QUESTION_HASH, q_id) db.hdel(self.ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(self.QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(self.ANSWER_HASH, q_id, updated_answer)
<commit_before>from database import QuizDB db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz(Base): def __init__(self, id): self.id = id QUESTION_HASH = "{0}:question".format(self.id) ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(QUESTION_HASH) == db.hlen(ANSWER_HASH) q_id = max([int(i) for i in db.hkeys(QUESTION_HASH)]) + 1 db.hset(QUESTION_HASH, q_id, question) db.hset(ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(QUESTION_HASH, q_id) db.hdel(ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(ANSWER_HASH, q_id, updated_answer) <commit_msg>Fix problems w/ class variables and fix bug with max function on an empty set<commit_after>
from database import QuizDB import config db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz: QUESTION_HASH = '' ANSWER_HASH = '' def __init__(self, id): self.id = id self.QUESTION_HASH = "{0}:question".format(self.id) self.ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(self.QUESTION_HASH) == db.hlen(self.ANSWER_HASH) questions = db.hkeys(self.QUESTION_HASH) if len(questions) > 0: q_id = max([int(i) for i in db.hkeys(self.QUESTION_HASH)]) + 1 else: q_id = 0 db.hset(self.QUESTION_HASH, q_id, question) db.hset(self.ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(self.QUESTION_HASH, q_id) db.hdel(self.ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(self.QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(self.ANSWER_HASH, q_id, updated_answer)
from database import QuizDB db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz(Base): def __init__(self, id): self.id = id QUESTION_HASH = "{0}:question".format(self.id) ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(QUESTION_HASH) == db.hlen(ANSWER_HASH) q_id = max([int(i) for i in db.hkeys(QUESTION_HASH)]) + 1 db.hset(QUESTION_HASH, q_id, question) db.hset(ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(QUESTION_HASH, q_id) db.hdel(ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(ANSWER_HASH, q_id, updated_answer) Fix problems w/ class variables and fix bug with max function on an empty setfrom database import QuizDB import config db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz: QUESTION_HASH = '' ANSWER_HASH = '' def __init__(self, id): self.id = id self.QUESTION_HASH = "{0}:question".format(self.id) self.ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(self.QUESTION_HASH) == db.hlen(self.ANSWER_HASH) questions = db.hkeys(self.QUESTION_HASH) if len(questions) > 0: q_id = max([int(i) for i in db.hkeys(self.QUESTION_HASH)]) + 1 else: q_id = 0 db.hset(self.QUESTION_HASH, q_id, question) db.hset(self.ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(self.QUESTION_HASH, q_id) db.hdel(self.ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(self.QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(self.ANSWER_HASH, q_id, updated_answer)
<commit_before>from database import QuizDB db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz(Base): def __init__(self, id): self.id = id QUESTION_HASH = "{0}:question".format(self.id) ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(QUESTION_HASH) == db.hlen(ANSWER_HASH) q_id = max([int(i) for i in db.hkeys(QUESTION_HASH)]) + 1 db.hset(QUESTION_HASH, q_id, question) db.hset(ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(QUESTION_HASH, q_id) db.hdel(ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(ANSWER_HASH, q_id, updated_answer) <commit_msg>Fix problems w/ class variables and fix bug with max function on an empty set<commit_after>from database import QuizDB import config db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT) class Quiz: QUESTION_HASH = '' ANSWER_HASH = '' def __init__(self, id): self.id = id self.QUESTION_HASH = "{0}:question".format(self.id) self.ANSWER_HASH = "{0}:answer".format(self.id) def new_card(self, question, answer): assert db.hlen(self.QUESTION_HASH) == db.hlen(self.ANSWER_HASH) questions = db.hkeys(self.QUESTION_HASH) if len(questions) > 0: q_id = max([int(i) for i in db.hkeys(self.QUESTION_HASH)]) + 1 else: q_id = 0 db.hset(self.QUESTION_HASH, q_id, question) db.hset(self.ANSWER_HASH, q_id, answer) def delete_card(self, q_id): db.hdel(self.QUESTION_HASH, q_id) db.hdel(self.ANSWER_HASH, q_id) def update_question(self, q_id, updated_question): db.hset(self.QUESTION_HASH, q_id, updated_question) def update_answer(self, q_id, updated_answer): db.hset(self.ANSWER_HASH, q_id, updated_answer)
0f6fc70278ce67dfcb0468d0913e349ec6b0a169
tndata_backend/utils/decorators.py
tndata_backend/utils/decorators.py
from django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using it's first argument to set a cache key. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the amove `get_stuff` method, obj.id will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first arg & use as the cache key obj_id = getattr(args[1], "id", str(args[1])) key = cache_key.format(obj_id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate
from django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using the ID attribute of it's first argument to set a cache key. NOTE: If this first argument for the cached method doesn't have an ID attribute, nothing will happen. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the above `get_stuff` method, `obj.id` will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first objected passed into the function & use # its id attribute as part of the cache key cache_object = args[1] if not hasattr(cache_object, 'id'): return None # just bail if there's no ID. key = cache_key.format(cache_object.id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate
Update for cached_method so it doesn't try to do anythin if the first argument doesn't have an ID attribute
Update for cached_method so it doesn't try to do anythin if the first argument doesn't have an ID attribute
Python
mit
izzyalonso/tndata_backend,izzyalonso/tndata_backend,tndatacommons/tndata_backend,tndatacommons/tndata_backend,izzyalonso/tndata_backend,tndatacommons/tndata_backend,tndatacommons/tndata_backend,izzyalonso/tndata_backend
from django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using it's first argument to set a cache key. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the amove `get_stuff` method, obj.id will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first arg & use as the cache key obj_id = getattr(args[1], "id", str(args[1])) key = cache_key.format(obj_id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate Update for cached_method so it doesn't try to do anythin if the first argument doesn't have an ID attribute
from django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using the ID attribute of it's first argument to set a cache key. NOTE: If this first argument for the cached method doesn't have an ID attribute, nothing will happen. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the above `get_stuff` method, `obj.id` will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first objected passed into the function & use # its id attribute as part of the cache key cache_object = args[1] if not hasattr(cache_object, 'id'): return None # just bail if there's no ID. key = cache_key.format(cache_object.id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate
<commit_before>from django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using it's first argument to set a cache key. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the amove `get_stuff` method, obj.id will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first arg & use as the cache key obj_id = getattr(args[1], "id", str(args[1])) key = cache_key.format(obj_id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate <commit_msg>Update for cached_method so it doesn't try to do anythin if the first argument doesn't have an ID attribute<commit_after>
from django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using the ID attribute of it's first argument to set a cache key. NOTE: If this first argument for the cached method doesn't have an ID attribute, nothing will happen. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the above `get_stuff` method, `obj.id` will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first objected passed into the function & use # its id attribute as part of the cache key cache_object = args[1] if not hasattr(cache_object, 'id'): return None # just bail if there's no ID. key = cache_key.format(cache_object.id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate
from django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using it's first argument to set a cache key. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the amove `get_stuff` method, obj.id will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first arg & use as the cache key obj_id = getattr(args[1], "id", str(args[1])) key = cache_key.format(obj_id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate Update for cached_method so it doesn't try to do anythin if the first argument doesn't have an ID attributefrom django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using the ID attribute of it's first argument to set a cache key. NOTE: If this first argument for the cached method doesn't have an ID attribute, nothing will happen. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the above `get_stuff` method, `obj.id` will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first objected passed into the function & use # its id attribute as part of the cache key cache_object = args[1] if not hasattr(cache_object, 'id'): return None # just bail if there's no ID. key = cache_key.format(cache_object.id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate
<commit_before>from django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using it's first argument to set a cache key. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the amove `get_stuff` method, obj.id will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first arg & use as the cache key obj_id = getattr(args[1], "id", str(args[1])) key = cache_key.format(obj_id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate <commit_msg>Update for cached_method so it doesn't try to do anythin if the first argument doesn't have an ID attribute<commit_after>from django.conf import settings from django.core.cache import cache from functools import wraps def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT): """Cache a method, using the ID attribute of it's first argument to set a cache key. NOTE: If this first argument for the cached method doesn't have an ID attribute, nothing will happen. Params: * cache_key is a format string used to set a cache key, e.g. "{}-foo" Usage: class SomeThing: @cached_method("{}-key") def get_stuff(self, obj): # ... In the above `get_stuff` method, `obj.id` will be used to generate the cache key. NOTE: this was intended to be used on serializer methods. """ def decorate(func): @wraps(func) def wrapper(*args, **kwargs): if len(args) > 1: # extract the first objected passed into the function & use # its id attribute as part of the cache key cache_object = args[1] if not hasattr(cache_object, 'id'): return None # just bail if there's no ID. key = cache_key.format(cache_object.id) result = cache.get(key) if result is None: result = func(*args, **kwargs) cache.set(key, result, timeout=timeout) return result # Nothing to use as a cache key, just call the method. return func(*args, **kwargs) return wrapper return decorate
c1e3024527c372c09b77a97befbdf5a3d39a69ac
tests/test_status.py
tests/test_status.py
from ophyd.controls.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done']
from ophyd.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done']
Remove new instnace of 'controls' from status test.
FIX: Remove new instnace of 'controls' from status test.
Python
bsd-3-clause
dchabot/ophyd,dchabot/ophyd
from ophyd.controls.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done'] FIX: Remove new instnace of 'controls' from status test.
from ophyd.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done']
<commit_before>from ophyd.controls.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done'] <commit_msg>FIX: Remove new instnace of 'controls' from status test.<commit_after>
from ophyd.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done']
from ophyd.controls.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done'] FIX: Remove new instnace of 'controls' from status test.from ophyd.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done']
<commit_before>from ophyd.controls.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done'] <commit_msg>FIX: Remove new instnace of 'controls' from status test.<commit_after>from ophyd.ophydobj import StatusBase def _setup_st(): st = StatusBase() state = {} def cb(): state['done'] = True return st, state, cb def test_status_post(): st, state, cb = _setup_st() assert 'done' not in state st.finished_cb = cb assert 'done' not in state st._finished() assert 'done' in state assert state['done'] def test_status_pre(): st, state, cb = _setup_st() st._finished() assert 'done' not in state st.finished_cb = cb assert 'done' in state assert state['done']
98b601953428fb4c77eafb4e06a018c4bb2b4391
isort/files.py
isort/files.py
import os from pathlib import Path from typing import Iterable, Iterator, List, Set from warnings import warn from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover if not config.quiet: warn(f"Likely recursive symlink detected to {resolved_path}") dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path
import os from pathlib import Path from typing import Iterable, Iterator, List, Set from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path
Remove "recursive symlink detected" UserWarning
Remove "recursive symlink detected" UserWarning
Python
mit
PyCQA/isort,PyCQA/isort
import os from pathlib import Path from typing import Iterable, Iterator, List, Set from warnings import warn from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover if not config.quiet: warn(f"Likely recursive symlink detected to {resolved_path}") dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path Remove "recursive symlink detected" UserWarning
import os from pathlib import Path from typing import Iterable, Iterator, List, Set from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path
<commit_before>import os from pathlib import Path from typing import Iterable, Iterator, List, Set from warnings import warn from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover if not config.quiet: warn(f"Likely recursive symlink detected to {resolved_path}") dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path <commit_msg>Remove "recursive symlink detected" UserWarning<commit_after>
import os from pathlib import Path from typing import Iterable, Iterator, List, Set from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path
import os from pathlib import Path from typing import Iterable, Iterator, List, Set from warnings import warn from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover if not config.quiet: warn(f"Likely recursive symlink detected to {resolved_path}") dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path Remove "recursive symlink detected" UserWarningimport os from pathlib import Path from typing import Iterable, Iterator, List, Set from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path
<commit_before>import os from pathlib import Path from typing import Iterable, Iterator, List, Set from warnings import warn from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover if not config.quiet: warn(f"Likely recursive symlink detected to {resolved_path}") dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path <commit_msg>Remove "recursive symlink detected" UserWarning<commit_after>import os from pathlib import Path from typing import Iterable, Iterator, List, Set from isort.settings import Config def find( paths: Iterable[str], config: Config, skipped: List[str], broken: List[str] ) -> Iterator[str]: """Fines and provides an iterator for all Python source files defined in paths.""" visited_dirs: Set[Path] = set() for path in paths: if os.path.isdir(path): for dirpath, dirnames, filenames in os.walk( path, topdown=True, followlinks=config.follow_links ): base_path = Path(dirpath) for dirname in list(dirnames): full_path = base_path / dirname resolved_path = full_path.resolve() if config.is_skipped(full_path): skipped.append(dirname) dirnames.remove(dirname) else: if resolved_path in visited_dirs: # pragma: no cover dirnames.remove(dirname) visited_dirs.add(resolved_path) for filename in filenames: filepath = os.path.join(dirpath, filename) if config.is_supported_filetype(filepath): if config.is_skipped(Path(os.path.abspath(filepath))): skipped.append(filename) else: yield filepath elif not os.path.exists(path): broken.append(path) else: yield path
f80febf88c3f045493e75efc788d88058f021f0f
merge_sort.py
merge_sort.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [len(lyst)] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high): lyst[i] = buf[i]
#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high+1): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high+1): lyst[i] = buf[i]
Fix initial buf variable to act as an array
Fix initial buf variable to act as an array
Python
mit
nbeck90/data_structures_2
#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [len(lyst)] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high): lyst[i] = buf[i] Fix initial buf variable to act as an array
#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high+1): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high+1): lyst[i] = buf[i]
<commit_before>#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [len(lyst)] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high): lyst[i] = buf[i] <commit_msg>Fix initial buf variable to act as an array<commit_after>
#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high+1): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high+1): lyst[i] = buf[i]
#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [len(lyst)] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high): lyst[i] = buf[i] Fix initial buf variable to act as an array#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high+1): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high+1): lyst[i] = buf[i]
<commit_before>#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [len(lyst)] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high): lyst[i] = buf[i] <commit_msg>Fix initial buf variable to act as an array<commit_after>#!/usr/bin/env python # -*- coding: UTF-8 -*- def merge_sort(lyst): buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high+1): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high+1): lyst[i] = buf[i]
62634879192e51b9f938da301534b08cf49d2e85
methodMang.py
methodMang.py
#!python3 from methods import output, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] self.valid = self.valid + [(output.Output().methods, output.Output())] self.valid = self.valid + [(data.Data().methods, data.Data())] def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val
#!python3 from methods import io, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass def reg(it, c): it.valid = it.valid + [(c().methods, c())] class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] reg(self, io.IO) reg(self, data.Data) def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val
Rename Output + smaller Register
Rename Output + smaller Register
Python
mit
Icelys/Scotch-Language
#!python3 from methods import output, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] self.valid = self.valid + [(output.Output().methods, output.Output())] self.valid = self.valid + [(data.Data().methods, data.Data())] def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val Rename Output + smaller Register
#!python3 from methods import io, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass def reg(it, c): it.valid = it.valid + [(c().methods, c())] class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] reg(self, io.IO) reg(self, data.Data) def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val
<commit_before>#!python3 from methods import output, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] self.valid = self.valid + [(output.Output().methods, output.Output())] self.valid = self.valid + [(data.Data().methods, data.Data())] def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val <commit_msg>Rename Output + smaller Register<commit_after>
#!python3 from methods import io, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass def reg(it, c): it.valid = it.valid + [(c().methods, c())] class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] reg(self, io.IO) reg(self, data.Data) def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val
#!python3 from methods import output, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] self.valid = self.valid + [(output.Output().methods, output.Output())] self.valid = self.valid + [(data.Data().methods, data.Data())] def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val Rename Output + smaller Register#!python3 from methods import io, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass def reg(it, c): it.valid = it.valid + [(c().methods, c())] class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] reg(self, io.IO) reg(self, data.Data) def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val
<commit_before>#!python3 from methods import output, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] self.valid = self.valid + [(output.Output().methods, output.Output())] self.valid = self.valid + [(data.Data().methods, data.Data())] def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val <commit_msg>Rename Output + smaller Register<commit_after>#!python3 from methods import io, data import tokenz import interpreter intp = interpreter.Interpreter() class UndefinedFunctionError(Exception): pass def reg(it, c): it.valid = it.valid + [(c().methods, c())] class Call: def __init__(self, method, args): self.method = method self.a = args self.vals = [] for t in self.a: self.vals.append(str(t.val)) self.valid = [] reg(self, io.IO) reg(self, data.Data) def run(self): f = False for m in self.valid: if self.method in m[0]: args2pass = "" args2pass = " ".join(self.vals) args2pass = intp.eval(args2pass) return_val = m[1].funcs[m[0].index(self.method)](args2pass) f = True break if not f: return_val = None raise UndefinedFunctionError("Attempted to run function %s, but was undefined" % self.method) return return_val
b42dddaa45a8915a653f4b145f2a58eb6996f28a
home/openbox/lib/helpers.py
home/openbox/lib/helpers.py
import os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None
import os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None
Fix firefox invocation as browser
Fix firefox invocation as browser
Python
bsd-2-clause
p/pubfiles,p/pubfiles,p/pubfiles,p/pubfiles,p/pubfiles
import os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None Fix firefox invocation as browser
import os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None
<commit_before>import os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None <commit_msg>Fix firefox invocation as browser<commit_after>
import os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None
import os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None Fix firefox invocation as browserimport os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None
<commit_before>import os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None <commit_msg>Fix firefox invocation as browser<commit_after>import os.path, os def run_as_browser(fn): def wrapped(*args, **kwargs): rv = fn(*args, **kwargs) return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv return wrapped class Helpers: @property @run_as_browser def default_firefox_bin(self): candidates = [ '/usr/local/lib/firefox/firefox-bin', '/usr/local/lib/firefox3/firefox-bin', '/usr/bin/iceweasel', ] return self._pick(candidates, os.path.exists) @property @run_as_browser def default_firefox_wrapper(self): candidates = [ 'firefox', 'firefox3' ] return self._pick(candidates, self._wrapper_tester) default_firefox = default_firefox_wrapper @property def as_browser(self): return 'sudo -Hiu browser' @property def opera(self): return 'sudo -Hiu browser opera' @property def chrome(self): return 'sudo -Hiu browser chrome' def have_bin(self, basename): return self._wrapper_tester(basename) def _wrapper_tester(self, candidate): dirs = os.environ['PATH'].split(':') for dir in dirs: path = os.path.join(dir, candidate) if os.path.exists(path): return True return False def _pick(self, candidates, tester): for candidate in candidates: if tester(candidate): return candidate # consider raising here return None
2e729b437434e6d355602f9fd74bc9bd3b42f120
core/tests.py
core/tests.py
from django.test import TestCase # Create your tests here.
from django.test import TestCase from core.models import Profile, User class ProfileTestCase(TestCase): """This class defines the test suite for the Person model.""" def setUp(self): """Define the test variables.""" self.username = "some-test-user" self.email = "some@test.user" self.password = "passgoeshere123" self.user = User( username=self.username, email=self.email, password=self.password ) def test_model_can_create_a_profile(self): """Test the Person model can create a profile.""" old_count = Profile.objects.count() self.user.save() self.profile = self.profile = Profile(user=self.user) self.profile.save() new_count = Profile.objects.count() self.assertNotEqual(old_count, new_count)
Add test to model Profile
Add test to model Profile
Python
mit
desenho-sw-g5/service_control,desenho-sw-g5/service_control
from django.test import TestCase # Create your tests here. Add test to model Profile
from django.test import TestCase from core.models import Profile, User class ProfileTestCase(TestCase): """This class defines the test suite for the Person model.""" def setUp(self): """Define the test variables.""" self.username = "some-test-user" self.email = "some@test.user" self.password = "passgoeshere123" self.user = User( username=self.username, email=self.email, password=self.password ) def test_model_can_create_a_profile(self): """Test the Person model can create a profile.""" old_count = Profile.objects.count() self.user.save() self.profile = self.profile = Profile(user=self.user) self.profile.save() new_count = Profile.objects.count() self.assertNotEqual(old_count, new_count)
<commit_before>from django.test import TestCase # Create your tests here. <commit_msg>Add test to model Profile<commit_after>
from django.test import TestCase from core.models import Profile, User class ProfileTestCase(TestCase): """This class defines the test suite for the Person model.""" def setUp(self): """Define the test variables.""" self.username = "some-test-user" self.email = "some@test.user" self.password = "passgoeshere123" self.user = User( username=self.username, email=self.email, password=self.password ) def test_model_can_create_a_profile(self): """Test the Person model can create a profile.""" old_count = Profile.objects.count() self.user.save() self.profile = self.profile = Profile(user=self.user) self.profile.save() new_count = Profile.objects.count() self.assertNotEqual(old_count, new_count)
from django.test import TestCase # Create your tests here. Add test to model Profilefrom django.test import TestCase from core.models import Profile, User class ProfileTestCase(TestCase): """This class defines the test suite for the Person model.""" def setUp(self): """Define the test variables.""" self.username = "some-test-user" self.email = "some@test.user" self.password = "passgoeshere123" self.user = User( username=self.username, email=self.email, password=self.password ) def test_model_can_create_a_profile(self): """Test the Person model can create a profile.""" old_count = Profile.objects.count() self.user.save() self.profile = self.profile = Profile(user=self.user) self.profile.save() new_count = Profile.objects.count() self.assertNotEqual(old_count, new_count)
<commit_before>from django.test import TestCase # Create your tests here. <commit_msg>Add test to model Profile<commit_after>from django.test import TestCase from core.models import Profile, User class ProfileTestCase(TestCase): """This class defines the test suite for the Person model.""" def setUp(self): """Define the test variables.""" self.username = "some-test-user" self.email = "some@test.user" self.password = "passgoeshere123" self.user = User( username=self.username, email=self.email, password=self.password ) def test_model_can_create_a_profile(self): """Test the Person model can create a profile.""" old_count = Profile.objects.count() self.user.save() self.profile = self.profile = Profile(user=self.user) self.profile.save() new_count = Profile.objects.count() self.assertNotEqual(old_count, new_count)
7dd0c64b4503ab32cf79864f4c23016518b1cdbd
electionleaflets/apps/api/tests/test_create_leaflet.py
electionleaflets/apps/api/tests/test_create_leaflet.py
import os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('leaflet-list') leaflet_image_url = reverse('leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] # Upload some images for name, path in IMAGES: data = { 'image': open(path), 'leaflet': leaflet_id } response = self.client.post(leaflet_image_url, data, format='multipart') response = self.client.get(leaflet_url+"1/", format='json') self.assertEqual(len(response.data['images']), 6)
import os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('api:leaflet-list') leaflet_image_url = reverse('api:leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] self.assertEqual(leaflet_id, 1) # import ipdb # ipdb.set_trace() # # Upload some images # for name, path in IMAGES: # data = { # 'image': open(path), # 'leaflet_id': leaflet_id # } # # response = self.client.post(leaflet_image_url, # data, format='multipart') # response = self.client.get(leaflet_url+"1/", format='json') # self.assertEqual(len(response.data['images']), 6)
Remove some API tests for now
Remove some API tests for now
Python
mit
JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets,JustinWingChungHui/electionleaflets,JustinWingChungHui/electionleaflets
import os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('leaflet-list') leaflet_image_url = reverse('leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] # Upload some images for name, path in IMAGES: data = { 'image': open(path), 'leaflet': leaflet_id } response = self.client.post(leaflet_image_url, data, format='multipart') response = self.client.get(leaflet_url+"1/", format='json') self.assertEqual(len(response.data['images']), 6) Remove some API tests for now
import os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('api:leaflet-list') leaflet_image_url = reverse('api:leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] self.assertEqual(leaflet_id, 1) # import ipdb # ipdb.set_trace() # # Upload some images # for name, path in IMAGES: # data = { # 'image': open(path), # 'leaflet_id': leaflet_id # } # # response = self.client.post(leaflet_image_url, # data, format='multipart') # response = self.client.get(leaflet_url+"1/", format='json') # self.assertEqual(len(response.data['images']), 6)
<commit_before>import os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('leaflet-list') leaflet_image_url = reverse('leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] # Upload some images for name, path in IMAGES: data = { 'image': open(path), 'leaflet': leaflet_id } response = self.client.post(leaflet_image_url, data, format='multipart') response = self.client.get(leaflet_url+"1/", format='json') self.assertEqual(len(response.data['images']), 6) <commit_msg>Remove some API tests for now<commit_after>
import os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('api:leaflet-list') leaflet_image_url = reverse('api:leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] self.assertEqual(leaflet_id, 1) # import ipdb # ipdb.set_trace() # # Upload some images # for name, path in IMAGES: # data = { # 'image': open(path), # 'leaflet_id': leaflet_id # } # # response = self.client.post(leaflet_image_url, # data, format='multipart') # response = self.client.get(leaflet_url+"1/", format='json') # self.assertEqual(len(response.data['images']), 6)
import os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('leaflet-list') leaflet_image_url = reverse('leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] # Upload some images for name, path in IMAGES: data = { 'image': open(path), 'leaflet': leaflet_id } response = self.client.post(leaflet_image_url, data, format='multipart') response = self.client.get(leaflet_url+"1/", format='json') self.assertEqual(len(response.data['images']), 6) Remove some API tests for nowimport os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('api:leaflet-list') leaflet_image_url = reverse('api:leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] self.assertEqual(leaflet_id, 1) # import ipdb # ipdb.set_trace() # # Upload some images # for name, path in IMAGES: # data = { # 'image': open(path), # 'leaflet_id': leaflet_id # } # # response = self.client.post(leaflet_image_url, # data, format='multipart') # response = self.client.get(leaflet_url+"1/", format='json') # self.assertEqual(len(response.data['images']), 6)
<commit_before>import os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('leaflet-list') leaflet_image_url = reverse('leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] # Upload some images for name, path in IMAGES: data = { 'image': open(path), 'leaflet': leaflet_id } response = self.client.post(leaflet_image_url, data, format='multipart') response = self.client.get(leaflet_url+"1/", format='json') self.assertEqual(len(response.data['images']), 6) <commit_msg>Remove some API tests for now<commit_after>import os import json from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import APITestCase TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',] BASE_PATH = os.path.join( os.path.dirname(__file__), 'test_images' ) IMAGES = [(name, os.path.join(BASE_PATH, name)) for name in TEST_IMAGES] class CreateLeafletTests(APITestCase): def test_create_leaflet(self): leaflet_url = reverse('api:leaflet-list') leaflet_image_url = reverse('api:leafletimage-list') response = self.client.post(leaflet_url, {}, format='json') self.assertEqual(response.data['status'], 'draft') leaflet_id = response.data['pk'] self.assertEqual(leaflet_id, 1) # import ipdb # ipdb.set_trace() # # Upload some images # for name, path in IMAGES: # data = { # 'image': open(path), # 'leaflet_id': leaflet_id # } # # response = self.client.post(leaflet_image_url, # data, format='multipart') # response = self.client.get(leaflet_url+"1/", format='json') # self.assertEqual(len(response.data['images']), 6)
327c00fe5fe9211ac5ba3b33e807ec938ecc8311
configstore/tests/test_docker_secret.py
configstore/tests/test_docker_secret.py
from unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) def test_secrets_path(self): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val)
from unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=False) def test_secrets_path(self, mocked_exists): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val)
Make sure exists always resturns None in the non-existant test case
Make sure exists always resturns None in the non-existant test case
Python
mit
caravancoop/configstore
from unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) def test_secrets_path(self): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val) Make sure exists always resturns None in the non-existant test case
from unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=False) def test_secrets_path(self, mocked_exists): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val)
<commit_before>from unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) def test_secrets_path(self): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val) <commit_msg>Make sure exists always resturns None in the non-existant test case<commit_after>
from unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=False) def test_secrets_path(self, mocked_exists): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val)
from unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) def test_secrets_path(self): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val) Make sure exists always resturns None in the non-existant test casefrom unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=False) def test_secrets_path(self, mocked_exists): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val)
<commit_before>from unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) def test_secrets_path(self): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val) <commit_msg>Make sure exists always resturns None in the non-existant test case<commit_after>from unittest import TestCase try: from unittest import mock except ImportError: import mock from configstore.backends.docker_secret import DockerSecretBackend from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH class TestDockerSecretBackend(TestCase): @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=True) def test_get_secret(self, mocked_exists): mocked_open = mock.mock_open(read_data=DEFAULT_VALUE) with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend() val = d.get_config(DEFAULT_KEY) self.assertEqual(DEFAULT_VALUE, val) @mock.patch('configstore.backends.docker_secret.os.path.exists', return_value=False) def test_secrets_path(self, mocked_exists): mocked_open = mock.MagicMock() with mock.patch('configstore.backends.docker_secret.open', mocked_open, create=True): d = DockerSecretBackend(CUSTOM_PATH) val = d.get_config(DEFAULT_KEY) self.assertIsNone(val)