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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bf89baf003bace5b48bcf8421a0548c7e1fd73a0 | viper/interpreter/value.py | viper/interpreter/value.py | from .environment import Environment
from viper.parser.ast.nodes import Expr
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, name: str, expr: Expr, env: Environment):
self.name = name
self.expr = expr
self.env = env
def __repr__(self) -> str:
return f"CloVal({self.name}, {self.expr}, {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
| from .environment import Environment
from viper.parser.ast.nodes import AST, Parameter
from typing import List
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, params: List[Parameter], code: AST, env: Environment):
self.params = params
self.code = code
self.env = env
def __repr__(self) -> str:
return f"CloVal(({', '.join(map(lambda p: p.internal, self.params))}), {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
| Update CloVal to allow for specifying multiple parameters | Update CloVal to allow for specifying multiple parameters
| Python | apache-2.0 | pdarragh/Viper | from .environment import Environment
from viper.parser.ast.nodes import Expr
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, name: str, expr: Expr, env: Environment):
self.name = name
self.expr = expr
self.env = env
def __repr__(self) -> str:
return f"CloVal({self.name}, {self.expr}, {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
Update CloVal to allow for specifying multiple parameters | from .environment import Environment
from viper.parser.ast.nodes import AST, Parameter
from typing import List
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, params: List[Parameter], code: AST, env: Environment):
self.params = params
self.code = code
self.env = env
def __repr__(self) -> str:
return f"CloVal(({', '.join(map(lambda p: p.internal, self.params))}), {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
| <commit_before>from .environment import Environment
from viper.parser.ast.nodes import Expr
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, name: str, expr: Expr, env: Environment):
self.name = name
self.expr = expr
self.env = env
def __repr__(self) -> str:
return f"CloVal({self.name}, {self.expr}, {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
<commit_msg>Update CloVal to allow for specifying multiple parameters<commit_after> | from .environment import Environment
from viper.parser.ast.nodes import AST, Parameter
from typing import List
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, params: List[Parameter], code: AST, env: Environment):
self.params = params
self.code = code
self.env = env
def __repr__(self) -> str:
return f"CloVal(({', '.join(map(lambda p: p.internal, self.params))}), {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
| from .environment import Environment
from viper.parser.ast.nodes import Expr
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, name: str, expr: Expr, env: Environment):
self.name = name
self.expr = expr
self.env = env
def __repr__(self) -> str:
return f"CloVal({self.name}, {self.expr}, {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
Update CloVal to allow for specifying multiple parametersfrom .environment import Environment
from viper.parser.ast.nodes import AST, Parameter
from typing import List
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, params: List[Parameter], code: AST, env: Environment):
self.params = params
self.code = code
self.env = env
def __repr__(self) -> str:
return f"CloVal(({', '.join(map(lambda p: p.internal, self.params))}), {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
| <commit_before>from .environment import Environment
from viper.parser.ast.nodes import Expr
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, name: str, expr: Expr, env: Environment):
self.name = name
self.expr = expr
self.env = env
def __repr__(self) -> str:
return f"CloVal({self.name}, {self.expr}, {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
<commit_msg>Update CloVal to allow for specifying multiple parameters<commit_after>from .environment import Environment
from viper.parser.ast.nodes import AST, Parameter
from typing import List
class Value:
pass
class TupleVal(Value):
def __init__(self, *vals: Value):
self.vals = list(vals)
def __repr__(self) -> str:
return f"TupleVal({', '.join(map(str, self.vals))})"
class NumVal(Value):
def __init__(self, val: str):
self.val = val
def __repr__(self) -> str:
return f"NumVal({self.val})"
class CloVal(Value):
def __init__(self, params: List[Parameter], code: AST, env: Environment):
self.params = params
self.code = code
self.env = env
def __repr__(self) -> str:
return f"CloVal(({', '.join(map(lambda p: p.internal, self.params))}), {self.env})"
class BoolVal(Value):
def __repr__(self) -> str:
return "BoolVal"
class TrueVal(BoolVal):
def __repr__(self) -> str:
return "TrueVal"
class FalseVal(BoolVal):
def __repr__(self) -> str:
return "FalseVal"
class UnitVal(Value):
def __repr__(self) -> str:
return "UnitVal"
class BottomVal(Value):
def __repr__(self) -> str:
return "BottomVal"
class EllipsisVal(Value):
def __repr__(self) -> str:
return "EllipsisVal"
|
312bb90415218398ddbe9250cfe7dbc4bb013e14 | opal/core/lookuplists.py | opal/core/lookuplists.py | """
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
# class LookupList(models.Model):
# class Meta:
# abstract = True
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
# def lookup_list(name, module=__name__):
# """
# Given the name of a lookup list, return the tuple of class_name, bases, attrs
# for the user to define the class
# """
# prefix = 'Lookup List: '
# class_name = name.capitalize() # TODO handle camelcase properly
# bases = (LookupList,)
# attrs = {
# 'name': models.CharField(max_length=255, unique=True),
# 'synonyms': generic.GenericRelation('opal.Synonym'),
# 'Meta': type('Meta', (object,), {'ordering': ['name'],
# 'verbose_name': prefix+name}),
# '__unicode__': lambda self: self.name,
# '__module__': module,
# }
# return class_name, bases, attrs
| """
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
| Delete commented out old code. | Delete commented out old code.
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal | """
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
# class LookupList(models.Model):
# class Meta:
# abstract = True
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
# def lookup_list(name, module=__name__):
# """
# Given the name of a lookup list, return the tuple of class_name, bases, attrs
# for the user to define the class
# """
# prefix = 'Lookup List: '
# class_name = name.capitalize() # TODO handle camelcase properly
# bases = (LookupList,)
# attrs = {
# 'name': models.CharField(max_length=255, unique=True),
# 'synonyms': generic.GenericRelation('opal.Synonym'),
# 'Meta': type('Meta', (object,), {'ordering': ['name'],
# 'verbose_name': prefix+name}),
# '__unicode__': lambda self: self.name,
# '__module__': module,
# }
# return class_name, bases, attrs
Delete commented out old code. | """
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
| <commit_before>"""
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
# class LookupList(models.Model):
# class Meta:
# abstract = True
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
# def lookup_list(name, module=__name__):
# """
# Given the name of a lookup list, return the tuple of class_name, bases, attrs
# for the user to define the class
# """
# prefix = 'Lookup List: '
# class_name = name.capitalize() # TODO handle camelcase properly
# bases = (LookupList,)
# attrs = {
# 'name': models.CharField(max_length=255, unique=True),
# 'synonyms': generic.GenericRelation('opal.Synonym'),
# 'Meta': type('Meta', (object,), {'ordering': ['name'],
# 'verbose_name': prefix+name}),
# '__unicode__': lambda self: self.name,
# '__module__': module,
# }
# return class_name, bases, attrs
<commit_msg>Delete commented out old code.<commit_after> | """
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
| """
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
# class LookupList(models.Model):
# class Meta:
# abstract = True
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
# def lookup_list(name, module=__name__):
# """
# Given the name of a lookup list, return the tuple of class_name, bases, attrs
# for the user to define the class
# """
# prefix = 'Lookup List: '
# class_name = name.capitalize() # TODO handle camelcase properly
# bases = (LookupList,)
# attrs = {
# 'name': models.CharField(max_length=255, unique=True),
# 'synonyms': generic.GenericRelation('opal.Synonym'),
# 'Meta': type('Meta', (object,), {'ordering': ['name'],
# 'verbose_name': prefix+name}),
# '__unicode__': lambda self: self.name,
# '__module__': module,
# }
# return class_name, bases, attrs
Delete commented out old code."""
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
| <commit_before>"""
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
# class LookupList(models.Model):
# class Meta:
# abstract = True
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
# def lookup_list(name, module=__name__):
# """
# Given the name of a lookup list, return the tuple of class_name, bases, attrs
# for the user to define the class
# """
# prefix = 'Lookup List: '
# class_name = name.capitalize() # TODO handle camelcase properly
# bases = (LookupList,)
# attrs = {
# 'name': models.CharField(max_length=255, unique=True),
# 'synonyms': generic.GenericRelation('opal.Synonym'),
# 'Meta': type('Meta', (object,), {'ordering': ['name'],
# 'verbose_name': prefix+name}),
# '__unicode__': lambda self: self.name,
# '__module__': module,
# }
# return class_name, bases, attrs
<commit_msg>Delete commented out old code.<commit_after>"""
OPAL Lookuplists
"""
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
|
35f286ac175d5480d3dbb7261205f12dd97144bb | checkmail.py | checkmail.py | #!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import re
import email
import argparse
import sys
import tempfile
mail_split_re = re.compile(r'\s(?=From -)')
def print_message(message, signature=None):
parsed = email.message_from_string(message)
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message)
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="Thunderbird mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
for msg in mail_split_re.split(args.mailfile.read()):
scan_mail(msg)
| #!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import email
import argparse
import sys
import tempfile
import mailbox
def print_message(parsed, signature=None):
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message.as_string())
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="mbox mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
mbox = mailbox.mbox(args.mailfile.name)
for msg in mbox:
scan_mail(msg)
| Use the python MBox class rather than parsing the mailbox manually | Use the python MBox class rather than parsing the mailbox manually
| Python | mit | DanSearle/CheckMail | #!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import re
import email
import argparse
import sys
import tempfile
mail_split_re = re.compile(r'\s(?=From -)')
def print_message(message, signature=None):
parsed = email.message_from_string(message)
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message)
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="Thunderbird mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
for msg in mail_split_re.split(args.mailfile.read()):
scan_mail(msg)
Use the python MBox class rather than parsing the mailbox manually | #!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import email
import argparse
import sys
import tempfile
import mailbox
def print_message(parsed, signature=None):
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message.as_string())
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="mbox mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
mbox = mailbox.mbox(args.mailfile.name)
for msg in mbox:
scan_mail(msg)
| <commit_before>#!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import re
import email
import argparse
import sys
import tempfile
mail_split_re = re.compile(r'\s(?=From -)')
def print_message(message, signature=None):
parsed = email.message_from_string(message)
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message)
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="Thunderbird mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
for msg in mail_split_re.split(args.mailfile.read()):
scan_mail(msg)
<commit_msg>Use the python MBox class rather than parsing the mailbox manually<commit_after> | #!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import email
import argparse
import sys
import tempfile
import mailbox
def print_message(parsed, signature=None):
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message.as_string())
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="mbox mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
mbox = mailbox.mbox(args.mailfile.name)
for msg in mbox:
scan_mail(msg)
| #!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import re
import email
import argparse
import sys
import tempfile
mail_split_re = re.compile(r'\s(?=From -)')
def print_message(message, signature=None):
parsed = email.message_from_string(message)
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message)
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="Thunderbird mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
for msg in mail_split_re.split(args.mailfile.read()):
scan_mail(msg)
Use the python MBox class rather than parsing the mailbox manually#!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import email
import argparse
import sys
import tempfile
import mailbox
def print_message(parsed, signature=None):
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message.as_string())
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="mbox mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
mbox = mailbox.mbox(args.mailfile.name)
for msg in mbox:
scan_mail(msg)
| <commit_before>#!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import re
import email
import argparse
import sys
import tempfile
mail_split_re = re.compile(r'\s(?=From -)')
def print_message(message, signature=None):
parsed = email.message_from_string(message)
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message)
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="Thunderbird mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
for msg in mail_split_re.split(args.mailfile.read()):
scan_mail(msg)
<commit_msg>Use the python MBox class rather than parsing the mailbox manually<commit_after>#!/usr/bin/env python
"""
Simple Python module to parse a Thunderbird mail file and
scan each email message with ClamAV in order to detect
suspect messages.
"""
import pyclamav
import os
import email
import argparse
import sys
import tempfile
import mailbox
def print_message(parsed, signature=None):
print "From: {0}, Subject: {1}, Signature: {2}".format(parsed["From"],
parsed["Subject"],
signature)
def scan_mail(message):
temp_message = tempfile.NamedTemporaryFile(delete=False)
with temp_message as f:
f.write(message.as_string())
try:
result = pyclamav.scanfile(temp_message.name)
if not result[0]:
return
print_message(message, result[1])
finally:
os.remove(temp_message.name)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('mailfile', nargs='?', type=argparse.FileType('r'),
default=sys.stdin,
help="mbox mail file to parse, if not provided input is taken from STDIN")
args = parser.parse_args()
mbox = mailbox.mbox(args.mailfile.name)
for msg in mbox:
scan_mail(msg)
|
f54123b1727f0af424d31398e7397300975b0272 | grow/submodules/__init__.py | grow/submodules/__init__.py | import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib2')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
| import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
| Use python2 pyyaml instead of python3. | Use python2 pyyaml instead of python3.
| Python | mit | denmojo/pygrow,grow/grow,grow/grow,denmojo/pygrow,grow/pygrow,grow/grow,vitorio/pygrow,codedcolors/pygrow,grow/pygrow,vitorio/pygrow,grow/grow,denmojo/pygrow,vitorio/pygrow,denmojo/pygrow,grow/pygrow,codedcolors/pygrow,codedcolors/pygrow | import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib2')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
Use python2 pyyaml instead of python3. | import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
| <commit_before>import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib2')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
<commit_msg>Use python2 pyyaml instead of python3.<commit_after> | import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
| import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib2')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
Use python2 pyyaml instead of python3.import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
| <commit_before>import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib2')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
<commit_msg>Use python2 pyyaml instead of python3.<commit_after>import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
|
842cfc631949831053f4310f586e7b2a83ff7cde | notifications_utils/timezones.py | notifications_utils/timezones.py | from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string or a naive datetime
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
| from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string, naive UTC datetime or an aware UTC datetime
Returns an aware London datetime, essentially the time you'd see on your clock
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
"""
Takes a naive UTC datetime and returns a naive London datetime
"""
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
"""
Takes a naive London datetime and returns a naive UTC datetime
"""
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
| Add descriptions to timezone functions | Add descriptions to timezone functions
These are quite complex things and benefit from having better descriptions.
Note, we weren't quite happy with the names of the functions.
`aware_gmt_datetime` should really be `aware_london_datetime` and
the other two functions could have more verbose names (mentioning
that they convert from naive to naive) but we decided not to change
these as will involve lots of changes around the codebase.
| Python | mit | alphagov/notifications-utils | from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string or a naive datetime
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
Add descriptions to timezone functions
These are quite complex things and benefit from having better descriptions.
Note, we weren't quite happy with the names of the functions.
`aware_gmt_datetime` should really be `aware_london_datetime` and
the other two functions could have more verbose names (mentioning
that they convert from naive to naive) but we decided not to change
these as will involve lots of changes around the codebase. | from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string, naive UTC datetime or an aware UTC datetime
Returns an aware London datetime, essentially the time you'd see on your clock
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
"""
Takes a naive UTC datetime and returns a naive London datetime
"""
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
"""
Takes a naive London datetime and returns a naive UTC datetime
"""
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
| <commit_before>from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string or a naive datetime
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
<commit_msg>Add descriptions to timezone functions
These are quite complex things and benefit from having better descriptions.
Note, we weren't quite happy with the names of the functions.
`aware_gmt_datetime` should really be `aware_london_datetime` and
the other two functions could have more verbose names (mentioning
that they convert from naive to naive) but we decided not to change
these as will involve lots of changes around the codebase.<commit_after> | from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string, naive UTC datetime or an aware UTC datetime
Returns an aware London datetime, essentially the time you'd see on your clock
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
"""
Takes a naive UTC datetime and returns a naive London datetime
"""
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
"""
Takes a naive London datetime and returns a naive UTC datetime
"""
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
| from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string or a naive datetime
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
Add descriptions to timezone functions
These are quite complex things and benefit from having better descriptions.
Note, we weren't quite happy with the names of the functions.
`aware_gmt_datetime` should really be `aware_london_datetime` and
the other two functions could have more verbose names (mentioning
that they convert from naive to naive) but we decided not to change
these as will involve lots of changes around the codebase.from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string, naive UTC datetime or an aware UTC datetime
Returns an aware London datetime, essentially the time you'd see on your clock
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
"""
Takes a naive UTC datetime and returns a naive London datetime
"""
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
"""
Takes a naive London datetime and returns a naive UTC datetime
"""
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
| <commit_before>from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string or a naive datetime
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
<commit_msg>Add descriptions to timezone functions
These are quite complex things and benefit from having better descriptions.
Note, we weren't quite happy with the names of the functions.
`aware_gmt_datetime` should really be `aware_london_datetime` and
the other two functions could have more verbose names (mentioning
that they convert from naive to naive) but we decided not to change
these as will involve lots of changes around the codebase.<commit_after>from datetime import datetime
import pytz
from dateutil import parser
local_timezone = pytz.timezone("Europe/London")
def utc_string_to_aware_gmt_datetime(date):
"""
Date can either be a string, naive UTC datetime or an aware UTC datetime
Returns an aware London datetime, essentially the time you'd see on your clock
"""
if not isinstance(date, datetime):
date = parser.parse(date)
forced_utc = date.replace(tzinfo=pytz.utc)
return forced_utc.astimezone(local_timezone)
def convert_utc_to_bst(utc_dt):
"""
Takes a naive UTC datetime and returns a naive London datetime
"""
return pytz.utc.localize(utc_dt).astimezone(local_timezone).replace(tzinfo=None)
def convert_bst_to_utc(date):
"""
Takes a naive London datetime and returns a naive UTC datetime
"""
return local_timezone.localize(date).astimezone(pytz.UTC).replace(tzinfo=None)
|
38bf0cba402d3c747584b8aae109c3735d23f6fa | config/settings/__init__.py | config/settings/__init__.py | import os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
| import os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
| Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL | Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL
| Python | apache-2.0 | aipescience/django-daiquiri-app,aipescience/django-daiquiri-app | import os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL | import os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
| <commit_before>import os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
<commit_msg>Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL<commit_after> | import os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
| import os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URLimport os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
| <commit_before>import os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
<commit_msg>Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL<commit_after>import os
# include settimgs from daiquiri
from daiquiri.core.settings import *
# include settings from base.py
from .base import *
# include settings from local.py
from .local import *
# include 3rd party apps after the daiquiri apps from base.py
INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INSTALLED_APPS
# prepend the local.BASE_URL to the different URL settings
try:
LOGIN_URL = BASE_URL + LOGIN_URL
LOGIN_REDIRECT_URL = BASE_URL + LOGIN_REDIRECT_URL
LOGOUT_URL = BASE_URL + LOGOUT_URL
ACCOUNT_LOGOUT_REDIRECT_URL = BASE_URL + ACCOUNT_LOGOUT_REDIRECT_URL
MEDIA_URL = BASE_URL + MEDIA_URL
STATIC_URL = BASE_URL + STATIC_URL
CSRF_COOKIE_PATH = BASE_URL + '/'
LANGUAGE_COOKIE_PATH = BASE_URL + '/'
SESSION_COOKIE_PATH = BASE_URL + '/'
except NameError:
pass
# prepend the LOGGING_DIR to the filenames in LOGGING
for handler in LOGGING['handlers'].values():
if 'filename' in handler:
handler['filename'] = os.path.join(LOGGING_DIR, handler['filename'])
|
6992437bd82fa6524b5c7ed98370e2e7c3ad0ee3 | dj_experiment/management/commands/infocatalog.py | dj_experiment/management/commands/infocatalog.py | from dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.title for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
| from dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.name for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
| Fix query by unique name | Fix query by unique name
| Python | mit | francbartoli/dj-experiment,francbartoli/dj-experiment | from dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.title for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
Fix query by unique name | from dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.name for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
| <commit_before>from dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.title for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
<commit_msg>Fix query by unique name<commit_after> | from dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.name for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
| from dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.title for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
Fix query by unique namefrom dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.name for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
| <commit_before>from dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.title for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
<commit_msg>Fix query by unique name<commit_after>from dj_experiment.models import Catalog
from django.core.management.base import BaseCommand, CommandError
from humanfriendly.tables import format_pretty_table
class Command(BaseCommand):
"""Retrieve information about experiments from the catalog."""
help = 'Retrieve information about experiments from the catalog'
def add_arguments(self, parser):
"""Add arguments for handling the command."""
pass
def handle(self, *args, **options):
"""Query all the entries from the catalog model."""
if args:
raise CommandError("infocatalog takes no arguments")
column_names = ['Catalog Name']
# [self.stdout.write(cat, ending='') for cat in Catalog.objects.all()]
catalog = [cat.name for cat in Catalog.objects.all()]
self.stdout.write(format_pretty_table(
[catalog, ], column_names))
|
41f254bd53ca6998725c959d9abe71975cffc92f | froide/accesstoken/admin.py | froide/accesstoken/admin.py | from django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
admin.site.register(AccessToken, AccessTokenAdmin)
| from django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
list_filter = ('purpose',)
search_fields = ('user__email',)
admin.site.register(AccessToken, AccessTokenAdmin)
| Add search, filter to access tokens | Add search, filter to access tokens | Python | mit | stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide | from django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
admin.site.register(AccessToken, AccessTokenAdmin)
Add search, filter to access tokens | from django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
list_filter = ('purpose',)
search_fields = ('user__email',)
admin.site.register(AccessToken, AccessTokenAdmin)
| <commit_before>from django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
admin.site.register(AccessToken, AccessTokenAdmin)
<commit_msg>Add search, filter to access tokens<commit_after> | from django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
list_filter = ('purpose',)
search_fields = ('user__email',)
admin.site.register(AccessToken, AccessTokenAdmin)
| from django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
admin.site.register(AccessToken, AccessTokenAdmin)
Add search, filter to access tokensfrom django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
list_filter = ('purpose',)
search_fields = ('user__email',)
admin.site.register(AccessToken, AccessTokenAdmin)
| <commit_before>from django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
admin.site.register(AccessToken, AccessTokenAdmin)
<commit_msg>Add search, filter to access tokens<commit_after>from django.contrib import admin
from .models import AccessToken
class AccessTokenAdmin(admin.ModelAdmin):
raw_id_fields = ('user',)
list_filter = ('purpose',)
search_fields = ('user__email',)
admin.site.register(AccessToken, AccessTokenAdmin)
|
38c2f86e8784530efc0234851d3bb9ebbfef58f5 | froide/account/api_views.py | froide/account/api_views.py | from rest_framework import serializers, views, permissions, response
from oauth2_provider.contrib.rest_framework import TokenHasScope
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id',)
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated, TokenHasScope]
required_scopes = ['read:user']
def get(self, request, format=None):
token = request.auth
user = request.user
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
return response.Response(serializer.data)
| from rest_framework import serializers, views, permissions, response
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'private')
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class UserFullSerializer(UserSerializer):
class Meta:
model = User
fields = UserEmailSerializer.Meta.fields + ('address',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated]
def has_permission(self, request, view):
token = request.auth
if token and not token.is_valid(['read:user']):
return False
return super(ProfileView, self).has_permission(
request, view
)
def get(self, request, format=None):
token = request.auth
user = request.user
if token:
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
else:
# if token is None, user is currently logged in user
serializer = UserFullSerializer(user)
return response.Response(serializer.data)
| Make logged in user endpoint available w/o token | Make logged in user endpoint available w/o token | Python | mit | stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide | from rest_framework import serializers, views, permissions, response
from oauth2_provider.contrib.rest_framework import TokenHasScope
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id',)
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated, TokenHasScope]
required_scopes = ['read:user']
def get(self, request, format=None):
token = request.auth
user = request.user
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
return response.Response(serializer.data)
Make logged in user endpoint available w/o token | from rest_framework import serializers, views, permissions, response
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'private')
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class UserFullSerializer(UserSerializer):
class Meta:
model = User
fields = UserEmailSerializer.Meta.fields + ('address',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated]
def has_permission(self, request, view):
token = request.auth
if token and not token.is_valid(['read:user']):
return False
return super(ProfileView, self).has_permission(
request, view
)
def get(self, request, format=None):
token = request.auth
user = request.user
if token:
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
else:
# if token is None, user is currently logged in user
serializer = UserFullSerializer(user)
return response.Response(serializer.data)
| <commit_before>from rest_framework import serializers, views, permissions, response
from oauth2_provider.contrib.rest_framework import TokenHasScope
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id',)
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated, TokenHasScope]
required_scopes = ['read:user']
def get(self, request, format=None):
token = request.auth
user = request.user
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
return response.Response(serializer.data)
<commit_msg>Make logged in user endpoint available w/o token<commit_after> | from rest_framework import serializers, views, permissions, response
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'private')
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class UserFullSerializer(UserSerializer):
class Meta:
model = User
fields = UserEmailSerializer.Meta.fields + ('address',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated]
def has_permission(self, request, view):
token = request.auth
if token and not token.is_valid(['read:user']):
return False
return super(ProfileView, self).has_permission(
request, view
)
def get(self, request, format=None):
token = request.auth
user = request.user
if token:
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
else:
# if token is None, user is currently logged in user
serializer = UserFullSerializer(user)
return response.Response(serializer.data)
| from rest_framework import serializers, views, permissions, response
from oauth2_provider.contrib.rest_framework import TokenHasScope
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id',)
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated, TokenHasScope]
required_scopes = ['read:user']
def get(self, request, format=None):
token = request.auth
user = request.user
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
return response.Response(serializer.data)
Make logged in user endpoint available w/o tokenfrom rest_framework import serializers, views, permissions, response
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'private')
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class UserFullSerializer(UserSerializer):
class Meta:
model = User
fields = UserEmailSerializer.Meta.fields + ('address',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated]
def has_permission(self, request, view):
token = request.auth
if token and not token.is_valid(['read:user']):
return False
return super(ProfileView, self).has_permission(
request, view
)
def get(self, request, format=None):
token = request.auth
user = request.user
if token:
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
else:
# if token is None, user is currently logged in user
serializer = UserFullSerializer(user)
return response.Response(serializer.data)
| <commit_before>from rest_framework import serializers, views, permissions, response
from oauth2_provider.contrib.rest_framework import TokenHasScope
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id',)
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated, TokenHasScope]
required_scopes = ['read:user']
def get(self, request, format=None):
token = request.auth
user = request.user
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
return response.Response(serializer.data)
<commit_msg>Make logged in user endpoint available w/o token<commit_after>from rest_framework import serializers, views, permissions, response
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'private')
def to_representation(self, obj):
default = super(UserSerializer, self).to_representation(obj)
if obj.is_superuser:
default['is_superuser'] = True
if obj.is_staff:
default['is_staff'] = True
return default
class UserDetailSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = UserSerializer.Meta.fields + ('first_name', 'last_name',)
class UserEmailSerializer(UserSerializer):
class Meta:
model = User
fields = UserDetailSerializer.Meta.fields + ('email',)
class UserFullSerializer(UserSerializer):
class Meta:
model = User
fields = UserEmailSerializer.Meta.fields + ('address',)
class ProfileView(views.APIView):
permission_classes = [permissions.IsAuthenticated]
def has_permission(self, request, view):
token = request.auth
if token and not token.is_valid(['read:user']):
return False
return super(ProfileView, self).has_permission(
request, view
)
def get(self, request, format=None):
token = request.auth
user = request.user
if token:
if token.is_valid(['read:email']):
serializer = UserEmailSerializer(user)
elif token.is_valid(['read:profile']):
serializer = UserDetailSerializer(user)
else:
serializer = UserSerializer(user)
else:
# if token is None, user is currently logged in user
serializer = UserFullSerializer(user)
return response.Response(serializer.data)
|
97db526a655f9723342df3c0c27e7325002c50aa | ovp_users/serializers.py | ovp_users/serializers.py | from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
pass
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
| from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
| Add password as a write_only field on CreateUserSerializer | Add password as a write_only field on CreateUserSerializer
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users | from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
pass
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
Add password as a write_only field on CreateUserSerializer | from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
| <commit_before>from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
pass
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
<commit_msg>Add password as a write_only field on CreateUserSerializer<commit_after> | from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
| from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
pass
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
Add password as a write_only field on CreateUserSerializerfrom django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
| <commit_before>from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
pass
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
<commit_msg>Add password as a write_only field on CreateUserSerializer<commit_after>from django.core.exceptions import ValidationError
from django.contrib.auth.password_validation import validate_password
from ovp_users import models
from rest_framework import serializers
class UserCreateSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['id', 'name', 'email', 'password']
extra_kwargs = {'password': {'write_only': True}}
def validate(self, data):
password = data.get('password')
errors = dict()
try:
validate_password(password=password)
except ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(UserCreateSerializer, self).validate(data)
class UserSearchSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['name']
class RecoveryTokenSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
class Meta:
fields = ['email']
class RecoverPasswordSerializer(serializers.Serializer):
email = serializers.CharField(required=True)
token = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
fields = ['email', 'token', 'new_password']
|
a0baec4446efb96483d414a11bc71a483ded1d2b | tests/alerts/alert_test_case.py | tests/alerts/alert_test_case.py | import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], events_type='event', expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.events_type = events_type
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
| import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
| Remove events_type from alert test case | Remove events_type from alert test case
| Python | mpl-2.0 | mpurzynski/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef,mozilla/MozDef,jeffbryner/MozDef,jeffbryner/MozDef | import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], events_type='event', expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.events_type = events_type
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
Remove events_type from alert test case | import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
| <commit_before>import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], events_type='event', expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.events_type = events_type
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
<commit_msg>Remove events_type from alert test case<commit_after> | import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
| import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], events_type='event', expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.events_type = events_type
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
Remove events_type from alert test caseimport os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
| <commit_before>import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], events_type='event', expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.events_type = events_type
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
<commit_msg>Remove events_type from alert test case<commit_after>import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts"))
from alert_test_suite import AlertTestSuite
class AlertTestCase(object):
def __init__(self, description, events=[], expected_alert=None):
self.description = description
# As a result of defining our test cases as class level variables
# we need to copy each event so that other tests dont
# mess with the same instance in memory
self.events = AlertTestSuite.copy(events)
assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.'
self.expected_alert = expected_alert
self.full_events = []
def run(self, alert_filename, alert_classname):
alert_file_module = __import__(alert_filename)
alert_class_attr = getattr(alert_file_module, alert_classname)
alert_task = alert_class_attr()
alert_task.run()
return alert_task
|
454b1ee88a0dea04fc7a551a411fad060546f391 | document/management/commands/clean_submitters.py | document/management/commands/clean_submitters.py | import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
@transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
| import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
# @transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
| Remove atomic transaction from command to reduce memory usage | Remove atomic transaction from command to reduce memory usage
| Python | mit | openkamer/openkamer,openkamer/openkamer,openkamer/openkamer,openkamer/openkamer | import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
@transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
Remove atomic transaction from command to reduce memory usage | import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
# @transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
| <commit_before>import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
@transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
<commit_msg>Remove atomic transaction from command to reduce memory usage<commit_after> | import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
# @transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
| import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
@transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
Remove atomic transaction from command to reduce memory usageimport logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
# @transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
| <commit_before>import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
@transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
<commit_msg>Remove atomic transaction from command to reduce memory usage<commit_after>import logging
from django.core.management.base import BaseCommand
from django.db import transaction
from document.models import Document
from document.models import Submitter
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
self.do()
# @transaction.atomic
def do(self):
submitters = Submitter.objects.all()
documents = Document.objects.all()
counter = 1
n_docs = documents.count()
print(n_docs)
for document in documents:
print('document ' + str(counter) + '/' + str(n_docs))
doc_submitters = submitters.filter(document=document)
person_ids = []
for doc_sub in doc_submitters:
if doc_sub.person.id in person_ids:
doc_sub.delete()
else:
person_ids.append(doc_sub.person.id)
counter += 1
|
5a8348fa634748caf55f1c35e204fda500297157 | pywkeeper.py | pywkeeper.py | #!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
if len(arguments) == 2:
length = int(arguments[1])
else:
length = DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
| #!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
length = options.n if options.n else DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option("-n", type='int', help="With 'generate', the length of the generated password")
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
| Use optparser for generate length | Use optparser for generate length
| Python | unlicense | kvikshaug/pwkeeper | #!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
if len(arguments) == 2:
length = int(arguments[1])
else:
length = DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
Use optparser for generate length | #!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
length = options.n if options.n else DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option("-n", type='int', help="With 'generate', the length of the generated password")
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
| <commit_before>#!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
if len(arguments) == 2:
length = int(arguments[1])
else:
length = DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
<commit_msg>Use optparser for generate length<commit_after> | #!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
length = options.n if options.n else DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option("-n", type='int', help="With 'generate', the length of the generated password")
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
| #!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
if len(arguments) == 2:
length = int(arguments[1])
else:
length = DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
Use optparser for generate length#!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
length = options.n if options.n else DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option("-n", type='int', help="With 'generate', the length of the generated password")
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
| <commit_before>#!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
if len(arguments) == 2:
length = int(arguments[1])
else:
length = DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
<commit_msg>Use optparser for generate length<commit_after>#!/usr/bin/env python
import json
import os
import optparse
import random
from crypto import *
from file_io import *
from settings import *
options = None
arguments = None
def main():
if arguments[0] == 'generate':
generate()
elif arguments[0] == 'save':
save()
elif arguments[0] == 'edit':
edit()
def save():
try:
bytes = multiple_of(read_file(DECRYPTED_FILE), BLOCK_LENGTH)
except IOError:
print("There's no plaintext file to save!")
print("Tried %s" % os.path.abspath(DECRYPTED_FILE))
return
iv, encrypted = encrypt(bytes)
write_file(ENCRYPTED_FILE, iv + encrypted)
os.unlink(DECRYPTED_FILE)
print("Removed plaintext and saved encrypted file.")
def edit():
bytes = decrypt()
write_file(DECRYPTED_FILE, bytes)
print("Plaintext written to: %s" % os.path.abspath(DECRYPTED_FILE))
def generate():
length = options.n if options.n else DEFAULT_PASSWORD_LENGTH
for i in range(length):
print(random.choice(KEY_CHARS), end='')
print()
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option("-n", type='int', help="With 'generate', the length of the generated password")
options, arguments = p.parse_args()
if len(arguments) == 0:
arguments.append(DEFAULT_ARGUMENT)
main()
|
a09491de1278db810c31280405c923c30337deb0 | scanblog/scanning/management/commands/fixuploadperms.py | scanblog/scanning/management/commands/fixuploadperms.py | import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
| import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
| Change order of permission changes | Change order of permission changes
| Python | agpl-3.0 | yourcelf/btb,yourcelf/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,flexpeace/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,yourcelf/btb | import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
Change order of permission changes | import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
| <commit_before>import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
<commit_msg>Change order of permission changes<commit_after> | import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
| import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
Change order of permission changesimport os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
| <commit_before>import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
<commit_msg>Change order of permission changes<commit_after>import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
args = ''
help = "Set all permissions in the uploads directory for deploy."
def handle(self, *args, **kwargs):
for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO),
os.path.join(settings.MEDIA_ROOT, "letters"),
os.path.join(settings.MEDIA_ROOT, "mailings"),
os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"),
settings.PUBLIC_MEDIA_ROOT):
print dirname
# files: -rw-rw-r--
os.system('sudo chmod -R 0664 "%s"' % dirname)
os.system('sudo chown -R www-data.btb "%s"' % dirname)
# directories: -rwxrwsr-x
os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
|
3ba3788fd8b1aa614056de144b6262c921d83702 | python/qitools/interact.py | python/qitools/interact.py | ## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
anwer = raw_input("> ")
return anwer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
| ## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
answer = raw_input("> ")
return answer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
| Fix typo in variable name | Fix typo in variable name
| Python | bsd-3-clause | dmerejkowsky/qibuild,aldebaran/qibuild,aldebaran/qibuild,aldebaran/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild,dmerejkowsky/qibuild,dmerejkowsky/qibuild,dmerejkowsky/qibuild | ## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
anwer = raw_input("> ")
return anwer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
Fix typo in variable name | ## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
answer = raw_input("> ")
return answer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
| <commit_before>## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
anwer = raw_input("> ")
return anwer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
<commit_msg>Fix typo in variable name<commit_after> | ## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
answer = raw_input("> ")
return answer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
| ## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
anwer = raw_input("> ")
return anwer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
Fix typo in variable name## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
answer = raw_input("> ")
return answer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
| <commit_before>## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
anwer = raw_input("> ")
return anwer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
<commit_msg>Fix typo in variable name<commit_after>## Copyright (C) 2011 Aldebaran Robotics
"""Small set of tools to interact with the user
"""
#TODO: color!
def ask_choice(choices, input_text):
"""Ask the user to choose from a list of choices
"""
print "::", input_text
for i, choice in enumerate(choices):
print " ", (i+1), choice
keep_asking = True
res = None
while keep_asking:
answer = raw_input("> ")
if not answer:
return choices[0]
try:
index = int(answer)
except ValueError:
print "Please enter number"
continue
if index not in range(1, len(choices)+1):
print "%i is out of range" % index
continue
res = choices[index-1]
keep_asking = False
return res
def ask_yes_no(question):
"""Ask the user to answer by yes or no"""
print "::", question, "(y/n)?"
answer = raw_input("> ")
return answer == "y"
def ask_string(question, default=None):
"""Ask the user to enter something.
Returns what the user entered
"""
if default:
question += " (%s)" % default
print "::", question
answer = raw_input("> ")
if not answer:
return default
return answer
|
80bdeb25795776bd73b911909863bc54b0afeea4 | tree/treeplayer/test/dataframe/dataframe_histograms.py | tree/treeplayer/test/dataframe/dataframe_histograms.py | import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main() | import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main()
| Replace tabs with spaces in the unit tests. | [TDF] Replace tabs with spaces in the unit tests.
| Python | lgpl-2.1 | karies/root,root-mirror/root,karies/root,root-mirror/root,root-mirror/root,karies/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,root-mirror/root,olifre/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,olifre/root,zzxuanyuan/root,root-mirror/root,zzxuanyuan/root,olifre/root,karies/root,karies/root,zzxuanyuan/root,root-mirror/root,olifre/root,olifre/root,olifre/root,zzxuanyuan/root,root-mirror/root,karies/root,karies/root,olifre/root,root-mirror/root,zzxuanyuan/root,zzxuanyuan/root,zzxuanyuan/root,karies/root,olifre/root,karies/root,karies/root,zzxuanyuan/root,karies/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root | import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main()[TDF] Replace tabs with spaces in the unit tests. | import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main()
| <commit_before>import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main()<commit_msg>[TDF] Replace tabs with spaces in the unit tests.<commit_after> | import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main()
| import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main()[TDF] Replace tabs with spaces in the unit tests.import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main()
| <commit_before>import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main()<commit_msg>[TDF] Replace tabs with spaces in the unit tests.<commit_after>import unittest
import ROOT
class HistogramsFromTDF(unittest.TestCase):
@classmethod
def setUp(cls):
ROOT.gRandom.SetSeed(1)
def test_histo1D(self):
ROOT.gRandom.SetSeed(1)
tdf = ROOT.ROOT.Experimental.TDataFrame(64)
g = tdf.Define("r","gRandom->Gaus(0,1)")
h1Proxy = g.Histo1D(("h1","h1",64, -2., 2.),"r")
h1 = h1Proxy.GetValue()
cppCode = 'gRandom->SetSeed(1);' + \
'ROOT::Experimental::TDataFrame tdf(64);' + \
'auto g = tdf.Define("r","gRandom->Gaus(0,1)");' + \
'auto h2Proxy = g.Histo1D({"h1","h1",64, -2., 2.},"r");'
ROOT.gInterpreter.ProcessLine(cppCode)
h2 = ROOT.h2Proxy.GetValue()
self.assertEqual(h1.GetEntries(), h2.GetEntries())
self.assertEqual(h1.GetMean(), h2.GetMean())
self.assertEqual(h1.GetStdDev(), h2.GetStdDev())
if __name__ == '__main__':
unittest.main()
|
836551789ee6764f48a1328804c55222acc106b1 | lc131_palindrome_partitioning.py | lc131_palindrome_partitioning.py | """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
if s[start:i+1] == s[start:i+1][::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
| """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
partial = s[start:i+1]
if partial == partial[::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
Time complexity: O(n * 2^n), where n is the length of s.
Space complexity: O(n).
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
| Use partial for duplicated partial string | Use partial for duplicated partial string
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
if s[start:i+1] == s[start:i+1][::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
Use partial for duplicated partial string | """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
partial = s[start:i+1]
if partial == partial[::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
Time complexity: O(n * 2^n), where n is the length of s.
Space complexity: O(n).
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
| <commit_before>"""Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
if s[start:i+1] == s[start:i+1][::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
<commit_msg>Use partial for duplicated partial string<commit_after> | """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
partial = s[start:i+1]
if partial == partial[::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
Time complexity: O(n * 2^n), where n is the length of s.
Space complexity: O(n).
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
| """Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
if s[start:i+1] == s[start:i+1][::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
Use partial for duplicated partial string"""Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
partial = s[start:i+1]
if partial == partial[::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
Time complexity: O(n * 2^n), where n is the length of s.
Space complexity: O(n).
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
| <commit_before>"""Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
if s[start:i+1] == s[start:i+1][::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
<commit_msg>Use partial for duplicated partial string<commit_after>"""Leetcode 131. Palindrome Partitioning
Medium
URL: https://leetcode.com/problems/palindrome-partitioning/
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
class Solution(object):
def _backtrack(self, result, temps, s, start):
if start == len(s):
result.append(temps[:])
return None
for i in range(start, len(s)):
# Check if palindrome.
partial = s[start:i+1]
if partial == partial[::-1]:
temps.append(s[start:i+1])
self._backtrack(result, temps, s, i + 1)
temps.pop()
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
Time complexity: O(n * 2^n), where n is the length of s.
Space complexity: O(n).
"""
# Apply backtracking.
result = []
temps = []
start = 0
self._backtrack(result, temps, s, start)
return result
def main():
s = "aab"
print Solution().partition(s)
if __name__ == '__main__':
main()
|
703861029a2d3a36bbb18ed9e56c55064323478c | account_banking_payment_export/migrations/8.0.0.1.166/pre-migrate.py | account_banking_payment_export/migrations/8.0.0.1.166/pre-migrate.py | # -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
| # -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
('payment_order', 'total'))
if cr.fetchone()[0] == 0:
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
| Check if column exists before creating it | [FIX] account_banking_payment_export: Check if column exists before creating it
| Python | agpl-3.0 | incaser/bank-payment,damdam-s/bank-payment,sergiocorato/bank-payment,Antiun/bank-payment,acsone/bank-payment,damdam-s/bank-payment,CompassionCH/bank-payment,diagramsoftware/bank-payment,sergiocorato/bank-payment,open-synergy/bank-payment,hbrunn/bank-payment,Antiun/bank-payment,CompassionCH/bank-payment | # -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
[FIX] account_banking_payment_export: Check if column exists before creating it | # -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
('payment_order', 'total'))
if cr.fetchone()[0] == 0:
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
| <commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
<commit_msg>[FIX] account_banking_payment_export: Check if column exists before creating it<commit_after> | # -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
('payment_order', 'total'))
if cr.fetchone()[0] == 0:
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
| # -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
[FIX] account_banking_payment_export: Check if column exists before creating it# -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
('payment_order', 'total'))
if cr.fetchone()[0] == 0:
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
| <commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
<commit_msg>[FIX] account_banking_payment_export: Check if column exists before creating it<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# 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/>.
#
##############################################################################
def migrate(cr, version):
cr.execute(
'SELECT count(attname) FROM pg_attribute '
'WHERE attrelid = '
'( SELECT oid FROM pg_class WHERE relname = %s ) '
'AND attname = %s',
('payment_order', 'total'))
if cr.fetchone()[0] == 0:
cr.execute('alter table payment_order add column total numeric')
cr.execute(
'update payment_order '
'set total=totals.total '
'from '
'(select order_id, sum(amount_currency) total '
'from payment_line group by order_id) totals '
'where payment_order.id=totals.order_id')
|
d521435ecd6082d0235ef489fd6ae3395bbbfc44 | poradnia/config/local.py | poradnia/config/local.py | # -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
'JQUERY_URL': 'http://localhost:8000/static/js/jquery.min.js',
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
| # -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
| Drop loading jquery by django-debug-toolbar - it is integrated now | Drop loading jquery by django-debug-toolbar - it is integrated now
| Python | mit | watchdogpolska/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia | # -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
'JQUERY_URL': 'http://localhost:8000/static/js/jquery.min.js',
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
Drop loading jquery by django-debug-toolbar - it is integrated now | # -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
| <commit_before># -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
'JQUERY_URL': 'http://localhost:8000/static/js/jquery.min.js',
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
<commit_msg>Drop loading jquery by django-debug-toolbar - it is integrated now<commit_after> | # -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
| # -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
'JQUERY_URL': 'http://localhost:8000/static/js/jquery.min.js',
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
Drop loading jquery by django-debug-toolbar - it is integrated now# -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
| <commit_before># -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
'JQUERY_URL': 'http://localhost:8000/static/js/jquery.min.js',
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
<commit_msg>Drop loading jquery by django-debug-toolbar - it is integrated now<commit_after># -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
# INSTALLED_APPS
INSTALLED_APPS = Common.INSTALLED_APPS
# END INSTALLED_APPS
# Mail settings
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_BACKEND = values.Value('django.core.mail.backends.console.EmailBackend')
# End mail settings
# django-debug-toolbar
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': [
'debug_toolbar.panels.redirects.RedirectsPanel',
],
'SHOW_TEMPLATE_CONTEXT': True,
}
# end django-debug-toolbar
# Your local stuff: Below this line define 3rd party libary settings
|
2b8377d968dc336cd344dd4191e24b3c4f76857d | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field
# We need to handle the case where our noop 0008 ran AND the case
# where the original 0008 ran. We do that by using Django's introspection
# API to query INFORMATION_SCHEMA. _meta is unavailable as the
# column has already been removed from the model.
fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
operations = []
if not any(f.name == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema directly with code lifted
# from the internals of django.db.backends.mysql.introspection.py
if connection.vendor == 'sqlite':
fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
rows = cursor.fetchall()
return [r[0] for r in rows]
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field We need to
# handle the case where our noop 0008 ran AND the case where the original
# 0008 ran. We do that by using the standard information_schema to find out
# what columns exist. _meta is unavailable as the column has already been
# removed from the model
operations = []
fields = table_description()
# during a migration from scratch, fields will be empty, but we do not want to add
# an additional facebook_url
if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
| Migrate correctly from scratch also | Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a select * from the table.
Lift the main part of mysql's get_table_description up to the migration itself
and just inspect it directly. Continue to call the API for sqlite.
| Python | agpl-3.0 | Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field
# We need to handle the case where our noop 0008 ran AND the case
# where the original 0008 ran. We do that by using Django's introspection
# API to query INFORMATION_SCHEMA. _meta is unavailable as the
# column has already been removed from the model.
fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
operations = []
if not any(f.name == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a select * from the table.
Lift the main part of mysql's get_table_description up to the migration itself
and just inspect it directly. Continue to call the API for sqlite. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema directly with code lifted
# from the internals of django.db.backends.mysql.introspection.py
if connection.vendor == 'sqlite':
fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
rows = cursor.fetchall()
return [r[0] for r in rows]
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field We need to
# handle the case where our noop 0008 ran AND the case where the original
# 0008 ran. We do that by using the standard information_schema to find out
# what columns exist. _meta is unavailable as the column has already been
# removed from the model
operations = []
fields = table_description()
# during a migration from scratch, fields will be empty, but we do not want to add
# an additional facebook_url
if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field
# We need to handle the case where our noop 0008 ran AND the case
# where the original 0008 ran. We do that by using Django's introspection
# API to query INFORMATION_SCHEMA. _meta is unavailable as the
# column has already been removed from the model.
fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
operations = []
if not any(f.name == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
<commit_msg>Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a select * from the table.
Lift the main part of mysql's get_table_description up to the migration itself
and just inspect it directly. Continue to call the API for sqlite.<commit_after> | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema directly with code lifted
# from the internals of django.db.backends.mysql.introspection.py
if connection.vendor == 'sqlite':
fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
rows = cursor.fetchall()
return [r[0] for r in rows]
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field We need to
# handle the case where our noop 0008 ran AND the case where the original
# 0008 ran. We do that by using the standard information_schema to find out
# what columns exist. _meta is unavailable as the column has already been
# removed from the model
operations = []
fields = table_description()
# during a migration from scratch, fields will be empty, but we do not want to add
# an additional facebook_url
if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field
# We need to handle the case where our noop 0008 ran AND the case
# where the original 0008 ran. We do that by using Django's introspection
# API to query INFORMATION_SCHEMA. _meta is unavailable as the
# column has already been removed from the model.
fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
operations = []
if not any(f.name == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a select * from the table.
Lift the main part of mysql's get_table_description up to the migration itself
and just inspect it directly. Continue to call the API for sqlite.# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema directly with code lifted
# from the internals of django.db.backends.mysql.introspection.py
if connection.vendor == 'sqlite':
fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
rows = cursor.fetchall()
return [r[0] for r in rows]
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field We need to
# handle the case where our noop 0008 ran AND the case where the original
# 0008 ran. We do that by using the standard information_schema to find out
# what columns exist. _meta is unavailable as the column has already been
# removed from the model
operations = []
fields = table_description()
# during a migration from scratch, fields will be empty, but we do not want to add
# an additional facebook_url
if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field
# We need to handle the case where our noop 0008 ran AND the case
# where the original 0008 ran. We do that by using Django's introspection
# API to query INFORMATION_SCHEMA. _meta is unavailable as the
# column has already been removed from the model.
fields = connection.introspection.get_table_description(connection.cursor(),'course_overviews_courseoverview')
operations = []
if not any(f.name == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
<commit_msg>Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a select * from the table.
Lift the main part of mysql's get_table_description up to the migration itself
and just inspect it directly. Continue to call the API for sqlite.<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema directly with code lifted
# from the internals of django.db.backends.mysql.introspection.py
if connection.vendor == 'sqlite':
fields = connection.introspection.get_table_description(connection.cursor(), 'course_overviews_courseoverview')
return [f.name for f in fields]
else:
cursor = connection.cursor()
cursor.execute("""
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'course_overviews_courseoverview' AND table_schema = DATABASE()""")
rows = cursor.fetchall()
return [r[0] for r in rows]
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_remove_courseoverview_facebook_url'),
]
# An original version of 0008 removed the facebook_url field We need to
# handle the case where our noop 0008 ran AND the case where the original
# 0008 ran. We do that by using the standard information_schema to find out
# what columns exist. _meta is unavailable as the column has already been
# removed from the model
operations = []
fields = table_description()
# during a migration from scratch, fields will be empty, but we do not want to add
# an additional facebook_url
if fields and not any(f == 'facebook_url' for f in fields):
operations += migrations.AddField(
model_name='courseoverview',
name='facebook_url',
field=models.TextField(null=True),
),
|
dd646b7573c1e2bb41f60723e02aa6ddf58d59f6 | kobo/apps/help/permissions.py | kobo/apps/help/permissions.py | # coding: utf-8
from rest_framework import permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif request.data.keys() == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
# Sorry, buddy.
return False
| # coding: utf-8
from rest_framework import exceptions, permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif list(request.data) == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
else:
formatted_fields = ', '.join(
[f'`{x}`' for x in request.data.keys()]
)
raise exceptions.PermissionDenied(
detail=(
'You may update only `interactions`, but your request '
f'contained {formatted_fields}.'
)
)
# Sorry, buddy.
return False
| Fix Python 2-to-3 bug in in-app messages | Fix Python 2-to-3 bug in in-app messages
…so that the permission check for `PATCH`ing `interactions` does not
always fail. Fixes #2762
| Python | agpl-3.0 | kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi | # coding: utf-8
from rest_framework import permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif request.data.keys() == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
# Sorry, buddy.
return False
Fix Python 2-to-3 bug in in-app messages
…so that the permission check for `PATCH`ing `interactions` does not
always fail. Fixes #2762 | # coding: utf-8
from rest_framework import exceptions, permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif list(request.data) == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
else:
formatted_fields = ', '.join(
[f'`{x}`' for x in request.data.keys()]
)
raise exceptions.PermissionDenied(
detail=(
'You may update only `interactions`, but your request '
f'contained {formatted_fields}.'
)
)
# Sorry, buddy.
return False
| <commit_before># coding: utf-8
from rest_framework import permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif request.data.keys() == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
# Sorry, buddy.
return False
<commit_msg>Fix Python 2-to-3 bug in in-app messages
…so that the permission check for `PATCH`ing `interactions` does not
always fail. Fixes #2762<commit_after> | # coding: utf-8
from rest_framework import exceptions, permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif list(request.data) == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
else:
formatted_fields = ', '.join(
[f'`{x}`' for x in request.data.keys()]
)
raise exceptions.PermissionDenied(
detail=(
'You may update only `interactions`, but your request '
f'contained {formatted_fields}.'
)
)
# Sorry, buddy.
return False
| # coding: utf-8
from rest_framework import permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif request.data.keys() == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
# Sorry, buddy.
return False
Fix Python 2-to-3 bug in in-app messages
…so that the permission check for `PATCH`ing `interactions` does not
always fail. Fixes #2762# coding: utf-8
from rest_framework import exceptions, permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif list(request.data) == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
else:
formatted_fields = ', '.join(
[f'`{x}`' for x in request.data.keys()]
)
raise exceptions.PermissionDenied(
detail=(
'You may update only `interactions`, but your request '
f'contained {formatted_fields}.'
)
)
# Sorry, buddy.
return False
| <commit_before># coding: utf-8
from rest_framework import permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif request.data.keys() == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
# Sorry, buddy.
return False
<commit_msg>Fix Python 2-to-3 bug in in-app messages
…so that the permission check for `PATCH`ing `interactions` does not
always fail. Fixes #2762<commit_after># coding: utf-8
from rest_framework import exceptions, permissions
class InAppMessagePermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user.is_authenticated:
# Deny access to anonymous users
return False
if request.user.is_superuser:
# Allow superusers to do anything
return True
if request.method in permissions.SAFE_METHODS:
# Allow read-only access to any authenticated user
return True
elif request.method == 'PATCH':
if not request.data:
# A `PATCH` with no data is a check to see what's allowed, or
# that's what the DRF "Browsable API" does, at least. We'll
# wave it through for authenticated users
return True
elif list(request.data) == ['interactions']:
# Allow any authenticated user to update their own interactions
return True
else:
formatted_fields = ', '.join(
[f'`{x}`' for x in request.data.keys()]
)
raise exceptions.PermissionDenied(
detail=(
'You may update only `interactions`, but your request '
f'contained {formatted_fields}.'
)
)
# Sorry, buddy.
return False
|
61db23b71aa15d14b8c88e36205c17cc1b01882f | frontends/etiquette_flask/etiquette_flask_prod.py | frontends/etiquette_flask/etiquette_flask_prod.py | '''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb(create=False)
| '''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb()
| Remove arg create because it will use closest_photodb. | Remove arg create because it will use closest_photodb.
| Python | bsd-3-clause | voussoir/etiquette,voussoir/etiquette,voussoir/etiquette | '''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb(create=False)
Remove arg create because it will use closest_photodb. | '''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb()
| <commit_before>'''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb(create=False)
<commit_msg>Remove arg create because it will use closest_photodb.<commit_after> | '''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb()
| '''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb(create=False)
Remove arg create because it will use closest_photodb.'''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb()
| <commit_before>'''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb(create=False)
<commit_msg>Remove arg create because it will use closest_photodb.<commit_after>'''
This file is the WSGI entrypoint for remote / production use.
If you are using Gunicorn, for example:
gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-"
'''
import werkzeug.middleware.proxy_fix
import backend
backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.wsgi_app)
site = backend.site
backend.common.init_photodb()
|
5355d55bf4ca0c4c0a3f2ee53f59275ef393af9d | dallinger_scripts/worker.py | dallinger_scripts/worker.py | """Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(redis_url, queue_class=LifoQueue)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
| """Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(
url=redis_url, ssl_cert_reqs="none", queue_class=LifoQueue
)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
| Remove cert requirements from hopefully last spot | Remove cert requirements from hopefully last spot
| Python | mit | Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger | """Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(redis_url, queue_class=LifoQueue)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
Remove cert requirements from hopefully last spot | """Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(
url=redis_url, ssl_cert_reqs="none", queue_class=LifoQueue
)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
| <commit_before>"""Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(redis_url, queue_class=LifoQueue)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
<commit_msg>Remove cert requirements from hopefully last spot<commit_after> | """Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(
url=redis_url, ssl_cert_reqs="none", queue_class=LifoQueue
)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
| """Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(redis_url, queue_class=LifoQueue)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
Remove cert requirements from hopefully last spot"""Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(
url=redis_url, ssl_cert_reqs="none", queue_class=LifoQueue
)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
| <commit_before>"""Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(redis_url, queue_class=LifoQueue)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
<commit_msg>Remove cert requirements from hopefully last spot<commit_after>"""Heroku web worker."""
listen = ["high", "default", "low"]
def main():
import gevent.monkey
gevent.monkey.patch_all()
from gevent.queue import LifoQueue
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
import os
from redis import BlockingConnectionPool, StrictRedis
from rq import Queue, Connection
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)
redis_url = os.getenv("REDIS_URL", "redis://localhost:6379")
# Specify queue class for improved performance with gevent.
# see http://carsonip.me/posts/10x-faster-python-gevent-redis-connection-pool/
redis_pool = BlockingConnectionPool.from_url(
url=redis_url, ssl_cert_reqs="none", queue_class=LifoQueue
)
redis_conn = StrictRedis(connection_pool=redis_pool)
with Connection(redis_conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
if __name__ == "__main__": # pragma: nocover
main()
|
3df97670f91c20ff2da26936dcf40592dbef89f0 | indra/sources/crog/__init__.py | indra/sources/crog/__init__.py | # -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
| # -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
| Fix citation formatting in docstring | Fix citation formatting in docstring
| Python | bsd-2-clause | bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/belpy,bgyori/indra | # -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
Fix citation formatting in docstring | # -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
| <commit_before># -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
<commit_msg>Fix citation formatting in docstring<commit_after> | # -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
| # -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
Fix citation formatting in docstring# -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
| <commit_before># -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
<commit_msg>Fix citation formatting in docstring<commit_after># -*- coding: utf-8 -*-
"""Processor for the `Chemical Roles Graph (CRoG)
<https://github.com/chemical-roles/chemical-roles>`_.
Contains axiomization of ChEBI roles, their targets, and actual
relationship polarity.
* `Extension of Roles in the ChEBI Ontology
<https://doi.org/10.26434/chemrxiv.12591221>`_.
Hoyt, C. T., *et al.* (2020). *ChemRxiv*, 12591221.
"""
from .api import process_from_web
from .processor import CrogProcessor
|
5b7469d573235405f735089e87d3b939b1a5e142 | tests/test_quotes.py | tests/test_quotes.py | import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8) | import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)
def test_is_cast_credit(self):
cast1 = 'Bryan Cranston - Walter White'.split()
cast2 = 'Giancarlo Esposito - Gustavo "Gus" Fring'.split()
self.assertTrue(wikiquote.is_cast_credit(cast1))
self.assertTrue(wikiquote.is_cast_credit(cast2))
| Add test for alternate version of cast credit | Add test for alternate version of cast credit
| Python | mit | federicotdn/python-wikiquotes,jakerockland/python-wikiquotes | import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)Add test for alternate version of cast credit | import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)
def test_is_cast_credit(self):
cast1 = 'Bryan Cranston - Walter White'.split()
cast2 = 'Giancarlo Esposito - Gustavo "Gus" Fring'.split()
self.assertTrue(wikiquote.is_cast_credit(cast1))
self.assertTrue(wikiquote.is_cast_credit(cast2))
| <commit_before>import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)<commit_msg>Add test for alternate version of cast credit<commit_after> | import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)
def test_is_cast_credit(self):
cast1 = 'Bryan Cranston - Walter White'.split()
cast2 = 'Giancarlo Esposito - Gustavo "Gus" Fring'.split()
self.assertTrue(wikiquote.is_cast_credit(cast1))
self.assertTrue(wikiquote.is_cast_credit(cast2))
| import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)Add test for alternate version of cast creditimport wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)
def test_is_cast_credit(self):
cast1 = 'Bryan Cranston - Walter White'.split()
cast2 = 'Giancarlo Esposito - Gustavo "Gus" Fring'.split()
self.assertTrue(wikiquote.is_cast_credit(cast1))
self.assertTrue(wikiquote.is_cast_credit(cast2))
| <commit_before>import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)<commit_msg>Add test for alternate version of cast credit<commit_after>import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)
def test_is_cast_credit(self):
cast1 = 'Bryan Cranston - Walter White'.split()
cast2 = 'Giancarlo Esposito - Gustavo "Gus" Fring'.split()
self.assertTrue(wikiquote.is_cast_credit(cast1))
self.assertTrue(wikiquote.is_cast_credit(cast2))
|
53c014a5ccff103a89c2b9ff9b5f1f30b5d4f7b0 | tests/test_states.py | tests/test_states.py | # coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
assert not valid_solution(states1[0:-1], order, drop_zone1)
| # coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
from mmvdApp.utils import InvalidOrderException
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
with pytest.raises(InvalidOrderException):
valid_solution(states1[0:-1], order, drop_zone1)
| Test missing checking for InvalidOrderException raised | Fix: Test missing checking for InvalidOrderException raised
| Python | mit | WojciechFocus/MMVD,WojciechFocus/MMVD | # coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
assert not valid_solution(states1[0:-1], order, drop_zone1)
Fix: Test missing checking for InvalidOrderException raised | # coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
from mmvdApp.utils import InvalidOrderException
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
with pytest.raises(InvalidOrderException):
valid_solution(states1[0:-1], order, drop_zone1)
| <commit_before># coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
assert not valid_solution(states1[0:-1], order, drop_zone1)
<commit_msg>Fix: Test missing checking for InvalidOrderException raised<commit_after> | # coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
from mmvdApp.utils import InvalidOrderException
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
with pytest.raises(InvalidOrderException):
valid_solution(states1[0:-1], order, drop_zone1)
| # coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
assert not valid_solution(states1[0:-1], order, drop_zone1)
Fix: Test missing checking for InvalidOrderException raised# coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
from mmvdApp.utils import InvalidOrderException
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
with pytest.raises(InvalidOrderException):
valid_solution(states1[0:-1], order, drop_zone1)
| <commit_before># coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
assert not valid_solution(states1[0:-1], order, drop_zone1)
<commit_msg>Fix: Test missing checking for InvalidOrderException raised<commit_after># coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
from mmvdApp.utils import InvalidOrderException
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
with pytest.raises(InvalidOrderException):
valid_solution(states1[0:-1], order, drop_zone1)
|
c1b600596e49409daf31d20f821f280d0aadf124 | emission/net/usercache/formatters/android/motion_activity.py | emission/net/usercache/formatters/android/motion_activity.py | import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
else:
data.confidence = entry.data.zzaEh
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
| import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
elif 'zzaEg' in entry.data:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaKM).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
elif 'zzaEh' in entry.data:
data.confidence = entry.data.zzaEh
else:
data.confidence = entry.data.zzaKN
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
| Support the new google play motion activity format | Support the new google play motion activity format
As part of the change to slim down the apk for android,
https://github.com/e-mission/e-mission-phone/pull/46,
https://github.com/e-mission/e-mission-data-collection/pull/116
we switched from google play version from 8.1.0 to 8.3.0, which is the version
that has separate jar files, at least in my install.
But this changed the motion activity format - the field names are now `zzaKM`
and `zzaKN` instead of `zzaEg` and `zzaEh`. So we change the formatter on the
server to handle this use case as well.
Note that we should really fix
https://github.com/e-mission/e-mission-data-collection/issues/80
to stop running into this in the future
| Python | bsd-3-clause | yw374cornell/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server | import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
else:
data.confidence = entry.data.zzaEh
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
Support the new google play motion activity format
As part of the change to slim down the apk for android,
https://github.com/e-mission/e-mission-phone/pull/46,
https://github.com/e-mission/e-mission-data-collection/pull/116
we switched from google play version from 8.1.0 to 8.3.0, which is the version
that has separate jar files, at least in my install.
But this changed the motion activity format - the field names are now `zzaKM`
and `zzaKN` instead of `zzaEg` and `zzaEh`. So we change the formatter on the
server to handle this use case as well.
Note that we should really fix
https://github.com/e-mission/e-mission-data-collection/issues/80
to stop running into this in the future | import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
elif 'zzaEg' in entry.data:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaKM).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
elif 'zzaEh' in entry.data:
data.confidence = entry.data.zzaEh
else:
data.confidence = entry.data.zzaKN
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
| <commit_before>import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
else:
data.confidence = entry.data.zzaEh
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
<commit_msg>Support the new google play motion activity format
As part of the change to slim down the apk for android,
https://github.com/e-mission/e-mission-phone/pull/46,
https://github.com/e-mission/e-mission-data-collection/pull/116
we switched from google play version from 8.1.0 to 8.3.0, which is the version
that has separate jar files, at least in my install.
But this changed the motion activity format - the field names are now `zzaKM`
and `zzaKN` instead of `zzaEg` and `zzaEh`. So we change the formatter on the
server to handle this use case as well.
Note that we should really fix
https://github.com/e-mission/e-mission-data-collection/issues/80
to stop running into this in the future<commit_after> | import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
elif 'zzaEg' in entry.data:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaKM).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
elif 'zzaEh' in entry.data:
data.confidence = entry.data.zzaEh
else:
data.confidence = entry.data.zzaKN
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
| import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
else:
data.confidence = entry.data.zzaEh
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
Support the new google play motion activity format
As part of the change to slim down the apk for android,
https://github.com/e-mission/e-mission-phone/pull/46,
https://github.com/e-mission/e-mission-data-collection/pull/116
we switched from google play version from 8.1.0 to 8.3.0, which is the version
that has separate jar files, at least in my install.
But this changed the motion activity format - the field names are now `zzaKM`
and `zzaKN` instead of `zzaEg` and `zzaEh`. So we change the formatter on the
server to handle this use case as well.
Note that we should really fix
https://github.com/e-mission/e-mission-data-collection/issues/80
to stop running into this in the futureimport logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
elif 'zzaEg' in entry.data:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaKM).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
elif 'zzaEh' in entry.data:
data.confidence = entry.data.zzaEh
else:
data.confidence = entry.data.zzaKN
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
| <commit_before>import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
else:
data.confidence = entry.data.zzaEh
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
<commit_msg>Support the new google play motion activity format
As part of the change to slim down the apk for android,
https://github.com/e-mission/e-mission-phone/pull/46,
https://github.com/e-mission/e-mission-data-collection/pull/116
we switched from google play version from 8.1.0 to 8.3.0, which is the version
that has separate jar files, at least in my install.
But this changed the motion activity format - the field names are now `zzaKM`
and `zzaKN` instead of `zzaEg` and `zzaEh`. So we change the formatter on the
server to handle this use case as well.
Note that we should really fix
https://github.com/e-mission/e-mission-data-collection/issues/80
to stop running into this in the future<commit_after>import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
elif 'zzaEg' in entry.data:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaKM).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
elif 'zzaEh' in entry.data:
data.confidence = entry.data.zzaEh
else:
data.confidence = entry.data.zzaKN
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
|
61c256b11897fb7130faadbe2ffa3d02d0863db6 | scripts/export-tutorial.py | scripts/export-tutorial.py | """
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file))
| """
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be. Lowercase the filenames along the way, otherwise it causes issues once the
# files are hosted.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file.lower()))
| Remove old criuft. FIx. Partially fix export issue. | Remove old criuft. FIx. Partially fix export issue.
| Python | mit | ResidentMario/geoplot | """
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file))
Remove old criuft. FIx. Partially fix export issue. | """
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be. Lowercase the filenames along the way, otherwise it causes issues once the
# files are hosted.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file.lower()))
| <commit_before>"""
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file))
<commit_msg>Remove old criuft. FIx. Partially fix export issue.<commit_after> | """
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be. Lowercase the filenames along the way, otherwise it causes issues once the
# files are hosted.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file.lower()))
| """
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file))
Remove old criuft. FIx. Partially fix export issue."""
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be. Lowercase the filenames along the way, otherwise it causes issues once the
# files are hosted.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file.lower()))
| <commit_before>"""
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file))
<commit_msg>Remove old criuft. FIx. Partially fix export issue.<commit_after>"""
Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their
support files in the ../docs/tutorial folder.
"""
import subprocess
import os
# Get the list of tutorial notebooks.
tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)]
# Run them in-place.
for notebook in tutorial_notebooks:
print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]))
subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook),
"--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])
# Get the list of generated files.
gened_files = [f for f in os.listdir(".") if (".py" not in f)]
# Move them to where they need to be. Lowercase the filenames along the way, otherwise it causes issues once the
# files are hosted.
for file in gened_files:
os.rename(file, "../docs/tutorial/{0}".format(file.lower()))
|
ca33afb60d98da4d54c1bce8eef6e7251aaaff7f | runserver.py | runserver.py | from dasem.app import app
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
from gevent.wsgi import WSGIServer
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
| """Entrypoint to start app."""
from gevent.wsgi import WSGIServer
import logging
from dasem.app import create_app
app = create_app(logging_level=logging.DEBUG)
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
| Change to use app factory | Change to use app factory
| Python | apache-2.0 | fnielsen/dasem,fnielsen/dasem | from dasem.app import app
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
from gevent.wsgi import WSGIServer
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
Change to use app factory | """Entrypoint to start app."""
from gevent.wsgi import WSGIServer
import logging
from dasem.app import create_app
app = create_app(logging_level=logging.DEBUG)
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
| <commit_before>from dasem.app import app
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
from gevent.wsgi import WSGIServer
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
<commit_msg>Change to use app factory<commit_after> | """Entrypoint to start app."""
from gevent.wsgi import WSGIServer
import logging
from dasem.app import create_app
app = create_app(logging_level=logging.DEBUG)
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
| from dasem.app import app
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
from gevent.wsgi import WSGIServer
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
Change to use app factory"""Entrypoint to start app."""
from gevent.wsgi import WSGIServer
import logging
from dasem.app import create_app
app = create_app(logging_level=logging.DEBUG)
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
| <commit_before>from dasem.app import app
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
from gevent.wsgi import WSGIServer
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
<commit_msg>Change to use app factory<commit_after>"""Entrypoint to start app."""
from gevent.wsgi import WSGIServer
import logging
from dasem.app import create_app
app = create_app(logging_level=logging.DEBUG)
# WSGIServer server better than werkzeug
# http://stackoverflow.com/questions/37962925/
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
|
e93151490ea9c96b3856ec2e269552d8b52e0355 | lobster/cmssw/__init__.py | lobster/cmssw/__init__.py | from job import JobProvider
from publish import publish
from jobit import JobitStore
from merge import MergeProvider
| from job import JobProvider
from jobit import JobitStore
from merge import MergeProvider
from plotting import plot
from publish import publish
| Add plotting to the default imports of cmssw. | Add plotting to the default imports of cmssw.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster | from job import JobProvider
from publish import publish
from jobit import JobitStore
from merge import MergeProvider
Add plotting to the default imports of cmssw. | from job import JobProvider
from jobit import JobitStore
from merge import MergeProvider
from plotting import plot
from publish import publish
| <commit_before>from job import JobProvider
from publish import publish
from jobit import JobitStore
from merge import MergeProvider
<commit_msg>Add plotting to the default imports of cmssw.<commit_after> | from job import JobProvider
from jobit import JobitStore
from merge import MergeProvider
from plotting import plot
from publish import publish
| from job import JobProvider
from publish import publish
from jobit import JobitStore
from merge import MergeProvider
Add plotting to the default imports of cmssw.from job import JobProvider
from jobit import JobitStore
from merge import MergeProvider
from plotting import plot
from publish import publish
| <commit_before>from job import JobProvider
from publish import publish
from jobit import JobitStore
from merge import MergeProvider
<commit_msg>Add plotting to the default imports of cmssw.<commit_after>from job import JobProvider
from jobit import JobitStore
from merge import MergeProvider
from plotting import plot
from publish import publish
|
efcafd02930d293f780c4d18910c5a732c552c43 | scheduler.py | scheduler.py | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", hour=4)
#@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
| from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_SCHEDULE"):
schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
schedule_kwargs = {"hour": 4}
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
| Switch to a test schedule based on the environment | Switch to a test schedule based on the environment
Switching an environment variable and kicking the `clock` process feels
like a neater solution than commenting out one line, uncommenting
another, and redeploying.
| Python | apache-2.0 | rossrader/destalinator | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", hour=4)
#@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
Switch to a test schedule based on the environment
Switching an environment variable and kicking the `clock` process feels
like a neater solution than commenting out one line, uncommenting
another, and redeploying. | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_SCHEDULE"):
schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
schedule_kwargs = {"hour": 4}
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
| <commit_before>from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", hour=4)
#@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
<commit_msg>Switch to a test schedule based on the environment
Switching an environment variable and kicking the `clock` process feels
like a neater solution than commenting out one line, uncommenting
another, and redeploying.<commit_after> | from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_SCHEDULE"):
schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
schedule_kwargs = {"hour": 4}
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
| from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", hour=4)
#@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
Switch to a test schedule based on the environment
Switching an environment variable and kicking the `clock` process feels
like a neater solution than commenting out one line, uncommenting
another, and redeploying.from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_SCHEDULE"):
schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
schedule_kwargs = {"hour": 4}
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
| <commit_before>from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", hour=4)
#@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
<commit_msg>Switch to a test schedule based on the environment
Switching an environment variable and kicking the `clock` process feels
like a neater solution than commenting out one line, uncommenting
another, and redeploying.<commit_after>from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import warner
import archiver
import announcer
import flagger
import os
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("TEST_SCHEDULE"):
schedule_kwargs = {"hour": "*", "minute": "*/10"}
else:
schedule_kwargs = {"hour": 4}
logging.basicConfig()
sched = BlockingScheduler()
@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
print("Destalinating")
if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
print("ERR: Missing at least one Slack environment variable.")
else:
scheduled_warner = warner.Warner()
scheduled_archiver = archiver.Archiver()
scheduled_announcer = announcer.Announcer()
scheduled_flagger = flagger.Flagger()
print("Warning")
scheduled_warner.warn()
print("Archiving")
scheduled_archiver.archive()
print("Announcing")
scheduled_announcer.announce()
print("Flagging")
scheduled_flagger.flag()
print("OK: destalinated")
print("END: destalinate_job")
sched.start()
|
cdb32cd52552843400cfd5738458f3c2d26b0137 | app.py | app.py | """Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/')
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
| """Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/', methods=['GET', 'POST'])
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
| Allow POST requests on server side | Allow POST requests on server side
| Python | bsd-3-clause | jstewmon/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint | """Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/')
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
Allow POST requests on server side | """Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/', methods=['GET', 'POST'])
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
| <commit_before>"""Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/')
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
<commit_msg>Allow POST requests on server side<commit_after> | """Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/', methods=['GET', 'POST'])
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
| """Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/')
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
Allow POST requests on server side"""Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/', methods=['GET', 'POST'])
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
| <commit_before>"""Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/')
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
<commit_msg>Allow POST requests on server side<commit_after>"""Web app that serves proselint's API."""
from flask import Flask, request
import subprocess
from flask_cors import CORS, cross_origin
import uuid
import os
import re
import urllib2
import json
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = "Origin, X-Requested-With,Content-Type, Accept"
@app.route('/v1/', methods=['GET', 'POST'])
@cross_origin() # allow all origins all methods.
def lint():
"""Run linter on the provided text and return the results."""
id = uuid.uuid4()
filename = os.path.join("tmp", "{}.md".format(id))
text = urllib2.unquote(request.values['text'])
with open(filename, "w+") as f:
f.write(text)
out = subprocess.check_output("proselint {}".format(filename), shell=True)
r = re.compile(
"(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)")
out2 = sorted([r.search(line).groupdict() for line in out.splitlines()])
return json.dumps(out2)
if __name__ == '__main__':
app.debug = True
app.run()
|
b31a4eb259a0f165ea29c76a86c3683f33f079cd | bot.py | bot.py | from flask import Flask
from flask_restful import Resource, Api
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# send dm to user in the request info
pass
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
| import os
import json
from flask import Flask
from flask_restful import Resource, Api, reqparse
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
token = os.environ.get('SLACK_KEY')
sc = SlackClient(token)
print sc.api_call('api.test')
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# expect user_id and message data from the client
parser = reqparse.RequestParser()
parser.add_argument('user_id')
parser.add_argument('visitor_name')
# assign data from request to variables
args = parser.parse_args()
user_id = args.get('user_id')
visitor_name = args.get('visitor_name')
if visitor_name:
message = 'You have a visitor called {} at the gate.'.format(visitor_name)
else:
message = 'Hi! You have a visitor waiting for you.'
# returns a string - to be converted to dict later. Then retrieve
# channel ID
string_resp = sc.api_call('im.open', user=user_id)
dict_resp = json.loads(string_resp)
channelID = dict_resp.get('channel').get('id')
abc = sc.api_call(
'chat.postMessage',
as_user='true:',
channel=channelID,
text=message
)
return {'message': 'Notification sent'}, 200
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
| Create logic to post DM to user on slack when user id is provided | Create logic to post DM to user on slack when user id is provided
| Python | mit | NdagiStanley/visibot | from flask import Flask
from flask_restful import Resource, Api
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# send dm to user in the request info
pass
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
Create logic to post DM to user on slack when user id is provided | import os
import json
from flask import Flask
from flask_restful import Resource, Api, reqparse
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
token = os.environ.get('SLACK_KEY')
sc = SlackClient(token)
print sc.api_call('api.test')
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# expect user_id and message data from the client
parser = reqparse.RequestParser()
parser.add_argument('user_id')
parser.add_argument('visitor_name')
# assign data from request to variables
args = parser.parse_args()
user_id = args.get('user_id')
visitor_name = args.get('visitor_name')
if visitor_name:
message = 'You have a visitor called {} at the gate.'.format(visitor_name)
else:
message = 'Hi! You have a visitor waiting for you.'
# returns a string - to be converted to dict later. Then retrieve
# channel ID
string_resp = sc.api_call('im.open', user=user_id)
dict_resp = json.loads(string_resp)
channelID = dict_resp.get('channel').get('id')
abc = sc.api_call(
'chat.postMessage',
as_user='true:',
channel=channelID,
text=message
)
return {'message': 'Notification sent'}, 200
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
| <commit_before>from flask import Flask
from flask_restful import Resource, Api
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# send dm to user in the request info
pass
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
<commit_msg>Create logic to post DM to user on slack when user id is provided<commit_after> | import os
import json
from flask import Flask
from flask_restful import Resource, Api, reqparse
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
token = os.environ.get('SLACK_KEY')
sc = SlackClient(token)
print sc.api_call('api.test')
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# expect user_id and message data from the client
parser = reqparse.RequestParser()
parser.add_argument('user_id')
parser.add_argument('visitor_name')
# assign data from request to variables
args = parser.parse_args()
user_id = args.get('user_id')
visitor_name = args.get('visitor_name')
if visitor_name:
message = 'You have a visitor called {} at the gate.'.format(visitor_name)
else:
message = 'Hi! You have a visitor waiting for you.'
# returns a string - to be converted to dict later. Then retrieve
# channel ID
string_resp = sc.api_call('im.open', user=user_id)
dict_resp = json.loads(string_resp)
channelID = dict_resp.get('channel').get('id')
abc = sc.api_call(
'chat.postMessage',
as_user='true:',
channel=channelID,
text=message
)
return {'message': 'Notification sent'}, 200
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
| from flask import Flask
from flask_restful import Resource, Api
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# send dm to user in the request info
pass
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
Create logic to post DM to user on slack when user id is providedimport os
import json
from flask import Flask
from flask_restful import Resource, Api, reqparse
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
token = os.environ.get('SLACK_KEY')
sc = SlackClient(token)
print sc.api_call('api.test')
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# expect user_id and message data from the client
parser = reqparse.RequestParser()
parser.add_argument('user_id')
parser.add_argument('visitor_name')
# assign data from request to variables
args = parser.parse_args()
user_id = args.get('user_id')
visitor_name = args.get('visitor_name')
if visitor_name:
message = 'You have a visitor called {} at the gate.'.format(visitor_name)
else:
message = 'Hi! You have a visitor waiting for you.'
# returns a string - to be converted to dict later. Then retrieve
# channel ID
string_resp = sc.api_call('im.open', user=user_id)
dict_resp = json.loads(string_resp)
channelID = dict_resp.get('channel').get('id')
abc = sc.api_call(
'chat.postMessage',
as_user='true:',
channel=channelID,
text=message
)
return {'message': 'Notification sent'}, 200
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
| <commit_before>from flask import Flask
from flask_restful import Resource, Api
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# send dm to user in the request info
pass
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
<commit_msg>Create logic to post DM to user on slack when user id is provided<commit_after>import os
import json
from flask import Flask
from flask_restful import Resource, Api, reqparse
from slackclient import SlackClient
app = Flask(__name__)
api = Api(app)
token = os.environ.get('SLACK_KEY')
sc = SlackClient(token)
print sc.api_call('api.test')
class RealName(Resource):
def get(self):
# return real_name from user id info from slack
pass
api.add_resource(RealName, '/names')
class PostDM(Resource):
def post(self):
# expect user_id and message data from the client
parser = reqparse.RequestParser()
parser.add_argument('user_id')
parser.add_argument('visitor_name')
# assign data from request to variables
args = parser.parse_args()
user_id = args.get('user_id')
visitor_name = args.get('visitor_name')
if visitor_name:
message = 'You have a visitor called {} at the gate.'.format(visitor_name)
else:
message = 'Hi! You have a visitor waiting for you.'
# returns a string - to be converted to dict later. Then retrieve
# channel ID
string_resp = sc.api_call('im.open', user=user_id)
dict_resp = json.loads(string_resp)
channelID = dict_resp.get('channel').get('id')
abc = sc.api_call(
'chat.postMessage',
as_user='true:',
channel=channelID,
text=message
)
return {'message': 'Notification sent'}, 200
api.add_resource(PostDM, '/send')
if __name__ == '__main__':
app.run(debug=True)
|
a8c8781373e1501ed8a628004904acc465b80dad | rep.py | rep.py | """
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input()
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
| """
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input().lstrip()
if line:
if line[0] == ')':
if line[0:4].upper() == ')OFF':
apl_exit("Bye bye")
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
| Add recognition of )OFF to mean exit gracefully | Add recognition of )OFF to mean exit gracefully
| Python | apache-2.0 | NewForester/apl-py,NewForester/apl-py | """
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input()
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
Add recognition of )OFF to mean exit gracefully | """
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input().lstrip()
if line:
if line[0] == ')':
if line[0:4].upper() == ')OFF':
apl_exit("Bye bye")
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
| <commit_before>"""
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input()
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
<commit_msg>Add recognition of )OFF to mean exit gracefully<commit_after> | """
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input().lstrip()
if line:
if line[0] == ')':
if line[0:4].upper() == ')OFF':
apl_exit("Bye bye")
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
| """
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input()
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
Add recognition of )OFF to mean exit gracefully"""
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input().lstrip()
if line:
if line[0] == ')':
if line[0:4].upper() == ')OFF':
apl_exit("Bye bye")
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
| <commit_before>"""
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input()
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
<commit_msg>Add recognition of )OFF to mean exit gracefully<commit_after>"""
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop.
"""
import sys
def read_evaluate_print (prompt):
"""
Read input, echo input
"""
try:
while True:
print(end=prompt)
line = input().lstrip()
if line:
if line[0] == ')':
if line[0:4].upper() == ')OFF':
apl_exit("Bye bye")
print('⎕', line)
except EOFError:
apl_exit(None)
def apl_quit ():
"""
Quit without clean up
"""
print ()
sys.exit(0)
def apl_exit (message):
"""
Clean up and quit
"""
if message is None:
print ()
else:
print (message)
sys.exit(0)
# EOF
|
3f9d68c8b1719047de29e41bd673f3b6926a81df | run.py | run.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
'configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
' configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
| Add missing space for exception message. | Add missing space for exception message.
| Python | mit | CAPU-ENG/CAPUHome-API,huxuan/CAPUHome-API | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
'configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
Add missing space for exception message. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
' configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
'configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
<commit_msg>Add missing space for exception message.<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
' configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
'configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
Add missing space for exception message.#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
' configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
'configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
<commit_msg>Add missing space for exception message.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: run.py
Author: huxuan <i(at)huxuan.org>
Description: Run script for app.
"""
import os.path
if not os.path.isfile('config.py'):
raise Exception('Please copy `config.sample.py` to `config.py` with proper'
' configuration to make it work.')
from app import app
def main():
""" Main function for run script. """
app.run()
if __name__ == '__main__':
main()
|
5af2464aa0a97bbcbce71342771e4fa3d86d97ea | run.py | run.py | from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("msgs.txt", "a+") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
| from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("input.txt", "w") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
| Update flask app to be compatible with the emulator script | Update flask app to be compatible with the emulator script
| Python | mit | sagnew/NESMS,sagnew/NESMS | from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("msgs.txt", "a+") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
Update flask app to be compatible with the emulator script | from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("input.txt", "w") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
| <commit_before>from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("msgs.txt", "a+") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
<commit_msg>Update flask app to be compatible with the emulator script<commit_after> | from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("input.txt", "w") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
| from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("msgs.txt", "a+") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
Update flask app to be compatible with the emulator scriptfrom flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("input.txt", "w") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
| <commit_before>from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("msgs.txt", "a+") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
<commit_msg>Update flask app to be compatible with the emulator script<commit_after>from flask import Flask, request, redirect
import twilio.twiml
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
#resp = twilio.twiml.Response()
#resp.message("yo homie im playing nes")
print request.form['Body']
print request.form['From']
with open("input.txt", "w") as f:
f.write(request.form['From'] + ":" + request.form['Body']+"\n")
#return str(resp)
return 'recieved'
if __name__ == "__main__":
app.run(host="0.0.0.0",debug=True)
|
eea9655d6b92c9bfd0276b1173010dad9fa54fa5 | api_tests/licenses/views/test_license_detail.py | api_tests/licenses/views/test_license_detail.py | from nose.tools import * # flake8: noqa
import functools
from tests.base import ApiTestCase
from osf.models.licenses import NodeLicense
from api.base.settings.defaults import API_BASE
class TestLicenseDetail(ApiTestCase):
def setUp(self):
super(TestLicenseDetail, self).setUp()
self.license = NodeLicense.find()[0]
self.url = '/{}licenses/{}/'.format(API_BASE, self.license._id)
self.res = self.app.get(self.url)
self.data = self.res.json['data']
def test_license_detail_success(self):
assert_equal(self.res.status_code, 200)
assert_equal(self.res.content_type, 'application/vnd.api+json')
def test_license_top_level(self):
assert_equal(self.data['type'], 'licenses')
assert_equal(self.data['id'], self.license._id)
def test_license_name(self):
assert_equal(self.data['attributes']['name'], self.license.name)
def test_license_text(self):
assert_equal(self.data['attributes']['text'], self.license.text)
| import pytest
import functools
from api.base.settings.defaults import API_BASE
from osf.models.licenses import NodeLicense
@pytest.mark.django_db
class TestLicenseDetail:
@pytest.fixture()
def license(self):
return NodeLicense.find()[0]
@pytest.fixture()
def url_license(self, license):
return '/{}licenses/{}/'.format(API_BASE, license._id)
@pytest.fixture()
def res_license(self, app, url_license):
return app.get(url_license)
@pytest.fixture()
def data_license(self, res_license):
return res_license.json['data']
def test_license_detail(self, license, res_license, data_license):
#test_license_detail_success(self, res_license):
assert res_license.status_code == 200
assert res_license.content_type == 'application/vnd.api+json'
#test_license_top_level(self, license, data_license):
assert data_license['type'] == 'licenses'
assert data_license['id'] == license._id
#test_license_name(self, data_license, license):
assert data_license['attributes']['name'] == license.name
#test_license_text(self, data_license, license):
assert data_license['attributes']['text'] == license.text
| Convert license detail to pytest | Convert license detail to pytest
| Python | apache-2.0 | caneruguz/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,caneruguz/osf.io,caseyrollins/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,felliott/osf.io,chrisseto/osf.io,mattclark/osf.io,crcresearch/osf.io,felliott/osf.io,binoculars/osf.io,icereval/osf.io,adlius/osf.io,TomBaxter/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,laurenrevere/osf.io,laurenrevere/osf.io,saradbowman/osf.io,leb2dg/osf.io,TomBaxter/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,erinspace/osf.io,mfraezz/osf.io,binoculars/osf.io,Johnetordoff/osf.io,adlius/osf.io,caseyrollins/osf.io,chennan47/osf.io,aaxelb/osf.io,adlius/osf.io,caseyrollins/osf.io,mfraezz/osf.io,aaxelb/osf.io,TomBaxter/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,caneruguz/osf.io,baylee-d/osf.io,chrisseto/osf.io,sloria/osf.io,chrisseto/osf.io,binoculars/osf.io,aaxelb/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,erinspace/osf.io,pattisdr/osf.io,caneruguz/osf.io,chennan47/osf.io,Johnetordoff/osf.io,mattclark/osf.io,crcresearch/osf.io,cslzchen/osf.io,felliott/osf.io,saradbowman/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,chrisseto/osf.io,mattclark/osf.io,cslzchen/osf.io,leb2dg/osf.io,sloria/osf.io,crcresearch/osf.io,chennan47/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,erinspace/osf.io,mfraezz/osf.io,baylee-d/osf.io,icereval/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,leb2dg/osf.io | from nose.tools import * # flake8: noqa
import functools
from tests.base import ApiTestCase
from osf.models.licenses import NodeLicense
from api.base.settings.defaults import API_BASE
class TestLicenseDetail(ApiTestCase):
def setUp(self):
super(TestLicenseDetail, self).setUp()
self.license = NodeLicense.find()[0]
self.url = '/{}licenses/{}/'.format(API_BASE, self.license._id)
self.res = self.app.get(self.url)
self.data = self.res.json['data']
def test_license_detail_success(self):
assert_equal(self.res.status_code, 200)
assert_equal(self.res.content_type, 'application/vnd.api+json')
def test_license_top_level(self):
assert_equal(self.data['type'], 'licenses')
assert_equal(self.data['id'], self.license._id)
def test_license_name(self):
assert_equal(self.data['attributes']['name'], self.license.name)
def test_license_text(self):
assert_equal(self.data['attributes']['text'], self.license.text)
Convert license detail to pytest | import pytest
import functools
from api.base.settings.defaults import API_BASE
from osf.models.licenses import NodeLicense
@pytest.mark.django_db
class TestLicenseDetail:
@pytest.fixture()
def license(self):
return NodeLicense.find()[0]
@pytest.fixture()
def url_license(self, license):
return '/{}licenses/{}/'.format(API_BASE, license._id)
@pytest.fixture()
def res_license(self, app, url_license):
return app.get(url_license)
@pytest.fixture()
def data_license(self, res_license):
return res_license.json['data']
def test_license_detail(self, license, res_license, data_license):
#test_license_detail_success(self, res_license):
assert res_license.status_code == 200
assert res_license.content_type == 'application/vnd.api+json'
#test_license_top_level(self, license, data_license):
assert data_license['type'] == 'licenses'
assert data_license['id'] == license._id
#test_license_name(self, data_license, license):
assert data_license['attributes']['name'] == license.name
#test_license_text(self, data_license, license):
assert data_license['attributes']['text'] == license.text
| <commit_before>from nose.tools import * # flake8: noqa
import functools
from tests.base import ApiTestCase
from osf.models.licenses import NodeLicense
from api.base.settings.defaults import API_BASE
class TestLicenseDetail(ApiTestCase):
def setUp(self):
super(TestLicenseDetail, self).setUp()
self.license = NodeLicense.find()[0]
self.url = '/{}licenses/{}/'.format(API_BASE, self.license._id)
self.res = self.app.get(self.url)
self.data = self.res.json['data']
def test_license_detail_success(self):
assert_equal(self.res.status_code, 200)
assert_equal(self.res.content_type, 'application/vnd.api+json')
def test_license_top_level(self):
assert_equal(self.data['type'], 'licenses')
assert_equal(self.data['id'], self.license._id)
def test_license_name(self):
assert_equal(self.data['attributes']['name'], self.license.name)
def test_license_text(self):
assert_equal(self.data['attributes']['text'], self.license.text)
<commit_msg>Convert license detail to pytest<commit_after> | import pytest
import functools
from api.base.settings.defaults import API_BASE
from osf.models.licenses import NodeLicense
@pytest.mark.django_db
class TestLicenseDetail:
@pytest.fixture()
def license(self):
return NodeLicense.find()[0]
@pytest.fixture()
def url_license(self, license):
return '/{}licenses/{}/'.format(API_BASE, license._id)
@pytest.fixture()
def res_license(self, app, url_license):
return app.get(url_license)
@pytest.fixture()
def data_license(self, res_license):
return res_license.json['data']
def test_license_detail(self, license, res_license, data_license):
#test_license_detail_success(self, res_license):
assert res_license.status_code == 200
assert res_license.content_type == 'application/vnd.api+json'
#test_license_top_level(self, license, data_license):
assert data_license['type'] == 'licenses'
assert data_license['id'] == license._id
#test_license_name(self, data_license, license):
assert data_license['attributes']['name'] == license.name
#test_license_text(self, data_license, license):
assert data_license['attributes']['text'] == license.text
| from nose.tools import * # flake8: noqa
import functools
from tests.base import ApiTestCase
from osf.models.licenses import NodeLicense
from api.base.settings.defaults import API_BASE
class TestLicenseDetail(ApiTestCase):
def setUp(self):
super(TestLicenseDetail, self).setUp()
self.license = NodeLicense.find()[0]
self.url = '/{}licenses/{}/'.format(API_BASE, self.license._id)
self.res = self.app.get(self.url)
self.data = self.res.json['data']
def test_license_detail_success(self):
assert_equal(self.res.status_code, 200)
assert_equal(self.res.content_type, 'application/vnd.api+json')
def test_license_top_level(self):
assert_equal(self.data['type'], 'licenses')
assert_equal(self.data['id'], self.license._id)
def test_license_name(self):
assert_equal(self.data['attributes']['name'], self.license.name)
def test_license_text(self):
assert_equal(self.data['attributes']['text'], self.license.text)
Convert license detail to pytestimport pytest
import functools
from api.base.settings.defaults import API_BASE
from osf.models.licenses import NodeLicense
@pytest.mark.django_db
class TestLicenseDetail:
@pytest.fixture()
def license(self):
return NodeLicense.find()[0]
@pytest.fixture()
def url_license(self, license):
return '/{}licenses/{}/'.format(API_BASE, license._id)
@pytest.fixture()
def res_license(self, app, url_license):
return app.get(url_license)
@pytest.fixture()
def data_license(self, res_license):
return res_license.json['data']
def test_license_detail(self, license, res_license, data_license):
#test_license_detail_success(self, res_license):
assert res_license.status_code == 200
assert res_license.content_type == 'application/vnd.api+json'
#test_license_top_level(self, license, data_license):
assert data_license['type'] == 'licenses'
assert data_license['id'] == license._id
#test_license_name(self, data_license, license):
assert data_license['attributes']['name'] == license.name
#test_license_text(self, data_license, license):
assert data_license['attributes']['text'] == license.text
| <commit_before>from nose.tools import * # flake8: noqa
import functools
from tests.base import ApiTestCase
from osf.models.licenses import NodeLicense
from api.base.settings.defaults import API_BASE
class TestLicenseDetail(ApiTestCase):
def setUp(self):
super(TestLicenseDetail, self).setUp()
self.license = NodeLicense.find()[0]
self.url = '/{}licenses/{}/'.format(API_BASE, self.license._id)
self.res = self.app.get(self.url)
self.data = self.res.json['data']
def test_license_detail_success(self):
assert_equal(self.res.status_code, 200)
assert_equal(self.res.content_type, 'application/vnd.api+json')
def test_license_top_level(self):
assert_equal(self.data['type'], 'licenses')
assert_equal(self.data['id'], self.license._id)
def test_license_name(self):
assert_equal(self.data['attributes']['name'], self.license.name)
def test_license_text(self):
assert_equal(self.data['attributes']['text'], self.license.text)
<commit_msg>Convert license detail to pytest<commit_after>import pytest
import functools
from api.base.settings.defaults import API_BASE
from osf.models.licenses import NodeLicense
@pytest.mark.django_db
class TestLicenseDetail:
@pytest.fixture()
def license(self):
return NodeLicense.find()[0]
@pytest.fixture()
def url_license(self, license):
return '/{}licenses/{}/'.format(API_BASE, license._id)
@pytest.fixture()
def res_license(self, app, url_license):
return app.get(url_license)
@pytest.fixture()
def data_license(self, res_license):
return res_license.json['data']
def test_license_detail(self, license, res_license, data_license):
#test_license_detail_success(self, res_license):
assert res_license.status_code == 200
assert res_license.content_type == 'application/vnd.api+json'
#test_license_top_level(self, license, data_license):
assert data_license['type'] == 'licenses'
assert data_license['id'] == license._id
#test_license_name(self, data_license, license):
assert data_license['attributes']['name'] == license.name
#test_license_text(self, data_license, license):
assert data_license['attributes']['text'] == license.text
|
6ec8f4618bd3e6140780b5acbab719390271fd2f | IMU_program/PythonServer.py | IMU_program/PythonServer.py | import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = ''
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
| import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = 'localhost'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
| Change python code to only listen on localhost | Change python code to only listen on localhost
| Python | apache-2.0 | dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo | import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = ''
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
Change python code to only listen on localhost | import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = 'localhost'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
| <commit_before>import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = ''
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
<commit_msg>Change python code to only listen on localhost<commit_after> | import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = 'localhost'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
| import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = ''
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
Change python code to only listen on localhostimport serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = 'localhost'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
| <commit_before>import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = ''
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
<commit_msg>Change python code to only listen on localhost<commit_after>import serial.tools.list_ports
import serial
import socket
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
PORT = 4242
HOST = 'localhost'
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
while True:
connection, adress = server_socket.accept()
print("Client connected")
while True:
try:
incoming = arduino.readline()
connection.send(incoming)
except:
print("Client disconnected")
break
|
bd4ee91c964ce7fb506b722d4d93a8af019d4e7c | test/test_future_and_futures.py | test/test_future_and_futures.py | import imp
import os
import sys
from django.test import TestCase
from kolibri import dist as kolibri_dist
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
| import imp
import os
import sys
# Import from kolibri first to ensure Kolibri's monkey patches are applied.
from kolibri import dist as kolibri_dist # noreorder
from django.test import TestCase # noreorder
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
| Fix import order in tests. | Fix import order in tests.
| Python | mit | learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri | import imp
import os
import sys
from django.test import TestCase
from kolibri import dist as kolibri_dist
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
Fix import order in tests. | import imp
import os
import sys
# Import from kolibri first to ensure Kolibri's monkey patches are applied.
from kolibri import dist as kolibri_dist # noreorder
from django.test import TestCase # noreorder
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
| <commit_before>import imp
import os
import sys
from django.test import TestCase
from kolibri import dist as kolibri_dist
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
<commit_msg>Fix import order in tests.<commit_after> | import imp
import os
import sys
# Import from kolibri first to ensure Kolibri's monkey patches are applied.
from kolibri import dist as kolibri_dist # noreorder
from django.test import TestCase # noreorder
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
| import imp
import os
import sys
from django.test import TestCase
from kolibri import dist as kolibri_dist
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
Fix import order in tests.import imp
import os
import sys
# Import from kolibri first to ensure Kolibri's monkey patches are applied.
from kolibri import dist as kolibri_dist # noreorder
from django.test import TestCase # noreorder
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
| <commit_before>import imp
import os
import sys
from django.test import TestCase
from kolibri import dist as kolibri_dist
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
<commit_msg>Fix import order in tests.<commit_after>import imp
import os
import sys
# Import from kolibri first to ensure Kolibri's monkey patches are applied.
from kolibri import dist as kolibri_dist # noreorder
from django.test import TestCase # noreorder
dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__))
class FutureAndFuturesTestCase(TestCase):
def test_import_concurrent_py3(self):
import concurrent
if sys.version_info[0] == 3:
# Python 3 is supposed to import its builtin package `concurrent`
# instead of being inside kolibri/dist/py2only or kolibri/dist
concurrent_parent_path = os.path.realpath(
os.path.dirname(os.path.dirname(concurrent.__file__))
)
self.assertNotEqual(dist_dir, concurrent_parent_path)
self.assertNotEqual(
os.path.join(dist_dir, "py2only"), concurrent_parent_path
)
def test_import_future_py2(self):
from future.standard_library import TOP_LEVEL_MODULES
if sys.version_info[0] == 2:
for module_name in TOP_LEVEL_MODULES:
if "test" in module_name:
continue
module_parent_path = os.path.realpath(
os.path.dirname(imp.find_module(module_name)[1])
)
# future's standard libraries such as `html` should not be found
# at the same level as kolibri/dist; otherwise, python3 will try to
# import them from kolibri/dist instead of its builtin packages
self.assertNotEqual(dist_dir, module_parent_path)
|
ad7485b9500ebc75e9c741641d3258a40fffe43b | myDevices/plugins/analog.py | myDevices/plugins/analog.py | """
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc_name):
"""Initializes the analog input.
Arguments:
adc_name: Name of analog-to-digital converter plugin in the format 'plugin_name:section'
"""
self.adc_name = adc_name
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
| """
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info, debug
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc):
"""Initializes the analog input.
Arguments:
adc: Analog-to-digital converter plugin ID in the format 'plugin_name:section', e.g. 'cayenne-mcp3xxx:MCP'
"""
self.adc_name = adc
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
try:
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
except ValueError as e:
debug(e)
value = None
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
| Modify AnalogInput initialization, add exception handling. | Modify AnalogInput initialization, add exception handling.
| Python | mit | myDevicesIoT/Cayenne-Agent,myDevicesIoT/Cayenne-Agent | """
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc_name):
"""Initializes the analog input.
Arguments:
adc_name: Name of analog-to-digital converter plugin in the format 'plugin_name:section'
"""
self.adc_name = adc_name
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
Modify AnalogInput initialization, add exception handling. | """
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info, debug
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc):
"""Initializes the analog input.
Arguments:
adc: Analog-to-digital converter plugin ID in the format 'plugin_name:section', e.g. 'cayenne-mcp3xxx:MCP'
"""
self.adc_name = adc
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
try:
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
except ValueError as e:
debug(e)
value = None
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
| <commit_before>"""
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc_name):
"""Initializes the analog input.
Arguments:
adc_name: Name of analog-to-digital converter plugin in the format 'plugin_name:section'
"""
self.adc_name = adc_name
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
<commit_msg>Modify AnalogInput initialization, add exception handling.<commit_after> | """
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info, debug
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc):
"""Initializes the analog input.
Arguments:
adc: Analog-to-digital converter plugin ID in the format 'plugin_name:section', e.g. 'cayenne-mcp3xxx:MCP'
"""
self.adc_name = adc
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
try:
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
except ValueError as e:
debug(e)
value = None
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
| """
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc_name):
"""Initializes the analog input.
Arguments:
adc_name: Name of analog-to-digital converter plugin in the format 'plugin_name:section'
"""
self.adc_name = adc_name
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
Modify AnalogInput initialization, add exception handling."""
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info, debug
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc):
"""Initializes the analog input.
Arguments:
adc: Analog-to-digital converter plugin ID in the format 'plugin_name:section', e.g. 'cayenne-mcp3xxx:MCP'
"""
self.adc_name = adc
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
try:
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
except ValueError as e:
debug(e)
value = None
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
| <commit_before>"""
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc_name):
"""Initializes the analog input.
Arguments:
adc_name: Name of analog-to-digital converter plugin in the format 'plugin_name:section'
"""
self.adc_name = adc_name
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
<commit_msg>Modify AnalogInput initialization, add exception handling.<commit_after>"""
This module provides classes for interfacing with analog plugins.
"""
import json
from myDevices.plugins.manager import PluginManager
from myDevices.utils.logger import info, debug
class AnalogInput():
"""Reads data from an analog input."""
def __init__(self, adc):
"""Initializes the analog input.
Arguments:
adc: Analog-to-digital converter plugin ID in the format 'plugin_name:section', e.g. 'cayenne-mcp3xxx:MCP'
"""
self.adc_name = adc
self.adc = None
self.read_args = {}
self.pluginManager = PluginManager()
self.set_adc()
def set_adc(self):
"""Sets the ADC plugin."""
if not self.adc:
self.adc = self.pluginManager.get_plugin_by_id(self.adc_name)
self.read_args = json.loads(self.adc['read_args'])
def read_value(self, channel, data_type=None):
"""Read the data value on the specified channel."""
self.set_adc()
try:
value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args)
except ValueError as e:
debug(e)
value = None
return value
def read_float(self, channel):
"""Read the float value on the specified channel."""
return self.read_value(channel, 'float')
def read_volt(self, channel):
"""Read the voltage on the specified channel."""
return self.read_value(channel, 'volt')
|
26f8c6d4cf51c1f479edc512fa8097ad4b8e1059 | puppet/modules/commonservices-apache/files/index.py | puppet/modules/commonservices-apache/files/index.py | #!/usr/bin/python
import os
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = target.replace('%7C', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
| #!/usr/bin/python
import os
from urllib import unquote
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = unquote(target)
target = target.replace('|', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
| Fix URL fragment management on Firefox | Fix URL fragment management on Firefox
Close Bug: 13
Change-Id: If3e3182e670b4c498043a58f2b5a82cb87560722
| Python | apache-2.0 | enovance/software-factory,invenfantasy/software-factory,invenfantasy/software-factory,enovance/software-factory,enovance/software-factory,invenfantasy/software-factory,invenfantasy/software-factory,invenfantasy/software-factory,enovance/software-factory,enovance/software-factory | #!/usr/bin/python
import os
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = target.replace('%7C', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
Fix URL fragment management on Firefox
Close Bug: 13
Change-Id: If3e3182e670b4c498043a58f2b5a82cb87560722 | #!/usr/bin/python
import os
from urllib import unquote
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = unquote(target)
target = target.replace('|', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
| <commit_before>#!/usr/bin/python
import os
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = target.replace('%7C', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
<commit_msg>Fix URL fragment management on Firefox
Close Bug: 13
Change-Id: If3e3182e670b4c498043a58f2b5a82cb87560722<commit_after> | #!/usr/bin/python
import os
from urllib import unquote
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = unquote(target)
target = target.replace('|', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
| #!/usr/bin/python
import os
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = target.replace('%7C', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
Fix URL fragment management on Firefox
Close Bug: 13
Change-Id: If3e3182e670b4c498043a58f2b5a82cb87560722#!/usr/bin/python
import os
from urllib import unquote
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = unquote(target)
target = target.replace('|', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
| <commit_before>#!/usr/bin/python
import os
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = target.replace('%7C', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
<commit_msg>Fix URL fragment management on Firefox
Close Bug: 13
Change-Id: If3e3182e670b4c498043a58f2b5a82cb87560722<commit_after>#!/usr/bin/python
import os
from urllib import unquote
from string import Template
print "Content-Type: text/html"
print
tmpl = Template(file('index.html.tmpl').read())
target = os.environ['REQUEST_URI']
if target.startswith('/_'):
target = '/' + target.lstrip('/').lstrip('_')
target = unquote(target)
target = target.replace('|', '#', 1)
else:
target = '/r/'
content = tmpl.substitute(target_url=target)
print content
|
d012a3de5d294cdbaa4dbc8141fdb6ad2af31893 | pystruct/tests/test_learners/test_frankwolfe_svm.py | pystruct/tests/test_learners/test_frankwolfe_svm.py |
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.4,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
|
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.5,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
| TEST use same amount of noise for frank wolfe test as for other test. Works now that C is scaled correctly :) | TEST use same amount of noise for frank wolfe test as for other test. Works now that C is scaled correctly :)
| Python | bsd-2-clause | pystruct/pystruct,pystruct/pystruct,amueller/pystruct,massmutual/pystruct,massmutual/pystruct,amueller/pystruct,d-mittal/pystruct,wattlebird/pystruct,wattlebird/pystruct,d-mittal/pystruct |
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.4,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
TEST use same amount of noise for frank wolfe test as for other test. Works now that C is scaled correctly :) |
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.5,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
| <commit_before>
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.4,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
<commit_msg>TEST use same amount of noise for frank wolfe test as for other test. Works now that C is scaled correctly :)<commit_after> |
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.5,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
|
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.4,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
TEST use same amount of noise for frank wolfe test as for other test. Works now that C is scaled correctly :)
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.5,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
| <commit_before>
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.4,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
<commit_msg>TEST use same amount of noise for frank wolfe test as for other test. Works now that C is scaled correctly :)<commit_after>
from numpy.testing import assert_array_equal
from pystruct.models import GridCRF
from pystruct.datasets import generate_blocks_multinomial
from pystruct.learners import FrankWolfeSSVM
def test_multinomial_blocks_frankwolfe():
X, Y = generate_blocks_multinomial(n_samples=50, noise=0.5,
seed=0)
crf = GridCRF(inference_method='qpbo')
clf = FrankWolfeSSVM(model=crf, C=1, line_search=True,
batch_mode=False, dual_check_every=500)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(Y, Y_pred)
|
7a552161eab19d24b7b221635e51a915adff0166 | templater.py | templater.py | #!/usr/bin/python
import string
if __name__ == "__main__":
import sys
template_file = sys.argv[1]
with open(template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in sys.argv[2:]:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
| #!/usr/bin/python
import string
import os
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--template", dest="template_file",
help="Input template file")
(options, args) = parser.parse_args()
if not os.path.isfile(options.template_file):
sys.stderr.write("Invalid input template file")
exit(1)
with open(options.template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in args:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
| Use OptionParser instead of simple sys.argv. | Use OptionParser instead of simple sys.argv.
| Python | mit | elecro/strep | #!/usr/bin/python
import string
if __name__ == "__main__":
import sys
template_file = sys.argv[1]
with open(template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in sys.argv[2:]:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
Use OptionParser instead of simple sys.argv. | #!/usr/bin/python
import string
import os
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--template", dest="template_file",
help="Input template file")
(options, args) = parser.parse_args()
if not os.path.isfile(options.template_file):
sys.stderr.write("Invalid input template file")
exit(1)
with open(options.template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in args:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
| <commit_before>#!/usr/bin/python
import string
if __name__ == "__main__":
import sys
template_file = sys.argv[1]
with open(template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in sys.argv[2:]:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
<commit_msg>Use OptionParser instead of simple sys.argv.<commit_after> | #!/usr/bin/python
import string
import os
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--template", dest="template_file",
help="Input template file")
(options, args) = parser.parse_args()
if not os.path.isfile(options.template_file):
sys.stderr.write("Invalid input template file")
exit(1)
with open(options.template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in args:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
| #!/usr/bin/python
import string
if __name__ == "__main__":
import sys
template_file = sys.argv[1]
with open(template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in sys.argv[2:]:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
Use OptionParser instead of simple sys.argv.#!/usr/bin/python
import string
import os
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--template", dest="template_file",
help="Input template file")
(options, args) = parser.parse_args()
if not os.path.isfile(options.template_file):
sys.stderr.write("Invalid input template file")
exit(1)
with open(options.template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in args:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
| <commit_before>#!/usr/bin/python
import string
if __name__ == "__main__":
import sys
template_file = sys.argv[1]
with open(template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in sys.argv[2:]:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
<commit_msg>Use OptionParser instead of simple sys.argv.<commit_after>#!/usr/bin/python
import string
import os
if __name__ == "__main__":
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--template", dest="template_file",
help="Input template file")
(options, args) = parser.parse_args()
if not os.path.isfile(options.template_file):
sys.stderr.write("Invalid input template file")
exit(1)
with open(options.template_file) as f:
data = f.read()
template = string.Template(data)
template_mapping = {}
for item in args:
# item is in the following form: KEY=VALUE
print("-> Current replacer %s" % item)
key, value = item.split("=", 1)
template_mapping[key] = value
print("-> Using mapping: %s" % str(template_mapping))
result = template.substitute(template_mapping)
print("-----\n")
print(result)
|
46f14b9681d011b78aabdf0bd9e4e86a92ff8023 | packages/python-windows/setup.py | packages/python-windows/setup.py | #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.pyd"]})
| #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.dll", "*.pyd"]})
| Fix the python-windows installer generator by making it include the .dll files in the installer. That list originally consisted only of "*.dll". When the build system was modified to generate .pyd files for the binary modules, it was changed to "*.pyd". The Subversion libraries and the dependencies are still .dll files, though, so "*.dll" needs to be brought back. | Fix the python-windows installer generator by making it include the .dll
files in the installer. That list originally consisted only of "*.dll".
When the build system was modified to generate .pyd files for the binary
modules, it was changed to "*.pyd". The Subversion libraries and the
dependencies are still .dll files, though, so "*.dll" needs to be brought
back.
* packages/python-windows/setup.py: Add *.dll to the list of package data.
Patch by: <DXDragon@yandex.ru>
| Python | apache-2.0 | jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion | #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.pyd"]})
Fix the python-windows installer generator by making it include the .dll
files in the installer. That list originally consisted only of "*.dll".
When the build system was modified to generate .pyd files for the binary
modules, it was changed to "*.pyd". The Subversion libraries and the
dependencies are still .dll files, though, so "*.dll" needs to be brought
back.
* packages/python-windows/setup.py: Add *.dll to the list of package data.
Patch by: <DXDragon@yandex.ru> | #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.dll", "*.pyd"]})
| <commit_before>#!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.pyd"]})
<commit_msg>Fix the python-windows installer generator by making it include the .dll
files in the installer. That list originally consisted only of "*.dll".
When the build system was modified to generate .pyd files for the binary
modules, it was changed to "*.pyd". The Subversion libraries and the
dependencies are still .dll files, though, so "*.dll" needs to be brought
back.
* packages/python-windows/setup.py: Add *.dll to the list of package data.
Patch by: <DXDragon@yandex.ru><commit_after> | #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.dll", "*.pyd"]})
| #!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.pyd"]})
Fix the python-windows installer generator by making it include the .dll
files in the installer. That list originally consisted only of "*.dll".
When the build system was modified to generate .pyd files for the binary
modules, it was changed to "*.pyd". The Subversion libraries and the
dependencies are still .dll files, though, so "*.dll" needs to be brought
back.
* packages/python-windows/setup.py: Add *.dll to the list of package data.
Patch by: <DXDragon@yandex.ru>#!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.dll", "*.pyd"]})
| <commit_before>#!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.pyd"]})
<commit_msg>Fix the python-windows installer generator by making it include the .dll
files in the installer. That list originally consisted only of "*.dll".
When the build system was modified to generate .pyd files for the binary
modules, it was changed to "*.pyd". The Subversion libraries and the
dependencies are still .dll files, though, so "*.dll" needs to be brought
back.
* packages/python-windows/setup.py: Add *.dll to the list of package data.
Patch by: <DXDragon@yandex.ru><commit_after>#!/usr/bin/env python
# ====================================================================
# Copyright (c) 2006 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://subversion.tigris.org/license-1.html.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# This software consists of voluntary contributions made by many
# individuals. For exact contribution history, see the revision
# history and logs, available at http://subversion.tigris.org/.
# ====================================================================
from distutils.core import setup
setup (name = "svn-python",
description = "Subversion Python Bindings",
maintainer = "Subversion Developers <dev@subversion.tigris.org>",
url = "http://subversion.tigris.org",
version = "1.4.0",
packages = ["libsvn", "svn"],
package_data = {"libsvn": ["*.dll", "*.pyd"]})
|
462397443770d55617356bf257b021406367b4c2 | wluopensource/osl_flatpages/models.py | wluopensource/osl_flatpages/models.py | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(max_length=100)
description = models.CharField(max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
| from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
| Allow blank entries for title and description for flatpages | Allow blank entries for title and description for flatpages
| Python | bsd-3-clause | jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(max_length=100)
description = models.CharField(max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
Allow blank entries for title and description for flatpages | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
| <commit_before>from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(max_length=100)
description = models.CharField(max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
<commit_msg>Allow blank entries for title and description for flatpages<commit_after> | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
| from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(max_length=100)
description = models.CharField(max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
Allow blank entries for title and description for flatpagesfrom django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
| <commit_before>from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(max_length=100)
description = models.CharField(max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
<commit_msg>Allow blank entries for title and description for flatpages<commit_after>from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
def __unicode__(self):
return self.page_name
def save(self, force_insert=False, force_update=False):
self.content = markdown.markdown(self.markdown_content)
super(Flatpage, self).save(force_insert, force_update)
|
7bc7bfa84550b4037672cc1168a178cf20f0c548 | pamda/private/curry_spec/make_func_curry_spec.py | pamda/private/curry_spec/make_func_curry_spec.py | from inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
| from inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults or []
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
| Fix make_fun_curry_spec for functions with no defaults | Fix make_fun_curry_spec for functions with no defaults
| Python | mit | jackfirth/pyramda | from inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
Fix make_fun_curry_spec for functions with no defaults | from inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults or []
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
| <commit_before>from inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
<commit_msg>Fix make_fun_curry_spec for functions with no defaults<commit_after> | from inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults or []
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
| from inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
Fix make_fun_curry_spec for functions with no defaultsfrom inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults or []
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
| <commit_before>from inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
<commit_msg>Fix make_fun_curry_spec for functions with no defaults<commit_after>from inspect import getargspec
from .curry_spec import CurrySpec
from ..accepts_varargs import accepts_varargs
class CurrySpecVarargError(ValueError):
def __init__(self, f):
name = f.__name__
message_template = "Cannot curry var-arg or var-kwarg function {0}"
message = message_template.format(name)
super(CurrySpecVarargError, self).__init__(message)
def func_arg_names(f):
return getargspec(f).args
def func_arg_defaults(f):
argspec = getargspec(f)
arg_names = argspec.args
default_arg_values = argspec.defaults or []
num_defaults = len(default_arg_values)
default_arg_names = arg_names[-num_defaults:]
return dict(zip(default_arg_names, default_arg_values))
def make_func_curry_spec(f):
if accepts_varargs(f):
raise CurrySpecVarargError(f)
return CurrySpec(func_arg_names(f), func_arg_defaults(f))
|
cc7893b5a81fc1fc41a1273ee4e89b0fc0f93530 | setup.py | setup.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://github.com/trac-hacks/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
| # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
| Change URL to point to trac-hacks.org | 1.0.0: Change URL to point to trac-hacks.org
| Python | bsd-3-clause | trac-hacks/TicketGuidelinesPlugin | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://github.com/trac-hacks/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
1.0.0: Change URL to point to trac-hacks.org | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
| <commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://github.com/trac-hacks/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
<commit_msg>1.0.0: Change URL to point to trac-hacks.org<commit_after> | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
| # -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://github.com/trac-hacks/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
1.0.0: Change URL to point to trac-hacks.org# -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
| <commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://github.com/trac-hacks/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
<commit_msg>1.0.0: Change URL to point to trac-hacks.org<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2010 Sebastian Krysmanski
# Copyright (C) 2012 Greg Lavallee
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
from setuptools import setup
PACKAGE = 'TicketGuidelinesPlugin'
VERSION = '1.0.0'
setup(
name=PACKAGE,
version=VERSION,
author='Sebastian Krysmanski',
url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin',
description="Adds your ticket guidelines to the ticket view. The "
"guidelines are specified in the wiki pages "
"'TicketGuidelines/NewShort' and "
"'TicketGuidelines/ModifyShort'.",
keywords='trac plugin',
license='Modified BSD',
install_requires=['Trac'],
packages=['ticketguidelines'],
package_data={'ticketguidelines': ['htdocs/*']},
entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE},
)
|
8d4388bed399b27d650a77e93d9ff4da8d7f8a82 | setup.py | setup.py | from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
install_requires=['cffi'],
)
| from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
package_data={'nnpy': ['*.h']},
install_requires=['cffi'],
)
| Install the nanomsg.h file, we need it. | Install the nanomsg.h file, we need it.
| Python | mit | tempbottle/nnpy,nanomsg/nnpy | from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
install_requires=['cffi'],
)
Install the nanomsg.h file, we need it. | from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
package_data={'nnpy': ['*.h']},
install_requires=['cffi'],
)
| <commit_before>from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
install_requires=['cffi'],
)
<commit_msg>Install the nanomsg.h file, we need it.<commit_after> | from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
package_data={'nnpy': ['*.h']},
install_requires=['cffi'],
)
| from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
install_requires=['cffi'],
)
Install the nanomsg.h file, we need it.from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
package_data={'nnpy': ['*.h']},
install_requires=['cffi'],
)
| <commit_before>from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
install_requires=['cffi'],
)
<commit_msg>Install the nanomsg.h file, we need it.<commit_after>from setuptools import setup
import generate
generate.run()
setup(
name='nnpy',
version='0.1',
url='https://github.com/djc/jasinja',
license='MIT',
author='Dirkjan Ochtman',
author_email='dirkjan@ochtman.nl',
description='cffi-based Python bindings for nanomsg',
long_description=open('README.rst').read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
packages=['nnpy'],
package_data={'nnpy': ['*.h']},
install_requires=['cffi'],
)
|
451483d991c5cb0b2c9b9a4879e10e759be0667a | setup.py | setup.py | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| Remove numpy as it's a dependency of Pandas already | Remove numpy as it's a dependency of Pandas already
| Python | mit | datasciencebr/serenata-toolbox | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
Remove numpy as it's a dependency of Pandas already | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| <commit_before>from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
<commit_msg>Remove numpy as it's a dependency of Pandas already<commit_after> | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
Remove numpy as it's a dependency of Pandas alreadyfrom setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| <commit_before>from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
<commit_msg>Remove numpy as it's a dependency of Pandas already<commit_after>from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
|
c9c86da6d25cc4801c428e927b3df4705f850995 | setup.py | setup.py | from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
| from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34', 'futures'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
| Add futures as a dependency. | Add futures as a dependency.
| Python | mit | uber/tchannel-python,Willyham/tchannel-python,uber/tchannel-python,Willyham/tchannel-python | from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
Add futures as a dependency. | from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34', 'futures'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
| <commit_before>from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
<commit_msg>Add futures as a dependency.<commit_after> | from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34', 'futures'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
| from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
Add futures as a dependency.from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34', 'futures'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
| <commit_before>from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
<commit_msg>Add futures as a dependency.<commit_after>from setuptools import find_packages, setup
setup(
name='tchannel',
version='0.1.0+dev0',
author='Aiden Scandella',
author_email='dev@uber.com',
description='Network multiplexing and framing protocol for RPC',
license='MIT',
url='https://github.com/uber/tchannel',
packages=find_packages(),
install_requires=['contextlib2', 'enum34', 'futures'],
entry_points={
'console_scripts': [
'tcurl.py = tchannel.tcurl:main'
]
},
)
|
64918cf64c46ecd0a540902147a1c8cde2937b00 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.4'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.5'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
| Bump the version to 0.1.5. | Bump the version to 0.1.5.
| Python | mit | kunxi/docxgen | #!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.4'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
Bump the version to 0.1.5. | #!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.5'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
| <commit_before>#!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.4'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
<commit_msg>Bump the version to 0.1.5.<commit_after> | #!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.5'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.4'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
Bump the version to 0.1.5.#!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.5'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
| <commit_before>#!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.4'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
<commit_msg>Bump the version to 0.1.5.<commit_after>#!/usr/bin/env python
from setuptools import setup, find_packages
version = '0.1.5'
setup(
name='docxgen',
version=version,
packages=find_packages(),
install_requires=['lxml', 'six'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
description='A library to generate Microsoft Office Word 2007 documents.',
author='Kun Xi',
author_email='kunxi@kunxi.org',
url='http://github.com/kunxi/docxgen',
license='MIT',
)
|
e1d969743ade709e0b14f1c329ad271aa7079fdb | setup.py | setup.py | import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
| import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
license='MIT License',
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
| Add official OSI name in the license metadata | Add official OSI name in the license metadata
This makes it easier for automatic license checkers to verify the license of this package. | Python | mit | EmilStenstrom/conllu | import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
Add official OSI name in the license metadata
This makes it easier for automatic license checkers to verify the license of this package. | import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
license='MIT License',
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
| <commit_before>import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
<commit_msg>Add official OSI name in the license metadata
This makes it easier for automatic license checkers to verify the license of this package.<commit_after> | import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
license='MIT License',
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
| import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
Add official OSI name in the license metadata
This makes it easier for automatic license checkers to verify the license of this package.import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
license='MIT License',
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
| <commit_before>import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
<commit_msg>Add official OSI name in the license metadata
This makes it easier for automatic license checkers to verify the license of this package.<commit_after>import os
from setuptools import setup # type: ignore
VERSION = '4.4.1'
setup(
name='conllu',
packages=["conllu"],
python_requires=">=3.6",
package_data={
"": ["py.typed"]
},
version=VERSION,
license='MIT License',
description='CoNLL-U Parser parses a CoNLL-U formatted string into a nested python dictionary',
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type="text/markdown",
author=u'Emil Stenström',
author_email="emil@emilstenstrom.se",
url='https://github.com/EmilStenstrom/conllu/',
keywords=['conllu', 'conll', 'conll-u', 'parser', 'nlp'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Operating System :: OS Independent",
],
)
|
ff2aabb04003e8f529fc5289a96fe504590191e6 | setup.py | setup.py | from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2==2.10',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
| from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2>=2.10.1,<3',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
| Update deps because of CVE-2019-10906 in Jinja2 < 2.10.1 | Update deps because of CVE-2019-10906 in Jinja2 < 2.10.1
| Python | mit | egnyte/gitlabform,egnyte/gitlabform | from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2==2.10',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
Update deps because of CVE-2019-10906 in Jinja2 < 2.10.1 | from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2>=2.10.1,<3',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
| <commit_before>from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2==2.10',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
<commit_msg>Update deps because of CVE-2019-10906 in Jinja2 < 2.10.1<commit_after> | from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2>=2.10.1,<3',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
| from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2==2.10',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
Update deps because of CVE-2019-10906 in Jinja2 < 2.10.1from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2>=2.10.1,<3',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
| <commit_before>from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2==2.10',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
<commit_msg>Update deps because of CVE-2019-10906 in Jinja2 < 2.10.1<commit_after>from setuptools import setup, find_packages
from pypandoc import convert
def convert_markdown_to_rst(file):
return convert(file, 'rst')
setup(name='gitlabform',
version='1.1.0',
description='Easy configuration as code tool for GitLab using config in plain YAML',
long_description=convert_markdown_to_rst('README.md'),
url='https://github.com/egnyte/gitlabform',
author='Egnyte',
keywords=['gitlab', 'configuration-as-code'],
classifiers=[
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Software Development :: Version Control :: Git",
],
packages=find_packages(),
install_requires=[
'requests>=2.20.0',
'pyyaml>=4.2b1',
'Jinja2>=2.10.1,<3',
],
tests_require=[
'pytest',
],
setup_requires=[
'pypandoc',
],
scripts=[
'bin/gitlabform',
],
)
|
b95bab6acacffc3b59e4d5a57d06f21159742044 | setup.py | setup.py | '''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| '''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
install_requires = ['requests'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| Add requests package as dependency | Add requests package as dependency
The package depends on the requests package, which is not explicitly mentioned in the setup file. Path adds this as requirement to the setup file. | Python | mit | dhhagan/py-openaq,dhhagan/py-openaq | '''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
Add requests package as dependency
The package depends on the requests package, which is not explicitly mentioned in the setup file. Path adds this as requirement to the setup file. | '''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
install_requires = ['requests'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| <commit_before>'''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
<commit_msg>Add requests package as dependency
The package depends on the requests package, which is not explicitly mentioned in the setup file. Path adds this as requirement to the setup file.<commit_after> | '''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
install_requires = ['requests'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| '''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
Add requests package as dependency
The package depends on the requests package, which is not explicitly mentioned in the setup file. Path adds this as requirement to the setup file.'''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
install_requires = ['requests'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| <commit_before>'''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
<commit_msg>Add requests package as dependency
The package depends on the requests package, which is not explicitly mentioned in the setup file. Path adds this as requirement to the setup file.<commit_after>'''
Python wrapper for the OpenAQ API
Written originally by David H Hagan
December 2015
'''
__version__ = '1.1.0'
try:
from setuptools import setup
except:
from distutils.core import setup
setup(
name = 'py-openaq',
version = __version__,
description = 'Python wrapper for the OpenAQ API',
keywords = ['OpenAQ', 'MIT', 'Air Quality'],
author = 'David H Hagan',
author_email = 'david@davidhhagan.com',
url = 'https://github.com/dhhagan/py-openaq',
license = 'MIT',
packages = ['openaq'],
install_requires = ['requests'],
test_suite = 'tests',
classifiers = [
'Development Status :: 3 - Alpha',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Atmospheric Science',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
ba84740e7ba0edd709c9cd076a7dce83a6c91a30 | research/mlt_quality_research.py | research/mlt_quality_research.py | #!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
| #!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
'''Try with search:
es.search(doc_type='', size=1, q='UnitText1.En:Einstein')
Or even better:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'], r['_id'])for r in es.search(doc_type=['places'], size=40, q='UnitText1.En:Albert Einstein')['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
| Add ES search example, similar to Mongo related FTS | Add ES search example, similar to Mongo related FTS
| Python | agpl-3.0 | Beit-Hatfutsot/dbs-back,Beit-Hatfutsot/dbs-back,Beit-Hatfutsot/dbs-back,Beit-Hatfutsot/dbs-back | #!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
Add ES search example, similar to Mongo related FTS | #!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
'''Try with search:
es.search(doc_type='', size=1, q='UnitText1.En:Einstein')
Or even better:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'], r['_id'])for r in es.search(doc_type=['places'], size=40, q='UnitText1.En:Albert Einstein')['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
| <commit_before>#!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
<commit_msg>Add ES search example, similar to Mongo related FTS<commit_after> | #!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
'''Try with search:
es.search(doc_type='', size=1, q='UnitText1.En:Einstein')
Or even better:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'], r['_id'])for r in es.search(doc_type=['places'], size=40, q='UnitText1.En:Albert Einstein')['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
| #!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
Add ES search example, similar to Mongo related FTS#!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
'''Try with search:
es.search(doc_type='', size=1, q='UnitText1.En:Einstein')
Or even better:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'], r['_id'])for r in es.search(doc_type=['places'], size=40, q='UnitText1.En:Albert Einstein')['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
| <commit_before>#!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
<commit_msg>Add ES search example, similar to Mongo related FTS<commit_after>#!/usr/bin/env python
import pprint
from elasticsearch import Elasticsearch
'''Inside ipython:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNames'], search_size=40)['hits']['hits']]
'''
'''Try with search:
es.search(doc_type='', size=1, q='UnitText1.En:Einstein')
Or even better:
[(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'], r['_id'])for r in es.search(doc_type=['places'], size=40, q='UnitText1.En:Albert Einstein')['hits']['hits']]
'''
def get_related(es, doc_id, index, doc_type, mlt_fields, target_collections, limit):
return [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index=index, doc_type=doc_type, id=doc_id, mlt_fields=mlt_fields, search_types=target_collections, search_size=limit)['hits']['hits']]
if __name__ == '__main__':
es = Elasticsearch()
mlt_fields = ['Header.En', 'UnitText1.En', 'Header.He', 'UnitText1.He']
target_collections = ['places','personalities','photoUnits','familyNames']
# For Paris:
pprint.pprint (get_related(es, 72312, 'bhp10', 'places', mlt_fields, target_collections, 40))
|
1a9a43b1e1f7872f70773f5793d2b588c2a58934 | setup.py | setup.py | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon',
'mock'
],
)
| #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon'
],
)
| Remove duplicate mock deps from coi-services | Remove duplicate mock deps from coi-services
| Python | bsd-2-clause | ooici/coi-services,ooici/coi-services,ooici/coi-services,ooici/coi-services,ooici/coi-services | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon',
'mock'
],
)
Remove duplicate mock deps from coi-services | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon'
],
)
| <commit_before>#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon',
'mock'
],
)
<commit_msg>Remove duplicate mock deps from coi-services<commit_after> | #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon'
],
)
| #!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon',
'mock'
],
)
Remove duplicate mock deps from coi-services#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon'
],
)
| <commit_before>#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon',
'mock'
],
)
<commit_msg>Remove duplicate mock deps from coi-services<commit_after>#!/usr/bin/env python
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
version = '0.1'
setup( name = 'coi-services',
version = version,
description = 'OOI ION COI Services',
url = 'https://github.com/ooici/coi-services',
download_url = 'http://ooici.net/releases',
license = 'Apache 2.0',
author = 'Michael Meisinger',
author_email = 'mmeisinger@ucsd.edu',
keywords = ['ooici','ioncore', 'pyon', 'coi'],
packages = find_packages(),
dependency_links = [
'http://ooici.net/releases'
],
test_suite = 'pyon',
install_requires = [
'pyon'
],
)
|
182b94f777b1743671b706c939ce14f89c31efca | lint/queue.py | lint/queue.py | from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
MIN_DELAY = 0.1
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay', MIN_DELAY)
queue = Daemon()
| from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay')
queue = Daemon()
| Remove MIN_DELAY bc a default setting is guaranteed | Remove MIN_DELAY bc a default setting is guaranteed
| Python | mit | SublimeLinter/SublimeLinter3,SublimeLinter/SublimeLinter3 | from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
MIN_DELAY = 0.1
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay', MIN_DELAY)
queue = Daemon()
Remove MIN_DELAY bc a default setting is guaranteed | from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay')
queue = Daemon()
| <commit_before>from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
MIN_DELAY = 0.1
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay', MIN_DELAY)
queue = Daemon()
<commit_msg>Remove MIN_DELAY bc a default setting is guaranteed<commit_after> | from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay')
queue = Daemon()
| from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
MIN_DELAY = 0.1
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay', MIN_DELAY)
queue = Daemon()
Remove MIN_DELAY bc a default setting is guaranteedfrom . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay')
queue = Daemon()
| <commit_before>from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
MIN_DELAY = 0.1
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay', MIN_DELAY)
queue = Daemon()
<commit_msg>Remove MIN_DELAY bc a default setting is guaranteed<commit_after>from . import persist
import time
import threading
# Map from view_id to threading.Timer objects
timers = {}
# For compatibility this is a class with unchanged API from SL3.
class Daemon:
def start(self, callback):
self._callback = callback
def hit(self, view):
assert self._callback, "Queue: Can't hit before start."
vid = view.id()
delay = get_delay() # [seconds]
return queue_lint(vid, delay, self._callback)
def queue_lint(vid, delay, callback):
hit_time = time.monotonic()
def worker():
callback(vid, hit_time)
try:
timers[vid].cancel()
except KeyError:
pass
timers[vid] = timer = threading.Timer(delay, worker)
timer.start()
return hit_time
def get_delay():
"""Return the delay between a lint request and when it will be processed.
If the lint mode is not background, there is no delay. Otherwise, if
a "delay" setting is not available in any of the settings, MIN_DELAY is used.
"""
if persist.settings.get('lint_mode') != 'background':
return 0
return persist.settings.get('delay')
queue = Daemon()
|
e01f8f4a9c9c0329b4d33106ef5589580ce5337d | bluesky/epics_callbacks.py | bluesky/epics_callbacks.py | import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event()
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
| import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event(loop=self._loop)
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
| Use the correct Event loop. | FIX: Use the correct Event loop.
| Python | bsd-3-clause | ericdill/bluesky,dchabot/bluesky,dchabot/bluesky,ericdill/bluesky,klauer/bluesky,sameera2004/bluesky,klauer/bluesky,sameera2004/bluesky | import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event()
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
FIX: Use the correct Event loop. | import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event(loop=self._loop)
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
| <commit_before>import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event()
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
<commit_msg>FIX: Use the correct Event loop.<commit_after> | import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event(loop=self._loop)
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
| import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event()
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
FIX: Use the correct Event loop.import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event(loop=self._loop)
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
| <commit_before>import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event()
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
<commit_msg>FIX: Use the correct Event loop.<commit_after>import epics
import asyncio
class PVSuspender:
"""
A class to manage the callback interface between asyincio and
pyepics.
This will probably be a base class eventually.
"""
def __init__(self, RE, pv_name, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
self._loop = loop
self.RE = RE
self._ev = None
self._pv = epics.PV(pv_name, auto_monitor=True)
self._pv.add_callback(self)
def _should_suspend(self, value):
"""
Determine if the current value of the PV is such
that we need to tell the scan to suspend
"""
return bool(value)
def _should_resume(self, value):
"""
Determine if the scan is ready to automatically
restart.
"""
return not bool(value)
def __call__(self, **kwargs):
"""
Make the class callable so that we can
pass it off to the pyepics callback stack.
"""
value = kwargs['value']
if self._ev is None or self._ev.is_set():
# in the case where either have never been
# called or have already fully cycled once
if self._should_suspend(value):
self._ev = asyncio.Event(loop=self._loop)
self._loop.call_soon_threadsafe(
self.RE.request_suspend,
self._ev.wait())
else:
if self._should_resume(value):
self._loop.call_soon_threadsafe(self._ev.set)
|
8530e491d600f6a03b163d885c5febee0e654cc5 | matador/core/management.py | matador/core/management.py | #!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def setup_logging(logging_destination='console', verbosity='DEBUG'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
setup_logging()
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
try:
args, sub_args = parser.parse_known_args()
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
| #!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def _setup_logging(logging_destination='console', verbosity='INFO'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
parser.add_argument(
'-l', '--logging',
type=str,
default='console',
dest='logging_destination',
help='logging (none, console or file)')
parser.add_argument(
'-v', '--verbosity',
type=str,
default='INFO',
help='Logging level. DEBUG, INFO, ERROR or CRITICAL')
try:
args, sub_args = parser.parse_known_args()
_setup_logging(args.logging_destination, args.verbosity)
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
| Add log level and destination arguments | Add log level and destination arguments
| Python | mit | Empiria/matador | #!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def setup_logging(logging_destination='console', verbosity='DEBUG'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
setup_logging()
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
try:
args, sub_args = parser.parse_known_args()
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
Add log level and destination arguments | #!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def _setup_logging(logging_destination='console', verbosity='INFO'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
parser.add_argument(
'-l', '--logging',
type=str,
default='console',
dest='logging_destination',
help='logging (none, console or file)')
parser.add_argument(
'-v', '--verbosity',
type=str,
default='INFO',
help='Logging level. DEBUG, INFO, ERROR or CRITICAL')
try:
args, sub_args = parser.parse_known_args()
_setup_logging(args.logging_destination, args.verbosity)
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
| <commit_before>#!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def setup_logging(logging_destination='console', verbosity='DEBUG'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
setup_logging()
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
try:
args, sub_args = parser.parse_known_args()
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
<commit_msg>Add log level and destination arguments<commit_after> | #!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def _setup_logging(logging_destination='console', verbosity='INFO'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
parser.add_argument(
'-l', '--logging',
type=str,
default='console',
dest='logging_destination',
help='logging (none, console or file)')
parser.add_argument(
'-v', '--verbosity',
type=str,
default='INFO',
help='Logging level. DEBUG, INFO, ERROR or CRITICAL')
try:
args, sub_args = parser.parse_known_args()
_setup_logging(args.logging_destination, args.verbosity)
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
| #!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def setup_logging(logging_destination='console', verbosity='DEBUG'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
setup_logging()
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
try:
args, sub_args = parser.parse_known_args()
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
Add log level and destination arguments#!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def _setup_logging(logging_destination='console', verbosity='INFO'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
parser.add_argument(
'-l', '--logging',
type=str,
default='console',
dest='logging_destination',
help='logging (none, console or file)')
parser.add_argument(
'-v', '--verbosity',
type=str,
default='INFO',
help='Logging level. DEBUG, INFO, ERROR or CRITICAL')
try:
args, sub_args = parser.parse_known_args()
_setup_logging(args.logging_destination, args.verbosity)
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
| <commit_before>#!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def setup_logging(logging_destination='console', verbosity='DEBUG'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
setup_logging()
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
try:
args, sub_args = parser.parse_known_args()
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
<commit_msg>Add log level and destination arguments<commit_after>#!/usr/bin/env python
import sys
import logging
import argparse
from matador.core.commands import commands
def _setup_logging(logging_destination='console', verbosity='INFO'):
logHandlers = {
'console': logging.StreamHandler(),
'none': logging.NullHandler(),
'file': logging.FileHandler('./axelrod.log')
}
logHandler = logHandlers[logging_destination]
logFormatters = {
'console': '%(message)s',
'none': '',
'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
logFormatter = logging.Formatter(logFormatters[logging_destination])
logHandler.setFormatter(logFormatter)
logger = logging.getLogger('matador')
level = logging.getLevelName(verbosity.upper())
logger.setLevel(level)
logger.addHandler(logHandler)
def execute_command():
parser = argparse.ArgumentParser(
description="Change management for Agresso")
parser.add_argument(
'command',
type=str,
help='Command')
parser.add_argument(
'-l', '--logging',
type=str,
default='console',
dest='logging_destination',
help='logging (none, console or file)')
parser.add_argument(
'-v', '--verbosity',
type=str,
default='INFO',
help='Logging level. DEBUG, INFO, ERROR or CRITICAL')
try:
args, sub_args = parser.parse_known_args()
_setup_logging(args.logging_destination, args.verbosity)
command = commands[args.command](parser)
except:
parser.print_help()
sys.exit()
command.execute()
|
f677c607d98fb54d0b469c06e3682322f6f6321f | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
],
package_dir={
'fulfil_client': 'fulfil_client'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
'fulfil_client.contrib',
],
package_dir={
'fulfil_client': 'fulfil_client',
'fulfil_client.contrib': 'fulfil_client/contrib'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
| Add contrib package to deployment | Add contrib package to deployment
| Python | isc | fulfilio/fulfil-python-api,sharoonthomas/fulfil-python-api | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
],
package_dir={
'fulfil_client': 'fulfil_client'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
Add contrib package to deployment | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
'fulfil_client.contrib',
],
package_dir={
'fulfil_client': 'fulfil_client',
'fulfil_client.contrib': 'fulfil_client/contrib'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
],
package_dir={
'fulfil_client': 'fulfil_client'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
<commit_msg>Add contrib package to deployment<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
'fulfil_client.contrib',
],
package_dir={
'fulfil_client': 'fulfil_client',
'fulfil_client.contrib': 'fulfil_client/contrib'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
],
package_dir={
'fulfil_client': 'fulfil_client'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
Add contrib package to deployment#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
'fulfil_client.contrib',
],
package_dir={
'fulfil_client': 'fulfil_client',
'fulfil_client.contrib': 'fulfil_client/contrib'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
],
package_dir={
'fulfil_client': 'fulfil_client'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
<commit_msg>Add contrib package to deployment<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'pyjwt',
'requests',
'requests_oauthlib',
'money',
'babel',
'six',
]
setup(
name='fulfil_client',
version='0.13.2',
description="Fulfil REST API Client in Python",
long_description=readme + '\n\n' + history,
author="Fulfil.IO Inc.",
author_email='hello@fulfil.io',
url='https://github.com/fulfilio/fulfil-python-api',
packages=[
'fulfil_client',
'fulfil_client.contrib',
],
package_dir={
'fulfil_client': 'fulfil_client',
'fulfil_client.contrib': 'fulfil_client/contrib'
},
include_package_data=True,
install_requires=requirements,
license="ISCL",
zip_safe=False,
keywords='fulfil_client',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'redis'],
)
|
3a12d545ef22db37d4d26b0a75af4dc4348afd9a | setup.py | setup.py | from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
) | from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'services/echo.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
)
| Include required echo service in package | Include required echo service in package
| Python | mit | markfinger/django-node,markfinger/django-node | from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
)Include required echo service in package | from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'services/echo.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
)
| <commit_before>from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
)<commit_msg>Include required echo service in package<commit_after> | from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'services/echo.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
)
| from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
)Include required echo service in packagefrom setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'services/echo.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
)
| <commit_before>from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
)<commit_msg>Include required echo service in package<commit_after>from setuptools import setup, find_packages
VERSION = '3.0.1'
setup(
name='django-node',
version=VERSION,
packages=find_packages(exclude=('tests', 'example',)),
package_data={
'django_node': [
'node_server.js',
'services/echo.js',
'package.json',
],
},
install_requires=[
'django',
'requests>=2.5.1',
],
description='Bindings and utils for integrating Node.js and NPM into a Django application',
long_description='Documentation at https://github.com/markfinger/django-node',
author='Mark Finger',
author_email='markfinger@gmail.com',
url='https://github.com/markfinger/django-node',
)
|
4ba46ac6674f7972d70d2e4f819303e38a934462 | setup.py | setup.py | # coding=utf-8
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact API SDK provides Python APIs to create and manage load tests",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
| # coding=utf-8
"""
Copyright 2013 Load Impact
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact SDK provides access to Load Impact's cloud-based load testing platform",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
| Add license notice and update description. | Add license notice and update description.
| Python | apache-2.0 | loadimpact/loadimpact-sdk-python | # coding=utf-8
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact API SDK provides Python APIs to create and manage load tests",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
Add license notice and update description. | # coding=utf-8
"""
Copyright 2013 Load Impact
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact SDK provides access to Load Impact's cloud-based load testing platform",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
| <commit_before># coding=utf-8
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact API SDK provides Python APIs to create and manage load tests",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
<commit_msg>Add license notice and update description.<commit_after> | # coding=utf-8
"""
Copyright 2013 Load Impact
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact SDK provides access to Load Impact's cloud-based load testing platform",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
| # coding=utf-8
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact API SDK provides Python APIs to create and manage load tests",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
Add license notice and update description.# coding=utf-8
"""
Copyright 2013 Load Impact
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact SDK provides access to Load Impact's cloud-based load testing platform",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
| <commit_before># coding=utf-8
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact API SDK provides Python APIs to create and manage load tests",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
<commit_msg>Add license notice and update description.<commit_after># coding=utf-8
"""
Copyright 2013 Load Impact
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# Make sure setup tools is installed, if not install it.
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'loadimpact'))
from version import __version__
setup(
name='loadimpact',
version=__version__,
author='Load Impact',
author_email='support@loadimpact.com',
packages=['loadimpact'],
url='http://developers.loadimpact.com/',
license='LICENSE.txt',
description="The Load Impact SDK provides access to Load Impact's cloud-based load testing platform",
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
],
keywords="loadimpact api rest sdk",
test_suite='test'
)
|
a092414a9af42c514febc9738da8d671cfb2ff3c | setup.py | setup.py | #!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
| #!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
install_requires=[
"pygments"
],
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
| Add pygments as dependency. Lets see if this works... | Add pygments as dependency. Lets see if this works...
| Python | mit | richrd/suplemon,richrd/suplemon,twolfson/suplemon,twolfson/suplemon | #!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
Add pygments as dependency. Lets see if this works... | #!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
install_requires=[
"pygments"
],
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
| <commit_before>#!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
<commit_msg>Add pygments as dependency. Lets see if this works...<commit_after> | #!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
install_requires=[
"pygments"
],
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
| #!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
Add pygments as dependency. Lets see if this works...#!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
install_requires=[
"pygments"
],
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
| <commit_before>#!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
<commit_msg>Add pygments as dependency. Lets see if this works...<commit_after>#!/usr/bin/env python
import re
from setuptools import setup
version = re.search(
'^__version__\s*=\s*"([^"]*)"',
open("suplemon/main.py").read(),
re.M
).group(1)
files = ["config/*.json", "themes/*", "modules/*.py", "linelight/*.py"]
setup(name="Suplemon",
version=version,
description="Console text editor with multi cursor support.",
author="Richard Lewis",
author_email="richrd.lewis@gmail.com",
url="https://github.com/richrd/suplemon/",
packages=["suplemon"],
package_data={"": files},
include_package_data=True,
install_requires=[
"pygments"
],
entry_points={
"console_scripts": ["suplemon=suplemon.cli:main"]
},
classifiers=[]
)
|
f2311a2369243939b5be12d07e17c3bf5b137073 | setup.py | setup.py | #!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.3.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
| #!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.4.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
| Update download url to newer version. | Update download url to newer version.
| Python | mit | giampaolo/pyftpdlib | #!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.3.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
Update download url to newer version. | #!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.4.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
| <commit_before>#!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.3.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
<commit_msg>Update download url to newer version.<commit_after> | #!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.4.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
| #!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.3.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
Update download url to newer version.#!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.4.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
| <commit_before>#!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.3.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
<commit_msg>Update download url to newer version.<commit_after>#!/usr/bin/env python
# setup.py
"""pyftpdlib installer.
To install pyftpdlib just open a command shell and run:
> python setup.py install
"""
from distutils.core import setup
long_descr = """\
Python FTP server library, based on asyncore framework, provides
an high-level portable interface to easily write asynchronous
FTP servers with Python."""
setup(
name='pyftpdlib',
version="0.4.0",
description='High-level asynchronous FTP server library',
long_description=long_descr,
license='MIT License',
platforms='Platform Independent',
author="Giampaolo Rodola'",
author_email='g.rodola@gmail.com',
url='http://code.google.com/p/pyftpdlib/',
download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.4.0.tar.gz',
packages=['pyftpdlib'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: File Transfer Protocol (FTP)',
'Topic :: Software Development :: Libraries :: Python Modules'
],
)
|
26b0571212d6abcd65fd4d857726131d12146d85 | setup.py | setup.py | from distutils.core import setup
setup(
name='LightMatchingEngine',
version='0.1.2',
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
) | from setuptools import setup
setup(
name='LightMatchingEngine',
use_scm_version=True,
setup_requires=['setuptools_scm'],
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
)
| Update to use scm for versioning | Update to use scm for versioning
| Python | mit | gavincyi/LightMatchingEngine | from distutils.core import setup
setup(
name='LightMatchingEngine',
version='0.1.2',
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
)Update to use scm for versioning | from setuptools import setup
setup(
name='LightMatchingEngine',
use_scm_version=True,
setup_requires=['setuptools_scm'],
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
)
| <commit_before>from distutils.core import setup
setup(
name='LightMatchingEngine',
version='0.1.2',
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
)<commit_msg>Update to use scm for versioning<commit_after> | from setuptools import setup
setup(
name='LightMatchingEngine',
use_scm_version=True,
setup_requires=['setuptools_scm'],
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
)
| from distutils.core import setup
setup(
name='LightMatchingEngine',
version='0.1.2',
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
)Update to use scm for versioningfrom setuptools import setup
setup(
name='LightMatchingEngine',
use_scm_version=True,
setup_requires=['setuptools_scm'],
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
)
| <commit_before>from distutils.core import setup
setup(
name='LightMatchingEngine',
version='0.1.2',
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
)<commit_msg>Update to use scm for versioning<commit_after>from setuptools import setup
setup(
name='LightMatchingEngine',
use_scm_version=True,
setup_requires=['setuptools_scm'],
author='Gavin Chan',
author_email='gavincyi@gmail.com',
packages=['lightmatchingengine'],
url='http://pypi.python.org/pypi/LightMatchingEngine/',
license='LICENSE.txt',
description='A light matching engine.'
)
|
eea9cabf7f15106124b3eb2b69f050f63f4c16f2 | yatsm/structural_break/_core.py | yatsm/structural_break/_core.py | from collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreak', _fields)
| from collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreakResult', _fields)
| Fix struc break named tuple name | Fix struc break named tuple name
| Python | mit | c11/yatsm,c11/yatsm | from collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreak', _fields)
Fix struc break named tuple name | from collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreakResult', _fields)
| <commit_before>from collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreak', _fields)
<commit_msg>Fix struc break named tuple name<commit_after> | from collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreakResult', _fields)
| from collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreak', _fields)
Fix struc break named tuple namefrom collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreakResult', _fields)
| <commit_before>from collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreak', _fields)
<commit_msg>Fix struc break named tuple name<commit_after>from collections import namedtuple
import pandas as pd
import xarray as xr
pandas_like = (pd.DataFrame, pd.Series, xr.DataArray)
_fields = ['method', 'index', 'score', 'process', 'pvalue', 'signif']
#: namedtuple: Structural break detection results
StructuralBreakResult = namedtuple('StructuralBreakResult', _fields)
|
3867d443c948dfa300016ed4235796b5c9e07011 | setup.py | setup.py | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.3',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
| import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.4',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
| Update version number and supported Python versions | Update version number and supported Python versions
| Python | mit | easy-as-python/django-webmention | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.3',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
Update version number and supported Python versions | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.4',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
| <commit_before>import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.3',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
<commit_msg>Update version number and supported Python versions<commit_after> | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.4',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
| import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.3',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
Update version number and supported Python versionsimport os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.4',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
| <commit_before>import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.3',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
<commit_msg>Update version number and supported Python versions<commit_after>import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.4',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
b0434a28080d59c27a755b70be195c9f3135bf94 | mdx_linkify/mdx_linkify.py | mdx_linkify/mdx_linkify.py | import bleach
from html5lib.sanitizer import HTMLSanitizer
from markdown.postprocessors import Postprocessor
from markdown import Extension
class MyTokenizer(HTMLSanitizer):
def sanitize_token(self, token):
return token
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks,
tokenizer=MyTokenizer)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| import bleach
from markdown.postprocessors import Postprocessor
from markdown import Extension
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| Make compatible with Bleach v2.0 and html5lib v1.0 | Make compatible with Bleach v2.0 and html5lib v1.0
| Python | mit | daGrevis/mdx_linkify | import bleach
from html5lib.sanitizer import HTMLSanitizer
from markdown.postprocessors import Postprocessor
from markdown import Extension
class MyTokenizer(HTMLSanitizer):
def sanitize_token(self, token):
return token
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks,
tokenizer=MyTokenizer)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
Make compatible with Bleach v2.0 and html5lib v1.0 | import bleach
from markdown.postprocessors import Postprocessor
from markdown import Extension
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| <commit_before>import bleach
from html5lib.sanitizer import HTMLSanitizer
from markdown.postprocessors import Postprocessor
from markdown import Extension
class MyTokenizer(HTMLSanitizer):
def sanitize_token(self, token):
return token
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks,
tokenizer=MyTokenizer)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
<commit_msg>Make compatible with Bleach v2.0 and html5lib v1.0<commit_after> | import bleach
from markdown.postprocessors import Postprocessor
from markdown import Extension
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| import bleach
from html5lib.sanitizer import HTMLSanitizer
from markdown.postprocessors import Postprocessor
from markdown import Extension
class MyTokenizer(HTMLSanitizer):
def sanitize_token(self, token):
return token
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks,
tokenizer=MyTokenizer)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
Make compatible with Bleach v2.0 and html5lib v1.0import bleach
from markdown.postprocessors import Postprocessor
from markdown import Extension
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
| <commit_before>import bleach
from html5lib.sanitizer import HTMLSanitizer
from markdown.postprocessors import Postprocessor
from markdown import Extension
class MyTokenizer(HTMLSanitizer):
def sanitize_token(self, token):
return token
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks,
tokenizer=MyTokenizer)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
<commit_msg>Make compatible with Bleach v2.0 and html5lib v1.0<commit_after>import bleach
from markdown.postprocessors import Postprocessor
from markdown import Extension
class LinkifyPostprocessor(Postprocessor):
def __init__(self, md, linkify_callbacks=[]):
super(Postprocessor, self).__init__(md)
self._callbacks = linkify_callbacks
def run(self, text):
text = bleach.linkify(text,
callbacks=self._callbacks)
return text
class LinkifyExtension(Extension):
config = {'linkify_callbacks': [[], 'Callbacks to send to bleach.linkify']}
def extendMarkdown(self, md, md_globals):
md.postprocessors.add(
"linkify",
LinkifyPostprocessor(md, self.getConfig('linkify_callbacks')),
"_begin")
def makeExtension(*args, **kwargs):
return LinkifyExtension(*args, **kwargs)
|
3c7c72ea00a7009e53cdd0404b35b887b6fb4e9e | setup.py | setup.py | from setuptools import setup
setup(
name='slacker',
version='0.6.8',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
| from setuptools import setup
setup(
name='slacker',
version='0.7.0',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
| Set version number to 0.7.0. | Set version number to 0.7.0.
| Python | apache-2.0 | STANAPO/slacker,techartorg/slacker,wkentaro/slacker,kashyap32/slacker,os/slacker,wasabi0522/slacker,hreeder/slacker | from setuptools import setup
setup(
name='slacker',
version='0.6.8',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
Set version number to 0.7.0. | from setuptools import setup
setup(
name='slacker',
version='0.7.0',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
| <commit_before>from setuptools import setup
setup(
name='slacker',
version='0.6.8',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
<commit_msg>Set version number to 0.7.0.<commit_after> | from setuptools import setup
setup(
name='slacker',
version='0.7.0',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
| from setuptools import setup
setup(
name='slacker',
version='0.6.8',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
Set version number to 0.7.0.from setuptools import setup
setup(
name='slacker',
version='0.7.0',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
| <commit_before>from setuptools import setup
setup(
name='slacker',
version='0.6.8',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
<commit_msg>Set version number to 0.7.0.<commit_after>from setuptools import setup
setup(
name='slacker',
version='0.7.0',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.apache.org/licenses/LICENSE-2.0',
test_suite='tests',
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
),
keywords='slack api'
)
|
73685bccb82dbdf570c1e2823e49e9b156b42ba1 | setup.py | setup.py | import os
import codecs
from setuptools import setup
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=['whitenoise'],
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
| import os
import codecs
from setuptools import setup, find_packages
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=find_packages(exclude=['tests*']),
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
| Use find_packages to ensure management command is included in installs | Use find_packages to ensure management command is included in installs
| Python | mit | evansd/whitenoise,KnockSoftware/whitenoise,evansd/whitenoise,hirokiky/whitenoise,evansd/whitenoise | import os
import codecs
from setuptools import setup
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=['whitenoise'],
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
Use find_packages to ensure management command is included in installs | import os
import codecs
from setuptools import setup, find_packages
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=find_packages(exclude=['tests*']),
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
| <commit_before>import os
import codecs
from setuptools import setup
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=['whitenoise'],
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
<commit_msg>Use find_packages to ensure management command is included in installs<commit_after> | import os
import codecs
from setuptools import setup, find_packages
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=find_packages(exclude=['tests*']),
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
| import os
import codecs
from setuptools import setup
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=['whitenoise'],
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
Use find_packages to ensure management command is included in installsimport os
import codecs
from setuptools import setup, find_packages
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=find_packages(exclude=['tests*']),
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
| <commit_before>import os
import codecs
from setuptools import setup
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=['whitenoise'],
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
<commit_msg>Use find_packages to ensure management command is included in installs<commit_after>import os
import codecs
from setuptools import setup, find_packages
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def read(*path):
full_path = os.path.join(PROJECT_ROOT, *path)
with codecs.open(full_path, 'r', encoding='utf-8') as f:
return f.read()
setup(
name='whitenoise',
version='0.12',
author='David Evans',
author_email='d@evans.io',
url='http://whitenoise.evans.io',
packages=find_packages(exclude=['tests*']),
license='MIT',
description="Serve static files direct from WSGI application",
long_description=read('README.rst'),
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
],
)
|
2551458006a0187dfb0c3d5ab87581df1029f65d | scripts/should_rebuild_master.py | scripts/should_rebuild_master.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
| #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files)
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
| Fix SyntaxError in the Travis scripts | Fix SyntaxError in the Travis scripts
| Python | mit | wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
Fix SyntaxError in the Travis scripts | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files)
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
| <commit_before>#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
<commit_msg>Fix SyntaxError in the Travis scripts<commit_after> | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files)
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
| #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
Fix SyntaxError in the Travis scripts#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files)
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
| <commit_before>#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
<commit_msg>Fix SyntaxError in the Travis scripts<commit_after>#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Decide whether we should re-build tests for a project on master.
Exits with code 1 if there are changes that require a rebuild, 0 if not.
"""
from __future__ import print_function
import os
import sys
from should_rerun_tests import should_run_tests, ShouldRebuild
import tooling
def should_run_deploy(changed_files, task):
"""
Given a set of changed files, check if we need to run tests.
"""
should_run_tests(changed_files=changed_files, task=task)
if (
task.startswith('sbt-') and
any(f.startswith('docker/scala_service') in changed_files)
):
raise ShouldRebuild(
'Changes to docker/scala_service mean we should deploy'
)
if __name__ == '__main__':
# Travis has an environment variable $TRAVIS_COMMIT_RANGE which tells us
# the range of commits that this push is testing. By inspecting its
# value and passing it to `git diff`, we can determine which files
# have changed.
changed_files = tooling.changed_files([os.environ['TRAVIS_COMMIT_RANGE']])
task = os.environ['TASK']
try:
should_run_deploy(changed_files=changed_files, task=task)
except ShouldRebuild as err:
print('*** %s' % err, file=sys.stderr)
sys.exit(1)
else:
sys.exit(0)
|
a2943faa21a51f90314a343da4ed14700c9f9c87 | setup.py | setup.py | from setuptools import setup
VERSION = '0.3'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
| from setuptools import setup
VERSION = '1.0'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
| Mark as stable and bump to 1.0 | Mark as stable and bump to 1.0
| Python | mit | filwaitman/jinja2-standalone-compiler | from setuptools import setup
VERSION = '0.3'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
Mark as stable and bump to 1.0 | from setuptools import setup
VERSION = '1.0'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
| <commit_before>from setuptools import setup
VERSION = '0.3'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
<commit_msg>Mark as stable and bump to 1.0<commit_after> | from setuptools import setup
VERSION = '1.0'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
| from setuptools import setup
VERSION = '0.3'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
Mark as stable and bump to 1.0from setuptools import setup
VERSION = '1.0'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
| <commit_before>from setuptools import setup
VERSION = '0.3'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
<commit_msg>Mark as stable and bump to 1.0<commit_after>from setuptools import setup
VERSION = '1.0'
setup(
name='jinja2_standalone_compiler',
packages=['jinja2_standalone_compiler', ],
version=VERSION,
author='Filipe Waitman',
author_email='filwaitman@gmail.com',
install_requires=[x.strip() for x in open('requirements.txt').readlines()],
url='https://github.com/filwaitman/jinja2-standalone-compiler',
download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION),
test_suite='tests',
keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Operating System :: OS Independent",
],
entry_points="""\
[console_scripts]
jinja2_standalone_compiler = jinja2_standalone_compiler:main_command
""",
)
|
35fc31cda618d05add5154e9ffbf2de676852d93 | setup.py | setup.py | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'requests',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| Add pandas as requirement for the project | Add pandas as requirement for the project
| Python | mit | datasciencebr/serenata-toolbox | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'requests',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
Add pandas as requirement for the project | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| <commit_before>from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'requests',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
<commit_msg>Add pandas as requirement for the project<commit_after> | from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'requests',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
Add pandas as requirement for the projectfrom setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
| <commit_before>from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'requests',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
<commit_msg>Add pandas as requirement for the project<commit_after>from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
|
929997d9d86f93033ef013c586095b59f151bce8 | setup.py | setup.py | #!/usr/local/bin/python -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
| #!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install requests'):
print 'Error installing python3 requests package. Exiting...'
quit()
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
| Add Python 3 requests install | Add Python 3 requests install
| Python | apache-2.0 | fxstein/SentientHome | #!/usr/local/bin/python -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
Add Python 3 requests install | #!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install requests'):
print 'Error installing python3 requests package. Exiting...'
quit()
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
| <commit_before>#!/usr/local/bin/python -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
<commit_msg>Add Python 3 requests install<commit_after> | #!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install requests'):
print 'Error installing python3 requests package. Exiting...'
quit()
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
| #!/usr/local/bin/python -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
Add Python 3 requests install#!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install requests'):
print 'Error installing python3 requests package. Exiting...'
quit()
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
| <commit_before>#!/usr/local/bin/python -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
<commit_msg>Add Python 3 requests install<commit_after>#!/usr/local/bin/python3 -u
__author__ = 'Oliver Ratzesberger <https://github.com/fxstein>'
__copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger'
__license__ = 'Apache License, Version 2.0'
# Make sure we have access to SentientHome commons
import os
print 'Checking node.js presence:'
if 0 != os.system('node -v'):
print 'node.js not present on system. Exiting...'
quit()
print 'Installing node.js dependencies:'
if 0 != os.system('npm install home'):
print 'Error installing node.js home module. Exiting...'
quit()
if 0 != os.system('npm install iniparser'):
print 'Error installing node.js iniparser module. Exiting...'
quit()
print 'Installing Python3 dependencies'
if 0 != os.system('pip3 install requests'):
print 'Error installing python3 requests package. Exiting...'
quit()
if 0 != os.system('pip3 install asyncio'):
print 'Error installing python3 asyncio package. Exiting...'
quit()
if 0 != os.system('pip3 install aiohttp'):
print 'Error installing python3 aiohttp package. Exiting...'
quit()
print 'Finished installing dependencies.'
|
69d8ef8c1eba424568158611d45f02bc316c737b | setup.py | setup.py | """
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='Glue',
version='0.1',
url='http://glue.github.com/',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
| """
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='glue',
version='0.1.1',
url='https://github.com/jorgebastida/glue',
dowload_url='https://nodeload.github.com/jorgebastida/glue/zipball/master',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
| Change the project name to glue, add the new public download_url | Change the project name to glue, add the new public download_url
| Python | bsd-3-clause | WillsB3/glue,zhiqinyigu/glue,jorgebastida/glue,dext0r/glue,beni55/glue,jorgebastida/glue,zhiqinyigu/glue,dext0r/glue,WillsB3/glue,beni55/glue | """
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='Glue',
version='0.1',
url='http://glue.github.com/',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
Change the project name to glue, add the new public download_url | """
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='glue',
version='0.1.1',
url='https://github.com/jorgebastida/glue',
dowload_url='https://nodeload.github.com/jorgebastida/glue/zipball/master',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
| <commit_before>"""
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='Glue',
version='0.1',
url='http://glue.github.com/',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
<commit_msg>Change the project name to glue, add the new public download_url<commit_after> | """
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='glue',
version='0.1.1',
url='https://github.com/jorgebastida/glue',
dowload_url='https://nodeload.github.com/jorgebastida/glue/zipball/master',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
| """
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='Glue',
version='0.1',
url='http://glue.github.com/',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
Change the project name to glue, add the new public download_url"""
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='glue',
version='0.1.1',
url='https://github.com/jorgebastida/glue',
dowload_url='https://nodeload.github.com/jorgebastida/glue/zipball/master',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
| <commit_before>"""
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='Glue',
version='0.1',
url='http://glue.github.com/',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
<commit_msg>Change the project name to glue, add the new public download_url<commit_after>"""
Glue
-----
Glue is a simple command line tool to generate CSS sprites.
"""
try:
from setuptools import setup
kw = {'entry_points':
"""[console_scripts]\nglue = glue:main\n""",
'zip_safe': False}
except ImportError:
from distutils.core import setup
kw = {'scripts': ['glue.py']}
setup(
name='glue',
version='0.1.1',
url='https://github.com/jorgebastida/glue',
dowload_url='https://nodeload.github.com/jorgebastida/glue/zipball/master',
license='BSD',
author='Jorge Bastida',
author_email='me@jorgebastida.com',
description='Glue is a simple command line tool to generate CSS sprites.',
long_description=('Glue is a simple command line tool to generate CSS '
'sprites.'),
py_modules=['glue'],
include_package_data=True,
platforms='any',
install_requires=[
'PIL>=1.1.6'
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities'
],
**kw
)
|
27d281ab2c733d80fdf7f3521e250e72341c85b7 | setup.py | setup.py | from distutils.core import setup
import os
f = open("README.rst")
try:
try:
readme_text = f.read()
except:
readme_text = ""
finally:
f.close()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
| from distutils.core import setup
import os
readme_fname = os.path.join(os.path.dirname(__file__), "README.rst")
readme_text = open(readme_fname).read()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
| Make long description import path agnostic. | Make long description import path agnostic.
| Python | bsd-3-clause | bloggse/ftptool | from distutils.core import setup
import os
f = open("README.rst")
try:
try:
readme_text = f.read()
except:
readme_text = ""
finally:
f.close()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
Make long description import path agnostic. | from distutils.core import setup
import os
readme_fname = os.path.join(os.path.dirname(__file__), "README.rst")
readme_text = open(readme_fname).read()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
| <commit_before>from distutils.core import setup
import os
f = open("README.rst")
try:
try:
readme_text = f.read()
except:
readme_text = ""
finally:
f.close()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
<commit_msg>Make long description import path agnostic.<commit_after> | from distutils.core import setup
import os
readme_fname = os.path.join(os.path.dirname(__file__), "README.rst")
readme_text = open(readme_fname).read()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
| from distutils.core import setup
import os
f = open("README.rst")
try:
try:
readme_text = f.read()
except:
readme_text = ""
finally:
f.close()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
Make long description import path agnostic.from distutils.core import setup
import os
readme_fname = os.path.join(os.path.dirname(__file__), "README.rst")
readme_text = open(readme_fname).read()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
| <commit_before>from distutils.core import setup
import os
f = open("README.rst")
try:
try:
readme_text = f.read()
except:
readme_text = ""
finally:
f.close()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
<commit_msg>Make long description import path agnostic.<commit_after>from distutils.core import setup
import os
readme_fname = os.path.join(os.path.dirname(__file__), "README.rst")
readme_text = open(readme_fname).read()
setup(name="ftptool", version="0.4",
url="http://blogg.se",
description="Higher-level interface to ftplib",
author="Blogg Esse AB",
author_email="opensource@blogg.se",
long_description=readme_text,
py_modules=["ftptool"])
|
9de760794eac63dd053b9a2ac78072a3648b7752 | tests/run.py | tests/run.py | from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_call_identifier",
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
| from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
from uuid import uuid4
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_{}".format(uuid4()),
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
| Add uuid to identifier in test script | Add uuid to identifier in test script
| Python | apache-2.0 | platoai/platoai-python,platoai/platoai | from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_call_identifier",
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
Add uuid to identifier in test script | from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
from uuid import uuid4
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_{}".format(uuid4()),
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
| <commit_before>from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_call_identifier",
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
<commit_msg>Add uuid to identifier in test script<commit_after> | from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
from uuid import uuid4
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_{}".format(uuid4()),
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
| from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_call_identifier",
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
Add uuid to identifier in test scriptfrom __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
from uuid import uuid4
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_{}".format(uuid4()),
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
| <commit_before>from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_call_identifier",
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
<commit_msg>Add uuid to identifier in test script<commit_after>from __future__ import print_function
import datetime
import os
import sys
from io import BytesIO
from pprint import pprint
from uuid import uuid4
import requests
import voxjar
if __name__ == "__main__":
metadata = {
"identifier": "test_{}".format(uuid4()),
"timestamp": datetime.datetime.now(),
"type": {
"identifier": "test_call_type_identifier",
"name": "test_call_type_name",
},
"agents": [
{
"identifier": "test_agent_identifier",
"name": "test_agent_name",
"phoneNumber": 1234567890,
}
],
"customers": [
{
"identifier": "test_customer_identifier",
"name": "test_customer_name",
"phoneNumber": 9876543210,
}
],
"direction": "OUTGOING",
"options": {"processAudio": True},
}
try:
url = sys.argv[1]
except IndexError:
# yapf: disable
url = "https://storage.googleapis.com/platoaiinc-audio-test/1-wav-gsm_ms-s16-8000"
client = voxjar.Client(url=os.getenv("VOXJAR_API_URL", "https://api.voxjar.com:9001"))
try:
pprint(client.push(metadata, audio=BytesIO(requests.get(url).content)))
except RuntimeError as e:
print(e)
|
521abaa6bfc4e1da4f11a22d811669f14e6c59f7 | setup.py | setup.py | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
#'Programming Language :: Python :: 3',
]
)
| Comment out python3 classifier for now. | Comment out python3 classifier for now.
| Python | lgpl-2.1 | mbr/slugger | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
Comment out python3 classifier for now. | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
#'Programming Language :: Python :: 3',
]
)
| <commit_before>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
<commit_msg>Comment out python3 classifier for now.<commit_after> | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
#'Programming Language :: Python :: 3',
]
)
| import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
Comment out python3 classifier for now.import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
#'Programming Language :: Python :: 3',
]
)
| <commit_before>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
<commit_msg>Comment out python3 classifier for now.<commit_after>import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='slugger',
version='0.2dev',
description=('Slugging done right. Tries to support close to 300'
'languages.'),
long_description=read('README.rst'),
keywords='slug slugging web i18n',
author='Marc Brinkmann',
author_email='git@marcbrinkmann.de',
url='http://github.com/mbr/slugger',
license='LGPLv2.1',
install_requires=['remember', 'logbook', 'unihandecode'],
include_package_data=True,
packages=find_packages(exclude=['glibcparse']),
classifiers=[
'Programming Language :: Python :: 2',
#'Programming Language :: Python :: 3',
]
)
|
68ef99afe3afe871e7f5471cbc18452f66c12be0 | setup.py | setup.py | #!/usr/bin/env python3
from setuptools import setup
setup(
name="cistern",
version="0.1.3",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.3.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| #!/usr/bin/env python3
from setuptools import setup
import sys
if not sys.version_info[0] == 3:
sys.exit("Sorry, Cistern only supports Python 3.")
setup(
name="cistern",
version="0.1.4",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.4.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| Add check for Python 3 and increment version | Add check for Python 3 and increment version
| Python | mit | archangelic/cistern | #!/usr/bin/env python3
from setuptools import setup
setup(
name="cistern",
version="0.1.3",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.3.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
Add check for Python 3 and increment version | #!/usr/bin/env python3
from setuptools import setup
import sys
if not sys.version_info[0] == 3:
sys.exit("Sorry, Cistern only supports Python 3.")
setup(
name="cistern",
version="0.1.4",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.4.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| <commit_before>#!/usr/bin/env python3
from setuptools import setup
setup(
name="cistern",
version="0.1.3",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.3.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
<commit_msg>Add check for Python 3 and increment version<commit_after> | #!/usr/bin/env python3
from setuptools import setup
import sys
if not sys.version_info[0] == 3:
sys.exit("Sorry, Cistern only supports Python 3.")
setup(
name="cistern",
version="0.1.4",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.4.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| #!/usr/bin/env python3
from setuptools import setup
setup(
name="cistern",
version="0.1.3",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.3.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
Add check for Python 3 and increment version#!/usr/bin/env python3
from setuptools import setup
import sys
if not sys.version_info[0] == 3:
sys.exit("Sorry, Cistern only supports Python 3.")
setup(
name="cistern",
version="0.1.4",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.4.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| <commit_before>#!/usr/bin/env python3
from setuptools import setup
setup(
name="cistern",
version="0.1.3",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.3.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
<commit_msg>Add check for Python 3 and increment version<commit_after>#!/usr/bin/env python3
from setuptools import setup
import sys
if not sys.version_info[0] == 3:
sys.exit("Sorry, Cistern only supports Python 3.")
setup(
name="cistern",
version="0.1.4",
license="MIT",
url="https://github.com/archangelic/cistern",
description="Command line tool for downloading torrents from RSS feeds.",
author="Michael Hancock",
author_email="michaelhancock89@gmail.com",
download_url=(
"https://github.com/archangelic/cistern/archive/v0.1.4.tar.gz"
),
install_requires=[
'click',
'configobj',
'feedparser',
'peewee',
'tabulate',
'transmissionrpc',
],
entry_points={
'console_scripts': [
'cistern=cistern.cistern:cli',
]
},
packages=[
'cistern',
],
keywords=['torrent', 'rss', 'transmission'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
9496f281ee46489712b85837b60adf9cd4eb9708 | setup.py | setup.py | # Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.6.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
| # Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.7.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
| Update google-cloud-bigquery version to incorporate PollingFuture retry changes. | Update google-cloud-bigquery version to incorporate PollingFuture retry changes.
Specifically: https://github.com/googleapis/google-cloud-python/commit/f576d148f802666dbd11cf7c50a0629a77f81665
Change-Id: Id3244786ffa73cbe3a166cfe35cb7f2219140a31
| Python | apache-2.0 | verilylifesciences/analysis-py-utils,verilylifesciences/analysis-py-utils | # Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.6.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
Update google-cloud-bigquery version to incorporate PollingFuture retry changes.
Specifically: https://github.com/googleapis/google-cloud-python/commit/f576d148f802666dbd11cf7c50a0629a77f81665
Change-Id: Id3244786ffa73cbe3a166cfe35cb7f2219140a31 | # Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.7.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
| <commit_before># Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.6.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
<commit_msg>Update google-cloud-bigquery version to incorporate PollingFuture retry changes.
Specifically: https://github.com/googleapis/google-cloud-python/commit/f576d148f802666dbd11cf7c50a0629a77f81665
Change-Id: Id3244786ffa73cbe3a166cfe35cb7f2219140a31<commit_after> | # Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.7.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
| # Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.6.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
Update google-cloud-bigquery version to incorporate PollingFuture retry changes.
Specifically: https://github.com/googleapis/google-cloud-python/commit/f576d148f802666dbd11cf7c50a0629a77f81665
Change-Id: Id3244786ffa73cbe3a166cfe35cb7f2219140a31# Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.7.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
| <commit_before># Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.6.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
<commit_msg>Update google-cloud-bigquery version to incorporate PollingFuture retry changes.
Specifically: https://github.com/googleapis/google-cloud-python/commit/f576d148f802666dbd11cf7c50a0629a77f81665
Change-Id: Id3244786ffa73cbe3a166cfe35cb7f2219140a31<commit_after># Copyright 2017 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package configuration."""
from setuptools import find_packages
from setuptools import setup
REQUIRED_PACKAGES = ['pandas',
'google-api-core==1.5.1',
'google-auth==1.4.1',
'google-cloud-bigquery==1.7.0',
'google-cloud-storage==1.10.0',
'pysqlite>=2.8.3',
'ddt',
'typing']
setup(
name='analysis-py-utils',
version='0.4.0',
license='Apache 2.0',
author='Verily Life Sciences',
url='https://github.com/verilylifesciences/analysis-py-utils',
install_requires=REQUIRED_PACKAGES,
packages=find_packages(),
include_package_data=True,
description='Python utilities for data analysis.',
requires=[])
|
4b85fbfba29410b4e04fc4db62c81206dac96b4a | setup.py | setup.py | from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
| from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3.1', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
| Add paramiko req >= 2.3.1 | Add paramiko req >= 2.3.1
| Python | apache-2.0 | turbulent/substance,turbulent/substance | from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
Add paramiko req >= 2.3.1 | from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3.1', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
| <commit_before>from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
<commit_msg>Add paramiko req >= 2.3.1<commit_after> | from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3.1', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
| from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
Add paramiko req >= 2.3.1from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3.1', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
| <commit_before>from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
<commit_msg>Add paramiko req >= 2.3.1<commit_after>from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko>=2.3.1', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.system():
install_requires.append('macfsevents')
setup(name='substance',
version=__version__,
author='Turbulent',
author_email='oss@turbulent.ca',
url='https://substance.readthedocs.io/',
license='Apache License 2.0',
long_description=readme,
description='Substance - Local dockerized development environment',
install_requires=install_requires,
packages=find_packages(),
package_data={'substance': ['support/*']},
test_suite='tests',
zip_safe=False,
include_package_data=True,
entry_points={
'console_scripts': [
'substance = substance.cli:cli',
'subenv = substance.subenv.cli:cli'
],
})
|
ccebabfc39fbb43c7f0f11dae7b5aa288e565788 | test_echo.py | test_echo.py | #!/usr/bin/env python
import pytest
import echo_server
import echo_client
| #!/usr/bin/env python
import pytest
import echo_server
from threading import Thread
import socket
def dummy_client():
message = "Christian Bale is a terrible actor."
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
def test_connection():
thread = Thread(target=echo_server.main)
thread.start()
assert dummy_client() == "Christian Bale is a terrible actor."
| Add test_connection unit test. This single test seems to cover it. | Add test_connection unit test. This single test seems to cover it.
| Python | mit | charlieRode/network_tools | #!/usr/bin/env python
import pytest
import echo_server
import echo_client
Add test_connection unit test. This single test seems to cover it. | #!/usr/bin/env python
import pytest
import echo_server
from threading import Thread
import socket
def dummy_client():
message = "Christian Bale is a terrible actor."
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
def test_connection():
thread = Thread(target=echo_server.main)
thread.start()
assert dummy_client() == "Christian Bale is a terrible actor."
| <commit_before>#!/usr/bin/env python
import pytest
import echo_server
import echo_client
<commit_msg>Add test_connection unit test. This single test seems to cover it.<commit_after> | #!/usr/bin/env python
import pytest
import echo_server
from threading import Thread
import socket
def dummy_client():
message = "Christian Bale is a terrible actor."
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
def test_connection():
thread = Thread(target=echo_server.main)
thread.start()
assert dummy_client() == "Christian Bale is a terrible actor."
| #!/usr/bin/env python
import pytest
import echo_server
import echo_client
Add test_connection unit test. This single test seems to cover it.#!/usr/bin/env python
import pytest
import echo_server
from threading import Thread
import socket
def dummy_client():
message = "Christian Bale is a terrible actor."
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
def test_connection():
thread = Thread(target=echo_server.main)
thread.start()
assert dummy_client() == "Christian Bale is a terrible actor."
| <commit_before>#!/usr/bin/env python
import pytest
import echo_server
import echo_client
<commit_msg>Add test_connection unit test. This single test seems to cover it.<commit_after>#!/usr/bin/env python
import pytest
import echo_server
from threading import Thread
import socket
def dummy_client():
message = "Christian Bale is a terrible actor."
port = 50000
address = '127.0.0.1'
client_socket = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_IP)
client_socket.connect((address, port))
client_socket.sendall(message)
client_socket.shutdown(socket.SHUT_WR)
return client_socket.recv(1024)
def test_connection():
thread = Thread(target=echo_server.main)
thread.start()
assert dummy_client() == "Christian Bale is a terrible actor."
|
a673b4608e7024a8778f7ea6ca7a6414748f8f21 | setup.py | setup.py | #!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
| #!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock', 'pep8',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
| Add pep8 to build deps | Add pep8 to build deps
| Python | apache-2.0 | ccassler/DeploymentManager,tbeckham/DeploymentManager,tbeckham/DeploymentManager,tbeckham/DeploymentManager,ccassler/DeploymentManager,ccassler/DeploymentManager | #!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
Add pep8 to build deps | #!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock', 'pep8',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
| <commit_before>#!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
<commit_msg>Add pep8 to build deps<commit_after> | #!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock', 'pep8',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
| #!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
Add pep8 to build deps#!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock', 'pep8',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
| <commit_before>#!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
<commit_msg>Add pep8 to build deps<commit_after>#!/usr/bin/env python
# Copyright 2009-2014 Eucalyptus Systems, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
setup(name='deploymentmanager',
version='0.1',
description='Eucalyptus Deployment and Configuration Management tools',
url='https://github.com/eucalyptus/DeploymentManager.git',
license='Apache License 2.0',
packages=find_packages(),
install_requires=['paramiko', 'PrettyTable', 'eve', 'requests', 'mock', 'pep8',
'Flask-Bootstrap', 'eve', 'PrettyTable', 'argparse', 'nose', 'httpretty'],
test_suite="nose.collector",
zip_safe=False,
classifiers=["Development Status :: 1 - Alpha",
"Topic :: Utilities",
"Environment :: Console"])
|
b8dea6cf081fa916f0c88fa8d042e1a9e7da6279 | charla/plugins/cap.py | charla/plugins/cap.py | from ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
| from ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source, *args):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
| Fix CAP so it takes any no. of args | Fix CAP so it takes any no. of args
| Python | mit | MrSwiss/charla,prologic/charla,spaceone/charla | from ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
Fix CAP so it takes any no. of args | from ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source, *args):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
| <commit_before>from ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
<commit_msg>Fix CAP so it takes any no. of args<commit_after> | from ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source, *args):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
| from ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
Fix CAP so it takes any no. of argsfrom ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source, *args):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
| <commit_before>from ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
<commit_msg>Fix CAP so it takes any no. of args<commit_after>from ..plugin import BasePlugin
from ..commands import BaseCommands
class Commands(BaseCommands):
def cap(self, sock, source, *args):
pass
class Capability(BasePlugin):
def init(self, *args, **kwargs):
super(Capability, self).init(*args, **kwargs)
Commands(*args, **kwargs).register(self)
|
ee6e887bc4be703c0d279baff1fac402c971883b | gitfs/views/index.py | gitfs/views/index.py | import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
#dirents = [
#('.', {'st_ino': 1, 'st_mode': S_IFDIR}),
#('..', {'st_ino': 2, 'st_mode': S_IFDIR}),
#('current', {'st_ino': 3, 'st_mode': S_IFDIR}),
#('history', {'st_ino': 4, 'st_mode': S_IFDIR})]
#return dirents
return ['.', '..', 'current', 'history']
| import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
return ['.', '..', 'current', 'history']
| Remove unused code from IndexView. | Remove unused code from IndexView.
| Python | apache-2.0 | bussiere/gitfs,PressLabs/gitfs,PressLabs/gitfs,ksmaheshkumar/gitfs,rowhit/gitfs | import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
#dirents = [
#('.', {'st_ino': 1, 'st_mode': S_IFDIR}),
#('..', {'st_ino': 2, 'st_mode': S_IFDIR}),
#('current', {'st_ino': 3, 'st_mode': S_IFDIR}),
#('history', {'st_ino': 4, 'st_mode': S_IFDIR})]
#return dirents
return ['.', '..', 'current', 'history']
Remove unused code from IndexView. | import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
return ['.', '..', 'current', 'history']
| <commit_before>import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
#dirents = [
#('.', {'st_ino': 1, 'st_mode': S_IFDIR}),
#('..', {'st_ino': 2, 'st_mode': S_IFDIR}),
#('current', {'st_ino': 3, 'st_mode': S_IFDIR}),
#('history', {'st_ino': 4, 'st_mode': S_IFDIR})]
#return dirents
return ['.', '..', 'current', 'history']
<commit_msg>Remove unused code from IndexView.<commit_after> | import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
return ['.', '..', 'current', 'history']
| import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
#dirents = [
#('.', {'st_ino': 1, 'st_mode': S_IFDIR}),
#('..', {'st_ino': 2, 'st_mode': S_IFDIR}),
#('current', {'st_ino': 3, 'st_mode': S_IFDIR}),
#('history', {'st_ino': 4, 'st_mode': S_IFDIR})]
#return dirents
return ['.', '..', 'current', 'history']
Remove unused code from IndexView.import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
return ['.', '..', 'current', 'history']
| <commit_before>import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
#dirents = [
#('.', {'st_ino': 1, 'st_mode': S_IFDIR}),
#('..', {'st_ino': 2, 'st_mode': S_IFDIR}),
#('current', {'st_ino': 3, 'st_mode': S_IFDIR}),
#('history', {'st_ino': 4, 'st_mode': S_IFDIR})]
#return dirents
return ['.', '..', 'current', 'history']
<commit_msg>Remove unused code from IndexView.<commit_after>import os
from errno import ENOENT
from stat import S_IFDIR
from gitfs import FuseMethodNotImplemented, FuseOSError
from .view import View
from log import log
class IndexView(View):
def statfs(self, path):
return {}
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
if path != '/':
raise FuseOSError(ENOENT)
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
return ['.', '..', 'current', 'history']
|
43fa842244da9d75496ba3ba02517870daca8849 | provision/08-create-keystone-stuff.py | provision/08-create-keystone-stuff.py | #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
| #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('/opt/himlar/json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
| Fix paths to json files | Fix paths to json files
| Python | apache-2.0 | norcams/himlar-connect,norcams/himlar-connect | #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
Fix paths to json files | #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('/opt/himlar/json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
| <commit_before>#!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
<commit_msg>Fix paths to json files<commit_after> | #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('/opt/himlar/json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
| #!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
Fix paths to json files#!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('/opt/himlar/json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
| <commit_before>#!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
<commit_msg>Fix paths to json files<commit_after>#!/usr/bin/env python
import ConfigParser
import requests
cp = ConfigParser.SafeConfigParser()
cp.read('/etc/keystone/keystone.conf')
token = cp.get('DEFAULT', 'admin_token')
baseurl = 'http://localhost:35357/v3/OS-FEDERATION'
headers = {
'X-Auth-Token': token,
'Content-Type': 'application/json',
}
with open('/opt/himlar/json/create-idp.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-mapping.json') as fh:
response = requests.put(baseurl + '/mappings/dataporten', headers=headers, data=fh.read())
response.raise_for_status()
with open('/opt/himlar/json/create-protocol.json') as fh:
response = requests.put(baseurl + '/identity_providers/dataporten/protocols/oidc', headers=headers, data=fh.read())
response.raise_for_status()
|
317eaa7dd37638f233d8968fb55ed596bc2b8502 | pycroscopy/io/translators/__init__.py | pycroscopy/io/translators/__init__.py | from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
| from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import igor_ibw
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
| Add missing import statement for igor translator | Add missing import statement for igor translator
| Python | mit | anugrah-saxena/pycroscopy,pycroscopy/pycroscopy | from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
Add missing import statement for igor translator | from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import igor_ibw
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
| <commit_before>from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
<commit_msg>Add missing import statement for igor translator<commit_after> | from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import igor_ibw
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
| from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
Add missing import statement for igor translatorfrom . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import igor_ibw
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
| <commit_before>from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
<commit_msg>Add missing import statement for igor translator<commit_after>from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import igor_ibw
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
|
43ea528a1832c94dd7879f995a1c4cc8dfb2a315 | pyroonga/tests/functional/conftest.py | pyroonga/tests/functional/conftest.py | # -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
def remove_table():
utils.sendquery('table_remove %s' % Tbl.__tablename__)
request.addfinalizer(remove_table)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
| # -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
def remove_table():
utils.sendquery('table_remove %s' % cls._tablename)
request.addfinalizer(remove_table)
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
| Fix an issue that tables not be removed in end of each test | Fix an issue that tables not be removed in end of each test
| Python | mit | naoina/pyroonga,naoina/pyroonga | # -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
def remove_table():
utils.sendquery('table_remove %s' % Tbl.__tablename__)
request.addfinalizer(remove_table)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
Fix an issue that tables not be removed in end of each test | # -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
def remove_table():
utils.sendquery('table_remove %s' % cls._tablename)
request.addfinalizer(remove_table)
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
| <commit_before># -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
def remove_table():
utils.sendquery('table_remove %s' % Tbl.__tablename__)
request.addfinalizer(remove_table)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
<commit_msg>Fix an issue that tables not be removed in end of each test<commit_after> | # -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
def remove_table():
utils.sendquery('table_remove %s' % cls._tablename)
request.addfinalizer(remove_table)
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
| # -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
def remove_table():
utils.sendquery('table_remove %s' % Tbl.__tablename__)
request.addfinalizer(remove_table)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
Fix an issue that tables not be removed in end of each test# -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
def remove_table():
utils.sendquery('table_remove %s' % cls._tablename)
request.addfinalizer(remove_table)
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
| <commit_before># -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
def remove_table():
utils.sendquery('table_remove %s' % Tbl.__tablename__)
request.addfinalizer(remove_table)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
<commit_msg>Fix an issue that tables not be removed in end of each test<commit_after># -*- coding: utf-8 -*-
import json
import os
import pytest
from pyroonga.odm.table import tablebase, TableBase
from pyroonga.tests import utils
FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json')
@pytest.fixture
def Table(request):
class TableBaseForTest(TableBase):
@utils.classproperty
def __tablename__(cls):
if not getattr(cls, '_tablename', None):
cls._tablename = utils.gen_unique_tablename()
def remove_table():
utils.sendquery('table_remove %s' % cls._tablename)
request.addfinalizer(remove_table)
return cls._tablename
Tbl = tablebase(cls=TableBaseForTest)
return Tbl
@pytest.fixture
def fixture1():
with open(FIXTURE_PATH % 1) as f:
return json.load(f)
@pytest.fixture
def fixture2():
with open(FIXTURE_PATH % 2) as f:
return json.load(f)
|
c613df26375d205272ecc1ccc6295b292508cc13 | PhotoLoader/loader/tests/test_model.py | PhotoLoader/loader/tests/test_model.py | from io import BytesIO
from PIL import Image
from django.core.files.base import ContentFile
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
def tearDown(self):
self.photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1")
# no problems with the new different image
up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(up_photo.md5sum, self.photo.md5sum)
| from io import BytesIO
import os
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from PIL import Image
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
self.up_photo = None
def tearDown(self):
# delete created files from media/photos folder
self.photo.delete()
self.up_photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1", thumbnail = None # we won't generate thumbnail image
)
path = default_storage.path(name="photos/test.jpg")
default_storage.delete(path) # remove photo created in 'media' folder
# no problems with the new different image
self.up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(self.up_photo.md5sum, self.photo.md5sum)
| Delete unnecessary file in 'media' folder | Delete unnecessary file in 'media' folder
| Python | mit | SerSamgy/PhotoLoader,SerSamgy/PhotoLoader | from io import BytesIO
from PIL import Image
from django.core.files.base import ContentFile
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
def tearDown(self):
self.photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1")
# no problems with the new different image
up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(up_photo.md5sum, self.photo.md5sum)
Delete unnecessary file in 'media' folder | from io import BytesIO
import os
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from PIL import Image
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
self.up_photo = None
def tearDown(self):
# delete created files from media/photos folder
self.photo.delete()
self.up_photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1", thumbnail = None # we won't generate thumbnail image
)
path = default_storage.path(name="photos/test.jpg")
default_storage.delete(path) # remove photo created in 'media' folder
# no problems with the new different image
self.up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(self.up_photo.md5sum, self.photo.md5sum)
| <commit_before>from io import BytesIO
from PIL import Image
from django.core.files.base import ContentFile
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
def tearDown(self):
self.photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1")
# no problems with the new different image
up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(up_photo.md5sum, self.photo.md5sum)
<commit_msg>Delete unnecessary file in 'media' folder<commit_after> | from io import BytesIO
import os
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from PIL import Image
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
self.up_photo = None
def tearDown(self):
# delete created files from media/photos folder
self.photo.delete()
self.up_photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1", thumbnail = None # we won't generate thumbnail image
)
path = default_storage.path(name="photos/test.jpg")
default_storage.delete(path) # remove photo created in 'media' folder
# no problems with the new different image
self.up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(self.up_photo.md5sum, self.photo.md5sum)
| from io import BytesIO
from PIL import Image
from django.core.files.base import ContentFile
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
def tearDown(self):
self.photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1")
# no problems with the new different image
up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(up_photo.md5sum, self.photo.md5sum)
Delete unnecessary file in 'media' folderfrom io import BytesIO
import os
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from PIL import Image
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
self.up_photo = None
def tearDown(self):
# delete created files from media/photos folder
self.photo.delete()
self.up_photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1", thumbnail = None # we won't generate thumbnail image
)
path = default_storage.path(name="photos/test.jpg")
default_storage.delete(path) # remove photo created in 'media' folder
# no problems with the new different image
self.up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(self.up_photo.md5sum, self.photo.md5sum)
| <commit_before>from io import BytesIO
from PIL import Image
from django.core.files.base import ContentFile
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
def tearDown(self):
self.photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1")
# no problems with the new different image
up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(up_photo.md5sum, self.photo.md5sum)
<commit_msg>Delete unnecessary file in 'media' folder<commit_after>from io import BytesIO
import os
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from PIL import Image
from .factory import PhotoFactory
class ModelTest(TestCase):
def setUp(self):
self.photo = PhotoFactory()
self.up_photo = None
def tearDown(self):
# delete created files from media/photos folder
self.photo.delete()
self.up_photo.delete()
def test_save(self):
self.assertTrue(self.photo.md5sum)
# prepare new upload image
thumb = Image.new('RGB', (1024, 768), 'red') # the same size and color as self.photo.image
thumb_io = BytesIO()
thumb.save(thumb_io, format='JPEG')
# prevent the purposefully-thrown exception from breaking the entire unittest's transaction
with transaction.atomic():
self.assertRaisesMessage(IntegrityError, "UNIQUE constraint failed: loader_photo.md5sum",
PhotoFactory, image = ContentFile(thumb_io.getvalue(), "test.jpg"),
name = "Uploaded Photo 1", thumbnail = None # we won't generate thumbnail image
)
path = default_storage.path(name="photos/test.jpg")
default_storage.delete(path) # remove photo created in 'media' folder
# no problems with the new different image
self.up_photo = PhotoFactory(name = "Uploaded Photo 1") # new blue image
self.assertNotEqual(self.up_photo.md5sum, self.photo.md5sum)
|
47f19fec718f8407965487e2d3b993e8dbc7e23b | qregexeditor/api/match_highlighter.py | qregexeditor/api/match_highlighter.py | import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
match = self.prog.search(text)
if match:
start, end = match.span()
while match and end > start:
self.setFormat(start, end - start, self._format)
match = self.prog.search(text, match.end())
if match:
start, end = match.span()
| import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
for m in self.prog.finditer(text):
start, end = m.span()
self.setFormat(start, end - start, self._format)
| Fix highlighting when multiple matches | Fix highlighting when multiple matches
| Python | mit | ColinDuquesnoy/QRegexEditor | import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
match = self.prog.search(text)
if match:
start, end = match.span()
while match and end > start:
self.setFormat(start, end - start, self._format)
match = self.prog.search(text, match.end())
if match:
start, end = match.span()
Fix highlighting when multiple matches | import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
for m in self.prog.finditer(text):
start, end = m.span()
self.setFormat(start, end - start, self._format)
| <commit_before>import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
match = self.prog.search(text)
if match:
start, end = match.span()
while match and end > start:
self.setFormat(start, end - start, self._format)
match = self.prog.search(text, match.end())
if match:
start, end = match.span()
<commit_msg>Fix highlighting when multiple matches<commit_after> | import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
for m in self.prog.finditer(text):
start, end = m.span()
self.setFormat(start, end - start, self._format)
| import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
match = self.prog.search(text)
if match:
start, end = match.span()
while match and end > start:
self.setFormat(start, end - start, self._format)
match = self.prog.search(text, match.end())
if match:
start, end = match.span()
Fix highlighting when multiple matchesimport re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
for m in self.prog.finditer(text):
start, end = m.span()
self.setFormat(start, end - start, self._format)
| <commit_before>import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
match = self.prog.search(text)
if match:
start, end = match.span()
while match and end > start:
self.setFormat(start, end - start, self._format)
match = self.prog.search(text, match.end())
if match:
start, end = match.span()
<commit_msg>Fix highlighting when multiple matches<commit_after>import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
if self.prog and text:
for m in self.prog.finditer(text):
start, end = m.span()
self.setFormat(start, end - start, self._format)
|
d4e5af537be36bd50405e60fdb46f31b88537916 | src/commoner_i/views.py | src/commoner_i/views.py | from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
| from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.free:
# return a 404 for FREE profiles
raise Http404
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
| Raise a 404 when for FREE profile badge requests | Raise a 404 when for FREE profile badge requests
| Python | agpl-3.0 | cc-archive/commoner,cc-archive/commoner | from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
Raise a 404 when for FREE profile badge requests | from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.free:
# return a 404 for FREE profiles
raise Http404
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
| <commit_before>from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
<commit_msg>Raise a 404 when for FREE profile badge requests<commit_after> | from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.free:
# return a 404 for FREE profiles
raise Http404
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
| from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
Raise a 404 when for FREE profile badge requestsfrom django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.free:
# return a 404 for FREE profiles
raise Http404
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
| <commit_before>from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
<commit_msg>Raise a 404 when for FREE profile badge requests<commit_after>from django.core.files.storage import default_storage
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404
def badge(request, username, size=''):
# serve the inactive badge by default
filename = 'images/badge/%sinactive.png' % size
# get a handle for the user profile
profile = get_object_or_404(User, username=username)
profile = profile.get_profile()
if profile.free:
# return a 404 for FREE profiles
raise Http404
if profile.active:
# serve the active badge
filename = 'images/badge%s/active.png' % size
# set the content type appropriately
return HttpResponse(default_storage.open(filename).read(),
content_type='image/png')
|
bb3842ab99b830eee5dc7f34061f3ad98a2b6374 | flask_ui/models/__init__.py | flask_ui/models/__init__.py | from flask_ui import db
class Group(db.Model):
__tablename__ = 'Groups'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
class User(db.Model):
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60))
class Tag(db.Model):
__tablename__ = 'Tags'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
group_id = db.Column(db.Integer, db.ForeignKey('Group.id'))
class Project(db.Model):
__tablename__ = 'Projects'
id = db.Column(db.Integer, primary_key=True)
name = db.String(30)
class Question(db.Model):
__tablename__ = 'Questions'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
text = db.Column(db.Text)
class Answer(db.Model):
__tablename__ = 'Answers'
id = db.Column(db.Integer, primary_key=True)
| Add a basic database model | Add a basic database model
| Python | mit | matcom/autoexam,matcom/autoexam,matcom/autoexam,matcom/autoexam,matcom/autoexam | Add a basic database model | from flask_ui import db
class Group(db.Model):
__tablename__ = 'Groups'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
class User(db.Model):
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60))
class Tag(db.Model):
__tablename__ = 'Tags'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
group_id = db.Column(db.Integer, db.ForeignKey('Group.id'))
class Project(db.Model):
__tablename__ = 'Projects'
id = db.Column(db.Integer, primary_key=True)
name = db.String(30)
class Question(db.Model):
__tablename__ = 'Questions'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
text = db.Column(db.Text)
class Answer(db.Model):
__tablename__ = 'Answers'
id = db.Column(db.Integer, primary_key=True)
| <commit_before><commit_msg>Add a basic database model<commit_after> | from flask_ui import db
class Group(db.Model):
__tablename__ = 'Groups'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
class User(db.Model):
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60))
class Tag(db.Model):
__tablename__ = 'Tags'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
group_id = db.Column(db.Integer, db.ForeignKey('Group.id'))
class Project(db.Model):
__tablename__ = 'Projects'
id = db.Column(db.Integer, primary_key=True)
name = db.String(30)
class Question(db.Model):
__tablename__ = 'Questions'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
text = db.Column(db.Text)
class Answer(db.Model):
__tablename__ = 'Answers'
id = db.Column(db.Integer, primary_key=True)
| Add a basic database modelfrom flask_ui import db
class Group(db.Model):
__tablename__ = 'Groups'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
class User(db.Model):
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60))
class Tag(db.Model):
__tablename__ = 'Tags'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
group_id = db.Column(db.Integer, db.ForeignKey('Group.id'))
class Project(db.Model):
__tablename__ = 'Projects'
id = db.Column(db.Integer, primary_key=True)
name = db.String(30)
class Question(db.Model):
__tablename__ = 'Questions'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
text = db.Column(db.Text)
class Answer(db.Model):
__tablename__ = 'Answers'
id = db.Column(db.Integer, primary_key=True)
| <commit_before><commit_msg>Add a basic database model<commit_after>from flask_ui import db
class Group(db.Model):
__tablename__ = 'Groups'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
class User(db.Model):
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60))
class Tag(db.Model):
__tablename__ = 'Tags'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
group_id = db.Column(db.Integer, db.ForeignKey('Group.id'))
class Project(db.Model):
__tablename__ = 'Projects'
id = db.Column(db.Integer, primary_key=True)
name = db.String(30)
class Question(db.Model):
__tablename__ = 'Questions'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20), unique=True)
text = db.Column(db.Text)
class Answer(db.Model):
__tablename__ = 'Answers'
id = db.Column(db.Integer, primary_key=True)
| |
ff3ec67192ec144c12cabc7b403f17650c460757 | tests/sentry/metrics/test_datadog.py | tests/sentry/metrics/test_datadog.py | from __future__ import absolute_import
import socket
from mock import patch
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=socket.gethostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=socket.gethostname(),
)
| from __future__ import absolute_import
from mock import patch
from datadog.util.hostname import get_hostname
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=get_hostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=get_hostname(),
)
| Test DatadogMetricsBackend against datadog's get_hostname | Test DatadogMetricsBackend against datadog's get_hostname
This fixes tests in Travis since the hostname returned is different
| Python | bsd-3-clause | ngonzalvez/sentry,korealerts1/sentry,fotinakis/sentry,beeftornado/sentry,ngonzalvez/sentry,gencer/sentry,nicholasserra/sentry,BuildingLink/sentry,JamesMura/sentry,kevinlondon/sentry,jean/sentry,beeftornado/sentry,mvaled/sentry,mvaled/sentry,Natim/sentry,looker/sentry,kevinlondon/sentry,korealerts1/sentry,daevaorn/sentry,daevaorn/sentry,ifduyue/sentry,BayanGroup/sentry,fotinakis/sentry,alexm92/sentry,looker/sentry,JamesMura/sentry,Kryz/sentry,alexm92/sentry,imankulov/sentry,BayanGroup/sentry,jean/sentry,ngonzalvez/sentry,BuildingLink/sentry,gencer/sentry,imankulov/sentry,JackDanger/sentry,gencer/sentry,ifduyue/sentry,mvaled/sentry,ifduyue/sentry,gencer/sentry,BayanGroup/sentry,JamesMura/sentry,JackDanger/sentry,mitsuhiko/sentry,kevinlondon/sentry,ifduyue/sentry,jean/sentry,Natim/sentry,beeftornado/sentry,zenefits/sentry,mvaled/sentry,mvaled/sentry,ifduyue/sentry,BuildingLink/sentry,looker/sentry,zenefits/sentry,jean/sentry,BuildingLink/sentry,daevaorn/sentry,Kryz/sentry,Kryz/sentry,JamesMura/sentry,jean/sentry,felixbuenemann/sentry,Natim/sentry,zenefits/sentry,zenefits/sentry,zenefits/sentry,looker/sentry,BuildingLink/sentry,looker/sentry,felixbuenemann/sentry,felixbuenemann/sentry,alexm92/sentry,nicholasserra/sentry,gencer/sentry,nicholasserra/sentry,imankulov/sentry,mitsuhiko/sentry,JamesMura/sentry,daevaorn/sentry,fotinakis/sentry,JackDanger/sentry,korealerts1/sentry,fotinakis/sentry,mvaled/sentry | from __future__ import absolute_import
import socket
from mock import patch
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=socket.gethostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=socket.gethostname(),
)
Test DatadogMetricsBackend against datadog's get_hostname
This fixes tests in Travis since the hostname returned is different | from __future__ import absolute_import
from mock import patch
from datadog.util.hostname import get_hostname
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=get_hostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=get_hostname(),
)
| <commit_before>from __future__ import absolute_import
import socket
from mock import patch
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=socket.gethostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=socket.gethostname(),
)
<commit_msg>Test DatadogMetricsBackend against datadog's get_hostname
This fixes tests in Travis since the hostname returned is different<commit_after> | from __future__ import absolute_import
from mock import patch
from datadog.util.hostname import get_hostname
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=get_hostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=get_hostname(),
)
| from __future__ import absolute_import
import socket
from mock import patch
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=socket.gethostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=socket.gethostname(),
)
Test DatadogMetricsBackend against datadog's get_hostname
This fixes tests in Travis since the hostname returned is differentfrom __future__ import absolute_import
from mock import patch
from datadog.util.hostname import get_hostname
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=get_hostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=get_hostname(),
)
| <commit_before>from __future__ import absolute_import
import socket
from mock import patch
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=socket.gethostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=socket.gethostname(),
)
<commit_msg>Test DatadogMetricsBackend against datadog's get_hostname
This fixes tests in Travis since the hostname returned is different<commit_after>from __future__ import absolute_import
from mock import patch
from datadog.util.hostname import get_hostname
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('datadog.threadstats.base.ThreadStats.increment')
def test_incr(self, mock_incr):
self.backend.incr('foo', instance='bar')
mock_incr.assert_called_once_with(
'sentrytest.foo', 1,
tags=['instance:bar'],
host=get_hostname(),
)
@patch('datadog.threadstats.base.ThreadStats.timing')
def test_timing(self, mock_timing):
self.backend.timing('foo', 30, instance='bar')
mock_timing.assert_called_once_with(
'sentrytest.foo', 30,
sample_rate=1,
tags=['instance:bar'],
host=get_hostname(),
)
|
8d02522c276b87f45999281c3aa6a57e19df9c09 | src/core/middlewares.py | src/core/middlewares.py | import re
from django.conf import settings
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
path = request.get_full_path().replace(lang, fallback, 1)
return self.response_redirect_class(path)
| import re
from django.conf import settings
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
script_prefix = get_script_prefix()
path = request.get_full_path().replace(
script_prefix + lang, script_prefix + fallback, 1,
)
return self.response_redirect_class(path)
| Prepend script prefix when replacing lang code | Prepend script prefix when replacing lang code
| Python | mit | pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016 | import re
from django.conf import settings
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
path = request.get_full_path().replace(lang, fallback, 1)
return self.response_redirect_class(path)
Prepend script prefix when replacing lang code | import re
from django.conf import settings
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
script_prefix = get_script_prefix()
path = request.get_full_path().replace(
script_prefix + lang, script_prefix + fallback, 1,
)
return self.response_redirect_class(path)
| <commit_before>import re
from django.conf import settings
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
path = request.get_full_path().replace(lang, fallback, 1)
return self.response_redirect_class(path)
<commit_msg>Prepend script prefix when replacing lang code<commit_after> | import re
from django.conf import settings
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
script_prefix = get_script_prefix()
path = request.get_full_path().replace(
script_prefix + lang, script_prefix + fallback, 1,
)
return self.response_redirect_class(path)
| import re
from django.conf import settings
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
path = request.get_full_path().replace(lang, fallback, 1)
return self.response_redirect_class(path)
Prepend script prefix when replacing lang codeimport re
from django.conf import settings
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
script_prefix = get_script_prefix()
path = request.get_full_path().replace(
script_prefix + lang, script_prefix + fallback, 1,
)
return self.response_redirect_class(path)
| <commit_before>import re
from django.conf import settings
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
path = request.get_full_path().replace(lang, fallback, 1)
return self.response_redirect_class(path)
<commit_msg>Prepend script prefix when replacing lang code<commit_after>import re
from django.conf import settings
from django.core.urlresolvers import get_script_prefix
from django.http import HttpResponseRedirect
# Matches things like
# /en
# /en/
# /en/foo/bar (can be anything after the first trailing slash)
# But not
# /en-gb
# because the fallback language code is not followed immediately by a slash.
FALLBACK_PREFIX_PATTERN = re.compile(
r'^/(?P<lang>{langs})(?:/?|/.+)$'.format(
langs='|'.join(settings.FALLBACK_LANGUAGE_PREFIXES.keys()),
),
re.UNICODE,
)
class LocaleFallbackMiddleware:
"""Redirect entries in ``settings.FALLBACK_LANGUAGE_PREFIXES`` to a
valid language prefix.
"""
response_redirect_class = HttpResponseRedirect
def process_request(self, request):
if not settings.USE_I18N:
return
match = FALLBACK_PREFIX_PATTERN.match(request.path_info)
if not match:
return
lang = match.group('lang')
fallback = settings.FALLBACK_LANGUAGE_PREFIXES[lang]
script_prefix = get_script_prefix()
path = request.get_full_path().replace(
script_prefix + lang, script_prefix + fallback, 1,
)
return self.response_redirect_class(path)
|
4489a5ffcd7fee5f6c243e050de5e65ef45a3100 | nested_comments/serializers.py | nested_comments/serializers.py | # Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
parent = PKRelatedFieldAcceptNull(read_only = True)
| # Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
| Remove unneded API serializer field that was breaking nested comments | Remove unneded API serializer field that was breaking nested comments
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | # Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
parent = PKRelatedFieldAcceptNull(read_only = True)
Remove unneded API serializer field that was breaking nested comments | # Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
| <commit_before># Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
parent = PKRelatedFieldAcceptNull(read_only = True)
<commit_msg>Remove unneded API serializer field that was breaking nested comments<commit_after> | # Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
| # Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
parent = PKRelatedFieldAcceptNull(read_only = True)
Remove unneded API serializer field that was breaking nested comments# Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
| <commit_before># Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
parent = PKRelatedFieldAcceptNull(read_only = True)
<commit_msg>Remove unneded API serializer field that was breaking nested comments<commit_after># Third party apps
from rest_framework import serializers
# Other AstroBin apps
from common.api_fields import PKRelatedFieldAcceptNull
# This app
from .models import NestedComment
class NestedCommentSerializer(serializers.ModelSerializer):
class Meta:
model = NestedComment
fields = (
'id',
'author',
'content_type',
'object_id',
'text',
'created',
'updated',
'deleted',
'parent',
)
|
80c192155256aa02f290130f792fc804fb59a4d7 | pycat/talk.py | pycat/talk.py | """Communication link driver."""
import sys
import selectors
CLIENT_TO_SERVER = object()
SERVER_TO_CLIENT = object()
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
with selectors.DefaultSelector() as selector:
selector.register(source, selectors.EVENT_READ, CLIENT_TO_SERVER)
selector.register(socket, selectors.EVENT_READ, SERVER_TO_CLIENT)
while True:
for key, events in selector.select():
if key.data is CLIENT_TO_SERVER:
data = source.readline()
socket.send(data)
elif key.data is SERVER_TO_CLIENT:
data = socket.recv(OUTPUT_BUFFER_SIZE)
sink.write(data)
sink.flush()
| """Communication link driver."""
import sys
import select
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
while True:
readable, writable, exceptional = select.select((socket, source),
(),
(socket, source, sink))
if source in readable:
socket.send(source.readline())
if socket in readable:
sink.write(socket.recv(OUTPUT_BUFFER_SIZE))
sink.flush()
| Switch to just using `select` directly | Switch to just using `select` directly
This is less efficient, but does let use get the "exceptional" cases
and handle them more pleasantly.
| Python | mit | prophile/pycat | """Communication link driver."""
import sys
import selectors
CLIENT_TO_SERVER = object()
SERVER_TO_CLIENT = object()
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
with selectors.DefaultSelector() as selector:
selector.register(source, selectors.EVENT_READ, CLIENT_TO_SERVER)
selector.register(socket, selectors.EVENT_READ, SERVER_TO_CLIENT)
while True:
for key, events in selector.select():
if key.data is CLIENT_TO_SERVER:
data = source.readline()
socket.send(data)
elif key.data is SERVER_TO_CLIENT:
data = socket.recv(OUTPUT_BUFFER_SIZE)
sink.write(data)
sink.flush()
Switch to just using `select` directly
This is less efficient, but does let use get the "exceptional" cases
and handle them more pleasantly. | """Communication link driver."""
import sys
import select
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
while True:
readable, writable, exceptional = select.select((socket, source),
(),
(socket, source, sink))
if source in readable:
socket.send(source.readline())
if socket in readable:
sink.write(socket.recv(OUTPUT_BUFFER_SIZE))
sink.flush()
| <commit_before>"""Communication link driver."""
import sys
import selectors
CLIENT_TO_SERVER = object()
SERVER_TO_CLIENT = object()
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
with selectors.DefaultSelector() as selector:
selector.register(source, selectors.EVENT_READ, CLIENT_TO_SERVER)
selector.register(socket, selectors.EVENT_READ, SERVER_TO_CLIENT)
while True:
for key, events in selector.select():
if key.data is CLIENT_TO_SERVER:
data = source.readline()
socket.send(data)
elif key.data is SERVER_TO_CLIENT:
data = socket.recv(OUTPUT_BUFFER_SIZE)
sink.write(data)
sink.flush()
<commit_msg>Switch to just using `select` directly
This is less efficient, but does let use get the "exceptional" cases
and handle them more pleasantly.<commit_after> | """Communication link driver."""
import sys
import select
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
while True:
readable, writable, exceptional = select.select((socket, source),
(),
(socket, source, sink))
if source in readable:
socket.send(source.readline())
if socket in readable:
sink.write(socket.recv(OUTPUT_BUFFER_SIZE))
sink.flush()
| """Communication link driver."""
import sys
import selectors
CLIENT_TO_SERVER = object()
SERVER_TO_CLIENT = object()
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
with selectors.DefaultSelector() as selector:
selector.register(source, selectors.EVENT_READ, CLIENT_TO_SERVER)
selector.register(socket, selectors.EVENT_READ, SERVER_TO_CLIENT)
while True:
for key, events in selector.select():
if key.data is CLIENT_TO_SERVER:
data = source.readline()
socket.send(data)
elif key.data is SERVER_TO_CLIENT:
data = socket.recv(OUTPUT_BUFFER_SIZE)
sink.write(data)
sink.flush()
Switch to just using `select` directly
This is less efficient, but does let use get the "exceptional" cases
and handle them more pleasantly."""Communication link driver."""
import sys
import select
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
while True:
readable, writable, exceptional = select.select((socket, source),
(),
(socket, source, sink))
if source in readable:
socket.send(source.readline())
if socket in readable:
sink.write(socket.recv(OUTPUT_BUFFER_SIZE))
sink.flush()
| <commit_before>"""Communication link driver."""
import sys
import selectors
CLIENT_TO_SERVER = object()
SERVER_TO_CLIENT = object()
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
with selectors.DefaultSelector() as selector:
selector.register(source, selectors.EVENT_READ, CLIENT_TO_SERVER)
selector.register(socket, selectors.EVENT_READ, SERVER_TO_CLIENT)
while True:
for key, events in selector.select():
if key.data is CLIENT_TO_SERVER:
data = source.readline()
socket.send(data)
elif key.data is SERVER_TO_CLIENT:
data = socket.recv(OUTPUT_BUFFER_SIZE)
sink.write(data)
sink.flush()
<commit_msg>Switch to just using `select` directly
This is less efficient, but does let use get the "exceptional" cases
and handle them more pleasantly.<commit_after>"""Communication link driver."""
import sys
import select
def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer):
"""Run communication, in a loop. Input from `source` is sent on `socket`,
and data received on `socket` is forwarded to `sink`.
All file descriptors must be non-blocking.
"""
OUTPUT_BUFFER_SIZE = 1024
while True:
readable, writable, exceptional = select.select((socket, source),
(),
(socket, source, sink))
if source in readable:
socket.send(source.readline())
if socket in readable:
sink.write(socket.recv(OUTPUT_BUFFER_SIZE))
sink.flush()
|
133bddf28eed38273eeb384b152ec35ae861a480 | sunpy/__init__.py | sunpy/__init__.py | """
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
| """
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
try:
_ASTROPY_SETUP_
except NameError:
_ASTROPY_SETUP_ = False
if not _ASTROPY_SETUP_:
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
| Make sure package does not import itself during setup | Make sure package does not import itself during setup
| Python | bsd-2-clause | dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy | """
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
Make sure package does not import itself during setup | """
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
try:
_ASTROPY_SETUP_
except NameError:
_ASTROPY_SETUP_ = False
if not _ASTROPY_SETUP_:
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
| <commit_before>"""
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
<commit_msg>Make sure package does not import itself during setup<commit_after> | """
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
try:
_ASTROPY_SETUP_
except NameError:
_ASTROPY_SETUP_ = False
if not _ASTROPY_SETUP_:
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
| """
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
Make sure package does not import itself during setup"""
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
try:
_ASTROPY_SETUP_
except NameError:
_ASTROPY_SETUP_ = False
if not _ASTROPY_SETUP_:
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
| <commit_before>"""
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
<commit_msg>Make sure package does not import itself during setup<commit_after>"""
SunPy
=====
An open-source Python library for Solar Physics data analysis.
Web Links
---------
Homepage: http://sunpy.org
Documentation: http://docs.sunpy.org/en/stable/
"""
from __future__ import absolute_import
try:
from .version import version as __version__
except ImportError:
__version__ = ''
try:
from .version import githash as __githash__
except ImportError:
__githash__ = ''
try:
_ASTROPY_SETUP_
except NameError:
_ASTROPY_SETUP_ = False
if not _ASTROPY_SETUP_:
import os
from sunpy.util.config import load_config, print_config
from sunpy.util import system_info
from sunpy.tests.runner import SunPyTestRunner
self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__))
# Load user configuration
config = load_config()
__all__ = ['config', 'self_test', 'system_info']
|
0dda4e65d4c15e3654cb77298e008d6f2d1f179b | numpy/_array_api/_dtypes.py | numpy/_array_api/_dtypes.py | import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool]
_boolean_dtypes = [bool]
_floating_dtypes = [float32, float64]
_integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
| import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool)
_boolean_dtypes = (bool)
_floating_dtypes = (float32, float64)
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
| Use tuples for internal type lists in the array API | Use tuples for internal type lists in the array API
These are easier for type checkers to handle.
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool]
_boolean_dtypes = [bool]
_floating_dtypes = [float32, float64]
_integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
Use tuples for internal type lists in the array API
These are easier for type checkers to handle. | import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool)
_boolean_dtypes = (bool)
_floating_dtypes = (float32, float64)
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
| <commit_before>import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool]
_boolean_dtypes = [bool]
_floating_dtypes = [float32, float64]
_integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
<commit_msg>Use tuples for internal type lists in the array API
These are easier for type checkers to handle.<commit_after> | import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool)
_boolean_dtypes = (bool)
_floating_dtypes = (float32, float64)
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
| import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool]
_boolean_dtypes = [bool]
_floating_dtypes = [float32, float64]
_integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
Use tuples for internal type lists in the array API
These are easier for type checkers to handle.import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool)
_boolean_dtypes = (bool)
_floating_dtypes = (float32, float64)
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
| <commit_before>import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool]
_boolean_dtypes = [bool]
_floating_dtypes = [float32, float64]
_integer_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_integer_or_boolean_dtypes = [bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
_numeric_dtypes = [float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64]
<commit_msg>Use tuples for internal type lists in the array API
These are easier for type checkers to handle.<commit_after>import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype('int8')
int16 = np.dtype('int16')
int32 = np.dtype('int32')
int64 = np.dtype('int64')
uint8 = np.dtype('uint8')
uint16 = np.dtype('uint16')
uint32 = np.dtype('uint32')
uint64 = np.dtype('uint64')
float32 = np.dtype('float32')
float64 = np.dtype('float64')
# Note: This name is changed
bool = np.dtype('bool')
_all_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64,
float32, float64, bool)
_boolean_dtypes = (bool)
_floating_dtypes = (float32, float64)
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_integer_or_boolean_dtypes = (bool, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_numeric_dtypes = (float32, float64, int8, int16, int32, int64, uint8, uint16, uint32, uint64)
|
57280453c222dddff6433e234608e89684e79c93 | test_board_pytest.py | test_board_pytest.py | from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
board.addPiece(0, 1)
assert board.boardMatrix.item((4,0)) == 1
| from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((4,0)) == 1
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((3,0)) == 1
assert board.addPiece(1, 1) == True
assert board.boardMatrix.item((4,1)) == 1
assert board.addPiece(4, 1) == True
assert board.boardMatrix.item((4,4)) == 1
| Add more tests for addPiece method. | Add more tests for addPiece method.
| Python | mit | isaacarvestad/four-in-a-row | from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
board.addPiece(0, 1)
assert board.boardMatrix.item((4,0)) == 1
Add more tests for addPiece method. | from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((4,0)) == 1
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((3,0)) == 1
assert board.addPiece(1, 1) == True
assert board.boardMatrix.item((4,1)) == 1
assert board.addPiece(4, 1) == True
assert board.boardMatrix.item((4,4)) == 1
| <commit_before>from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
board.addPiece(0, 1)
assert board.boardMatrix.item((4,0)) == 1
<commit_msg>Add more tests for addPiece method.<commit_after> | from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((4,0)) == 1
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((3,0)) == 1
assert board.addPiece(1, 1) == True
assert board.boardMatrix.item((4,1)) == 1
assert board.addPiece(4, 1) == True
assert board.boardMatrix.item((4,4)) == 1
| from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
board.addPiece(0, 1)
assert board.boardMatrix.item((4,0)) == 1
Add more tests for addPiece method.from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((4,0)) == 1
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((3,0)) == 1
assert board.addPiece(1, 1) == True
assert board.boardMatrix.item((4,1)) == 1
assert board.addPiece(4, 1) == True
assert board.boardMatrix.item((4,4)) == 1
| <commit_before>from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
board.addPiece(0, 1)
assert board.boardMatrix.item((4,0)) == 1
<commit_msg>Add more tests for addPiece method.<commit_after>from board import Board
def test_constructor():
board = Board(0,0)
assert board.boardMatrix.size == 0
assert board.columns == 0
assert board.rows == 0
board = Board(5,5)
assert board.boardMatrix.size == 25
assert board.columns == 5
assert board.rows == 5
def test_addPiece():
board = Board(5,5)
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((4,0)) == 1
assert board.addPiece(0, 1) == True
assert board.boardMatrix.item((3,0)) == 1
assert board.addPiece(1, 1) == True
assert board.boardMatrix.item((4,1)) == 1
assert board.addPiece(4, 1) == True
assert board.boardMatrix.item((4,4)) == 1
|
0575b4345fc21ca537a95866ff2a24d25128c698 | readthedocs/config/find.py | readthedocs/config/find.py | """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_all(path, filename_regex):
"""Find all files in ``path`` that match ``filename_regex`` regex."""
path = os.path.abspath(path)
for root, dirs, files in os.walk(path, topdown=True):
dirs.sort()
for filename in files:
if re.match(filename_regex, filename):
yield os.path.abspath(os.path.join(root, filename))
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
for _path in find_all(path, filename_regex):
return _path
return ''
| """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
_path = os.path.abspath(path)
for filename in os.listdir(_path):
if re.match(filename_regex, filename):
return os.path.join(_path, filename)
return ''
| Remove logic for iterating directories to search for config file | Remove logic for iterating directories to search for config file
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_all(path, filename_regex):
"""Find all files in ``path`` that match ``filename_regex`` regex."""
path = os.path.abspath(path)
for root, dirs, files in os.walk(path, topdown=True):
dirs.sort()
for filename in files:
if re.match(filename_regex, filename):
yield os.path.abspath(os.path.join(root, filename))
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
for _path in find_all(path, filename_regex):
return _path
return ''
Remove logic for iterating directories to search for config file | """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
_path = os.path.abspath(path)
for filename in os.listdir(_path):
if re.match(filename_regex, filename):
return os.path.join(_path, filename)
return ''
| <commit_before>"""Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_all(path, filename_regex):
"""Find all files in ``path`` that match ``filename_regex`` regex."""
path = os.path.abspath(path)
for root, dirs, files in os.walk(path, topdown=True):
dirs.sort()
for filename in files:
if re.match(filename_regex, filename):
yield os.path.abspath(os.path.join(root, filename))
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
for _path in find_all(path, filename_regex):
return _path
return ''
<commit_msg>Remove logic for iterating directories to search for config file<commit_after> | """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
_path = os.path.abspath(path)
for filename in os.listdir(_path):
if re.match(filename_regex, filename):
return os.path.join(_path, filename)
return ''
| """Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_all(path, filename_regex):
"""Find all files in ``path`` that match ``filename_regex`` regex."""
path = os.path.abspath(path)
for root, dirs, files in os.walk(path, topdown=True):
dirs.sort()
for filename in files:
if re.match(filename_regex, filename):
yield os.path.abspath(os.path.join(root, filename))
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
for _path in find_all(path, filename_regex):
return _path
return ''
Remove logic for iterating directories to search for config file"""Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
_path = os.path.abspath(path)
for filename in os.listdir(_path):
if re.match(filename_regex, filename):
return os.path.join(_path, filename)
return ''
| <commit_before>"""Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_all(path, filename_regex):
"""Find all files in ``path`` that match ``filename_regex`` regex."""
path = os.path.abspath(path)
for root, dirs, files in os.walk(path, topdown=True):
dirs.sort()
for filename in files:
if re.match(filename_regex, filename):
yield os.path.abspath(os.path.join(root, filename))
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
for _path in find_all(path, filename_regex):
return _path
return ''
<commit_msg>Remove logic for iterating directories to search for config file<commit_after>"""Helper functions to search files."""
from __future__ import division, print_function, unicode_literals
import os
import re
def find_one(path, filename_regex):
"""Find the first file in ``path`` that match ``filename_regex`` regex."""
_path = os.path.abspath(path)
for filename in os.listdir(_path):
if re.match(filename_regex, filename):
return os.path.join(_path, filename)
return ''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.