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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
952550b344e96236995ac72eaa0777fd356f21e2
|
infinity.py
|
infinity.py
|
try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return False
return self.positive
def __eq__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
inf = Infinity()
|
try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if self == other:
return False
return self.positive
def __eq__(self, other):
if (
isinstance(other, self.__class__) and
other.positive == self.positive
):
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
def __float__(self):
return float(str(self))
def __add__(self, other):
if other == self:
return self
raise NotImplemented
def timetuple(self):
return tuple()
inf = Infinity()
|
Add float coercion, datetime comparison support
|
Add float coercion, datetime comparison support
|
Python
|
bsd-3-clause
|
kvesteri/infinity
|
try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return False
return self.positive
def __eq__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
inf = Infinity()
Add float coercion, datetime comparison support
|
try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if self == other:
return False
return self.positive
def __eq__(self, other):
if (
isinstance(other, self.__class__) and
other.positive == self.positive
):
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
def __float__(self):
return float(str(self))
def __add__(self, other):
if other == self:
return self
raise NotImplemented
def timetuple(self):
return tuple()
inf = Infinity()
|
<commit_before>try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return False
return self.positive
def __eq__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
inf = Infinity()
<commit_msg>Add float coercion, datetime comparison support<commit_after>
|
try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if self == other:
return False
return self.positive
def __eq__(self, other):
if (
isinstance(other, self.__class__) and
other.positive == self.positive
):
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
def __float__(self):
return float(str(self))
def __add__(self, other):
if other == self:
return self
raise NotImplemented
def timetuple(self):
return tuple()
inf = Infinity()
|
try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return False
return self.positive
def __eq__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
inf = Infinity()
Add float coercion, datetime comparison supporttry:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if self == other:
return False
return self.positive
def __eq__(self, other):
if (
isinstance(other, self.__class__) and
other.positive == self.positive
):
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
def __float__(self):
return float(str(self))
def __add__(self, other):
if other == self:
return self
raise NotImplemented
def timetuple(self):
return tuple()
inf = Infinity()
|
<commit_before>try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return False
return self.positive
def __eq__(self, other):
if isinstance(other, self.__class__) and other.positive == self.positive:
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
inf = Infinity()
<commit_msg>Add float coercion, datetime comparison support<commit_after>try:
from functools import total_ordering
except ImportError:
# Use Python 2.6 port
from total_ordering import total_ordering
@total_ordering
class Infinity(object):
"""
An object that is greater than any other object (except itself).
Inspired by https://pypi.python.org/pypi/Extremes
Examples::
Infinity can be compared to any object:
>>> from infinity import inf
>>> import sys
>>> inf > -sys.maxint
True
>>> inf > None
True
>>> inf > ''
True
>>> inf > datetime(2000, 20, 2)
"""
def __init__(self, positive=True):
self.positive = positive
def __neg__(self):
return Infinity(not self.positive)
def __gt__(self, other):
if self == other:
return False
return self.positive
def __eq__(self, other):
if (
isinstance(other, self.__class__) and
other.positive == self.positive
):
return True
return False
def __ne__(self, other):
return not (self == other)
def __bool__(self):
return self.positive
def __nonzero__(self):
return self.positive
def __str__(self):
return '%sinf' % ('' if self.positive else '-')
def __float__(self):
return float(str(self))
def __add__(self, other):
if other == self:
return self
raise NotImplemented
def timetuple(self):
return tuple()
inf = Infinity()
|
8e01ce70a76811152a86c461fc7235a58dc7f5e3
|
cc/license/formatters/rdfa.py
|
cc/license/formatters/rdfa.py
|
from cc.license.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
|
from cc.license.lib.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
|
Make imports work for formatters module.
|
Make imports work for formatters module.
|
Python
|
mit
|
creativecommons/cc.license,creativecommons/cc.license
|
from cc.license.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
Make imports work for formatters module.
|
from cc.license.lib.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
|
<commit_before>from cc.license.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
<commit_msg>Make imports work for formatters module.<commit_after>
|
from cc.license.lib.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
|
from cc.license.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
Make imports work for formatters module.from cc.license.lib.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
|
<commit_before>from cc.license.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
<commit_msg>Make imports work for formatters module.<commit_after>from cc.license.lib.interfaces import ILicenseFormatter
import zope.interface
class Formatter(object):
zope.interface.implements(ILicenseFormatter)
id = "HTML + RDFa formatter"
def format(self, license, work_dict = {}, locale = 'en'):
"""Return a string serialization for the license, optionally
incorporating the work metadata and locale."""
raise NotImplementedYet # !
|
4334cbf05da1c1f6a6a984e1a062a7e8f252b664
|
components/includes/utilities.py
|
components/includes/utilities.py
|
import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
|
import random
import json
import time
import socket
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
|
Clean up, comments, liveness checking, robust data transfer
|
Clean up, comments, liveness checking, robust data transfer
|
Python
|
bsd-2-clause
|
mavroudisv/Crux
|
import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
Clean up, comments, liveness checking, robust data transfer
|
import random
import json
import time
import socket
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
|
<commit_before>import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
<commit_msg>Clean up, comments, liveness checking, robust data transfer<commit_after>
|
import random
import json
import time
import socket
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
|
import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
Clean up, comments, liveness checking, robust data transferimport random
import json
import time
import socket
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
|
<commit_before>import random
import json
import time
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
<commit_msg>Clean up, comments, liveness checking, robust data transfer<commit_after>import random
import json
import time
import socket
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if multiping(port, machines):
success = True
break
except Exception as e:
print str(e)
time.sleep(1)
attempted += 1
return success
|
c538e1a673e208030db04ab9ad3b97e962f3e2ac
|
download_summaries.py
|
download_summaries.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# setting target dir and time interval of interest
tgt_dir = r"D:\nhl\official_and_json\2016-17"
tgt_dir = r"d:\tmp\test"
date = "2017/05/01"
to_date = "2017/05/01"
downloader = SummaryDownloader(tgt_dir, date, to_date, workers=8)
downloader.run()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
from datetime import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# retrieving arguments specified on command line
parser = argparse.ArgumentParser(
description='Download NHL game summary reports.')
parser.add_argument(
'-d', '--tgt_dir', dest='tgt_dir', required=True,
metavar='download target directory',
help="Target directories for downloads")
parser.add_argument(
'-f', '--from', dest='from_date', required=False,
metavar='first date to download summaries for',
help="The first date summaries will be downloaded for")
parser.add_argument(
'-t', '--to', dest='to_date', required=False,
metavar='last date to download summaries for',
help="The last date summaries will be downloaded for")
args = parser.parse_args()
# setting target dir and time interval of interest
tgt_dir = args.tgt_dir
from_date = args.from_date
to_date = args.to_date
# setting first date to download summaries for if not specified
if from_date is None:
# using previously downloaded files in target directory to retrieve
# last date data have already been downloaded before
all_dates = list()
for root, dirs, files in os.walk(tgt_dir):
for file in files:
if file.lower().endswith(".zip") and file.lower()[0].isdigit():
try:
curr_date = parse(os.path.basename(file.split(".")[0]))
all_dates.append(curr_date)
except:
pass
from_date = (sorted(all_dates)[-1] + relativedelta(days=1)).strftime(
"%B %d, %Y")
# setting last date to download summaries for...
if to_date is None:
# ...to same as first date to download summaries for if this one is set
if args.from_date:
to_date = from_date
# ...to date before current one otherwise
else:
to_date = (datetime.now() + relativedelta(days=-1)).strftime(
"%B %d, %Y")
downloader = SummaryDownloader(tgt_dir, from_date, to_date, workers=8)
downloader.run()
|
Allow control of download process via command line
|
Allow control of download process via command line
|
Python
|
mit
|
leaffan/pynhldb
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# setting target dir and time interval of interest
tgt_dir = r"D:\nhl\official_and_json\2016-17"
tgt_dir = r"d:\tmp\test"
date = "2017/05/01"
to_date = "2017/05/01"
downloader = SummaryDownloader(tgt_dir, date, to_date, workers=8)
downloader.run()
Allow control of download process via command line
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
from datetime import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# retrieving arguments specified on command line
parser = argparse.ArgumentParser(
description='Download NHL game summary reports.')
parser.add_argument(
'-d', '--tgt_dir', dest='tgt_dir', required=True,
metavar='download target directory',
help="Target directories for downloads")
parser.add_argument(
'-f', '--from', dest='from_date', required=False,
metavar='first date to download summaries for',
help="The first date summaries will be downloaded for")
parser.add_argument(
'-t', '--to', dest='to_date', required=False,
metavar='last date to download summaries for',
help="The last date summaries will be downloaded for")
args = parser.parse_args()
# setting target dir and time interval of interest
tgt_dir = args.tgt_dir
from_date = args.from_date
to_date = args.to_date
# setting first date to download summaries for if not specified
if from_date is None:
# using previously downloaded files in target directory to retrieve
# last date data have already been downloaded before
all_dates = list()
for root, dirs, files in os.walk(tgt_dir):
for file in files:
if file.lower().endswith(".zip") and file.lower()[0].isdigit():
try:
curr_date = parse(os.path.basename(file.split(".")[0]))
all_dates.append(curr_date)
except:
pass
from_date = (sorted(all_dates)[-1] + relativedelta(days=1)).strftime(
"%B %d, %Y")
# setting last date to download summaries for...
if to_date is None:
# ...to same as first date to download summaries for if this one is set
if args.from_date:
to_date = from_date
# ...to date before current one otherwise
else:
to_date = (datetime.now() + relativedelta(days=-1)).strftime(
"%B %d, %Y")
downloader = SummaryDownloader(tgt_dir, from_date, to_date, workers=8)
downloader.run()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# setting target dir and time interval of interest
tgt_dir = r"D:\nhl\official_and_json\2016-17"
tgt_dir = r"d:\tmp\test"
date = "2017/05/01"
to_date = "2017/05/01"
downloader = SummaryDownloader(tgt_dir, date, to_date, workers=8)
downloader.run()
<commit_msg>Allow control of download process via command line<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
from datetime import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# retrieving arguments specified on command line
parser = argparse.ArgumentParser(
description='Download NHL game summary reports.')
parser.add_argument(
'-d', '--tgt_dir', dest='tgt_dir', required=True,
metavar='download target directory',
help="Target directories for downloads")
parser.add_argument(
'-f', '--from', dest='from_date', required=False,
metavar='first date to download summaries for',
help="The first date summaries will be downloaded for")
parser.add_argument(
'-t', '--to', dest='to_date', required=False,
metavar='last date to download summaries for',
help="The last date summaries will be downloaded for")
args = parser.parse_args()
# setting target dir and time interval of interest
tgt_dir = args.tgt_dir
from_date = args.from_date
to_date = args.to_date
# setting first date to download summaries for if not specified
if from_date is None:
# using previously downloaded files in target directory to retrieve
# last date data have already been downloaded before
all_dates = list()
for root, dirs, files in os.walk(tgt_dir):
for file in files:
if file.lower().endswith(".zip") and file.lower()[0].isdigit():
try:
curr_date = parse(os.path.basename(file.split(".")[0]))
all_dates.append(curr_date)
except:
pass
from_date = (sorted(all_dates)[-1] + relativedelta(days=1)).strftime(
"%B %d, %Y")
# setting last date to download summaries for...
if to_date is None:
# ...to same as first date to download summaries for if this one is set
if args.from_date:
to_date = from_date
# ...to date before current one otherwise
else:
to_date = (datetime.now() + relativedelta(days=-1)).strftime(
"%B %d, %Y")
downloader = SummaryDownloader(tgt_dir, from_date, to_date, workers=8)
downloader.run()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# setting target dir and time interval of interest
tgt_dir = r"D:\nhl\official_and_json\2016-17"
tgt_dir = r"d:\tmp\test"
date = "2017/05/01"
to_date = "2017/05/01"
downloader = SummaryDownloader(tgt_dir, date, to_date, workers=8)
downloader.run()
Allow control of download process via command line#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
from datetime import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# retrieving arguments specified on command line
parser = argparse.ArgumentParser(
description='Download NHL game summary reports.')
parser.add_argument(
'-d', '--tgt_dir', dest='tgt_dir', required=True,
metavar='download target directory',
help="Target directories for downloads")
parser.add_argument(
'-f', '--from', dest='from_date', required=False,
metavar='first date to download summaries for',
help="The first date summaries will be downloaded for")
parser.add_argument(
'-t', '--to', dest='to_date', required=False,
metavar='last date to download summaries for',
help="The last date summaries will be downloaded for")
args = parser.parse_args()
# setting target dir and time interval of interest
tgt_dir = args.tgt_dir
from_date = args.from_date
to_date = args.to_date
# setting first date to download summaries for if not specified
if from_date is None:
# using previously downloaded files in target directory to retrieve
# last date data have already been downloaded before
all_dates = list()
for root, dirs, files in os.walk(tgt_dir):
for file in files:
if file.lower().endswith(".zip") and file.lower()[0].isdigit():
try:
curr_date = parse(os.path.basename(file.split(".")[0]))
all_dates.append(curr_date)
except:
pass
from_date = (sorted(all_dates)[-1] + relativedelta(days=1)).strftime(
"%B %d, %Y")
# setting last date to download summaries for...
if to_date is None:
# ...to same as first date to download summaries for if this one is set
if args.from_date:
to_date = from_date
# ...to date before current one otherwise
else:
to_date = (datetime.now() + relativedelta(days=-1)).strftime(
"%B %d, %Y")
downloader = SummaryDownloader(tgt_dir, from_date, to_date, workers=8)
downloader.run()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# setting target dir and time interval of interest
tgt_dir = r"D:\nhl\official_and_json\2016-17"
tgt_dir = r"d:\tmp\test"
date = "2017/05/01"
to_date = "2017/05/01"
downloader = SummaryDownloader(tgt_dir, date, to_date, workers=8)
downloader.run()
<commit_msg>Allow control of download process via command line<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
from datetime import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from utils.summary_downloader import SummaryDownloader
if __name__ == '__main__':
# retrieving arguments specified on command line
parser = argparse.ArgumentParser(
description='Download NHL game summary reports.')
parser.add_argument(
'-d', '--tgt_dir', dest='tgt_dir', required=True,
metavar='download target directory',
help="Target directories for downloads")
parser.add_argument(
'-f', '--from', dest='from_date', required=False,
metavar='first date to download summaries for',
help="The first date summaries will be downloaded for")
parser.add_argument(
'-t', '--to', dest='to_date', required=False,
metavar='last date to download summaries for',
help="The last date summaries will be downloaded for")
args = parser.parse_args()
# setting target dir and time interval of interest
tgt_dir = args.tgt_dir
from_date = args.from_date
to_date = args.to_date
# setting first date to download summaries for if not specified
if from_date is None:
# using previously downloaded files in target directory to retrieve
# last date data have already been downloaded before
all_dates = list()
for root, dirs, files in os.walk(tgt_dir):
for file in files:
if file.lower().endswith(".zip") and file.lower()[0].isdigit():
try:
curr_date = parse(os.path.basename(file.split(".")[0]))
all_dates.append(curr_date)
except:
pass
from_date = (sorted(all_dates)[-1] + relativedelta(days=1)).strftime(
"%B %d, %Y")
# setting last date to download summaries for...
if to_date is None:
# ...to same as first date to download summaries for if this one is set
if args.from_date:
to_date = from_date
# ...to date before current one otherwise
else:
to_date = (datetime.now() + relativedelta(days=-1)).strftime(
"%B %d, %Y")
downloader = SummaryDownloader(tgt_dir, from_date, to_date, workers=8)
downloader.run()
|
2f5417811eb8048659bd9b5408c721d481af4ece
|
tests/python-support/experiments.py
|
tests/python-support/experiments.py
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path() ]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
return json.loads(result.stdout)
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path()]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
try:
return json.loads(result.stdout)
except json.JSONDecodeError as err:
import sys
document = err.doc
print("Failed to parse output from experiment. Document was: \n\n{}".format(document),
file=sys.stderr)
raise err
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
Print JSON document upon parse error
|
Print JSON document upon parse error
|
Python
|
mit
|
Andlon/crest,Andlon/crest,Andlon/crest
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path() ]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
return json.loads(result.stdout)
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
Print JSON document upon parse error
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path()]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
try:
return json.loads(result.stdout)
except json.JSONDecodeError as err:
import sys
document = err.doc
print("Failed to parse output from experiment. Document was: \n\n{}".format(document),
file=sys.stderr)
raise err
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
<commit_before>import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path() ]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
return json.loads(result.stdout)
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
<commit_msg>Print JSON document upon parse error<commit_after>
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path()]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
try:
return json.loads(result.stdout)
except json.JSONDecodeError as err:
import sys
document = err.doc
print("Failed to parse output from experiment. Document was: \n\n{}".format(document),
file=sys.stderr)
raise err
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path() ]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
return json.loads(result.stdout)
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
Print JSON document upon parse errorimport os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path()]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
try:
return json.loads(result.stdout)
except json.JSONDecodeError as err:
import sys
document = err.doc
print("Failed to parse output from experiment. Document was: \n\n{}".format(document),
file=sys.stderr)
raise err
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
<commit_before>import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path() ]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
return json.loads(result.stdout)
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
<commit_msg>Print JSON document upon parse error<commit_after>import os
import subprocess
import json
def _experiment_runner_path():
this_path = os.path.dirname(os.path.realpath(__file__))
return this_path + "/../../target/release/experiments"
def run_experiment(params):
args = [_experiment_runner_path()]
result = subprocess.run(args=args,
input=json.dumps(params, indent=4),
stdout=subprocess.PIPE,
universal_newlines=True)
try:
return json.loads(result.stdout)
except json.JSONDecodeError as err:
import sys
document = err.doc
print("Failed to parse output from experiment. Document was: \n\n{}".format(document),
file=sys.stderr)
raise err
def run_experiments(param_collection):
return [run_experiment(param) for param in param_collection]
|
c55d0ff6071c5b96125160da1e911419ee70314c
|
ditto/configuration/urls.py
|
ditto/configuration/urls.py
|
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/(\w+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
|
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/([\w\-]+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
|
Fix chatroom url pattern to include '-'
|
Fix chatroom url pattern to include '-'
|
Python
|
bsd-3-clause
|
Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto
|
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/(\w+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
Fix chatroom url pattern to include '-'
|
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/([\w\-]+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
|
<commit_before>from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/(\w+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
<commit_msg>Fix chatroom url pattern to include '-'<commit_after>
|
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/([\w\-]+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
|
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/(\w+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
Fix chatroom url pattern to include '-'from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/([\w\-]+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
|
<commit_before>from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/(\w+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
<commit_msg>Fix chatroom url pattern to include '-'<commit_after>from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex=r'^step([1234])/$',
view=views.edit_initial_config,
name='initialconfig'
),
url(r'^debug/start-again/$',
views.start_again,
name="start-again"),
url(
regex=r'^(basicinfo|permissions|features)/$',
view=views.edit_config,
name='editconfig'
),
url(
regex=r'^roles/$',
view=views.roles,
name='settings'
),
url(
regex=r'^roles/(\d+)/delete/$',
view=views.delete_role,
name='delete-role'
),
url(
regex=r'^evaluation/$',
view=views.evaluation,
name='evaluation'
),
url(
regex=r'^chatroom/$',
view=views.chatroom,
name='chatroom_config'
),
url(
regex=r'^chatroom/([\w\-]+)/$',
view=views.chatroom,
name='chatroom_config_room'
),
)
|
fcfc9165526daf69d73a3822684efb8098fbb9d1
|
moment_polytopes/__init__.py
|
moment_polytopes/__init__.py
|
from __future__ import absolute_import, print_function
__version__ = '1.0-dev'
|
from __future__ import absolute_import, print_function
__version__ = '1.0.dev0'
|
Use appropriate version naming scheme.
|
Use appropriate version naming scheme.
|
Python
|
mit
|
catch22/moment_polytopes
|
from __future__ import absolute_import, print_function
__version__ = '1.0-dev'
Use appropriate version naming scheme.
|
from __future__ import absolute_import, print_function
__version__ = '1.0.dev0'
|
<commit_before>from __future__ import absolute_import, print_function
__version__ = '1.0-dev'
<commit_msg>Use appropriate version naming scheme.<commit_after>
|
from __future__ import absolute_import, print_function
__version__ = '1.0.dev0'
|
from __future__ import absolute_import, print_function
__version__ = '1.0-dev'
Use appropriate version naming scheme.from __future__ import absolute_import, print_function
__version__ = '1.0.dev0'
|
<commit_before>from __future__ import absolute_import, print_function
__version__ = '1.0-dev'
<commit_msg>Use appropriate version naming scheme.<commit_after>from __future__ import absolute_import, print_function
__version__ = '1.0.dev0'
|
cc2fcbf73b0f3eb6ddfee2b55edc6239df3171e0
|
bower/commands/install.py
|
bower/commands/install.py
|
import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
self.fileList.append([package['name'], package['url']])
self.window.show_quick_panel(self.fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})
|
import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
fileList.append([package['name'], package['url']])
self.window.show_quick_panel(fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})
|
Correct my cowboy fix that broke.
|
Correct my cowboy fix that broke.
|
Python
|
mit
|
benschwarz/sublime-bower,ebidel/sublime-bower
|
import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
self.fileList.append([package['name'], package['url']])
self.window.show_quick_panel(self.fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})Correct my cowboy fix that broke.
|
import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
fileList.append([package['name'], package['url']])
self.window.show_quick_panel(fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})
|
<commit_before>import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
self.fileList.append([package['name'], package['url']])
self.window.show_quick_panel(self.fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})<commit_msg>Correct my cowboy fix that broke.<commit_after>
|
import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
fileList.append([package['name'], package['url']])
self.window.show_quick_panel(fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})
|
import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
self.fileList.append([package['name'], package['url']])
self.window.show_quick_panel(self.fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})Correct my cowboy fix that broke.import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
fileList.append([package['name'], package['url']])
self.window.show_quick_panel(fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})
|
<commit_before>import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
self.fileList.append([package['name'], package['url']])
self.window.show_quick_panel(self.fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})<commit_msg>Correct my cowboy fix that broke.<commit_after>import sublime_plugin
from bower.utils.api import API
class InstallCommand(sublime_plugin.WindowCommand):
def run(self, *args, **kwargs):
self.list_packages()
def list_packages(self):
fileList = []
packages = API().get('packages')
packages.reverse()
for package in packages:
fileList.append([package['name'], package['url']])
self.window.show_quick_panel(fileList, self.get_file)
def get_file(self, index):
if (index > -1):
if not self.window.views():
self.window.new_file()
name = self.fileList[index][0]
cwd = self.window.folders()[0]
self.window.run_command("download_package", {"pkg_name": name, "cwd": cwd})
|
969a36dc68ba9675b790f6712405ceb272cf7cbd
|
easy_thumbnails/__init__.py
|
easy_thumbnails/__init__.py
|
VERSION = (1, 0, 'alpha', 14)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
|
VERSION = (1, 0, 'alpha', 15)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
|
Bump the number for a minor release to fix the mysql migrations issue.
|
Bump the number for a minor release to fix the mysql migrations issue.
|
Python
|
bsd-3-clause
|
emschorsch/easy-thumbnails,siovene/easy-thumbnails,jrief/easy-thumbnails,Mactory/easy-thumbnails,jrief/easy-thumbnails,jaddison/easy-thumbnails,sandow-digital/easy-thumbnails-cropman,sandow-digital/easy-thumbnails-cropman,emschorsch/easy-thumbnails,SmileyChris/easy-thumbnails
|
VERSION = (1, 0, 'alpha', 14)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
Bump the number for a minor release to fix the mysql migrations issue.
|
VERSION = (1, 0, 'alpha', 15)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
|
<commit_before>VERSION = (1, 0, 'alpha', 14)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
<commit_msg>Bump the number for a minor release to fix the mysql migrations issue.<commit_after>
|
VERSION = (1, 0, 'alpha', 15)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
|
VERSION = (1, 0, 'alpha', 14)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
Bump the number for a minor release to fix the mysql migrations issue.VERSION = (1, 0, 'alpha', 15)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
|
<commit_before>VERSION = (1, 0, 'alpha', 14)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
<commit_msg>Bump the number for a minor release to fix the mysql migrations issue.<commit_after>VERSION = (1, 0, 'alpha', 15)
def get_version(join=' ', short=False):
"""
Return the version of this package as a string.
The version number is built from a ``VERSION`` tuple, which should consist
of integers, or trailing version information (such as 'alpha', 'beta' or
'final'). For example:
>>> VERSION = (2, 0, 6)
>>> get_version()
'2.0.6'
>>> VERSION = (1, 0, 'beta', 2)
>>> get_version()
'1.0 beta 2'
Use the ``join`` argument to join the version elements by an alternate
character to the default ``' '``. This is useful when building a distutils
setup module::
from this_package import get_version
setup(
version=get_version(join='-'),
# ...
)
Use the ``short`` argument to get the version number without trailing
version information.
"""
version = []
number = []
remainder = []
for i, bit in enumerate(VERSION):
if isinstance(bit, int):
number.append(str(bit))
else:
remainder = [str(bit) for bit in VERSION[i:]]
break
if number:
version.append('.'.join(number))
if not short:
if remainder == ['alpha', 0]:
version.append('pre-alpha')
elif 'final' not in remainder:
version.extend(remainder)
return join.join(version)
|
dd9fb6cf515d9e7ceb26cc6f7e8fd869d721552c
|
shop/models/fields.py
|
shop/models/fields.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql':
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
postgresql_engine_names = [
'django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2',
]
if settings.DATABASES['default']['ENGINE'] in postgresql_engine_names:
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
|
Check for older Postgresql engine name for JSONField
|
Check for older Postgresql engine name for JSONField
The Postgresql database engine name was changed from
'django.db.backends.postgresql_psycopg2' to
'django.db.backends.postgresql' in Django 1.9. However, the former name
still works in newer versions of Django for compatibility reasons. This
value should also be checked when deciding which JSONField to use, since
it is common in older projects that have upgraded from previous versions
of Django.
See the link below for more information:
https://docs.djangoproject.com/en/1.9/ref/settings/#engine
|
Python
|
bsd-3-clause
|
divio/django-shop,khchine5/django-shop,nimbis/django-shop,khchine5/django-shop,khchine5/django-shop,awesto/django-shop,khchine5/django-shop,awesto/django-shop,awesto/django-shop,divio/django-shop,nimbis/django-shop,divio/django-shop,nimbis/django-shop,nimbis/django-shop
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql':
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
Check for older Postgresql engine name for JSONField
The Postgresql database engine name was changed from
'django.db.backends.postgresql_psycopg2' to
'django.db.backends.postgresql' in Django 1.9. However, the former name
still works in newer versions of Django for compatibility reasons. This
value should also be checked when deciding which JSONField to use, since
it is common in older projects that have upgraded from previous versions
of Django.
See the link below for more information:
https://docs.djangoproject.com/en/1.9/ref/settings/#engine
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
postgresql_engine_names = [
'django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2',
]
if settings.DATABASES['default']['ENGINE'] in postgresql_engine_names:
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql':
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
<commit_msg>Check for older Postgresql engine name for JSONField
The Postgresql database engine name was changed from
'django.db.backends.postgresql_psycopg2' to
'django.db.backends.postgresql' in Django 1.9. However, the former name
still works in newer versions of Django for compatibility reasons. This
value should also be checked when deciding which JSONField to use, since
it is common in older projects that have upgraded from previous versions
of Django.
See the link below for more information:
https://docs.djangoproject.com/en/1.9/ref/settings/#engine<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
postgresql_engine_names = [
'django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2',
]
if settings.DATABASES['default']['ENGINE'] in postgresql_engine_names:
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql':
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
Check for older Postgresql engine name for JSONField
The Postgresql database engine name was changed from
'django.db.backends.postgresql_psycopg2' to
'django.db.backends.postgresql' in Django 1.9. However, the former name
still works in newer versions of Django for compatibility reasons. This
value should also be checked when deciding which JSONField to use, since
it is common in older projects that have upgraded from previous versions
of Django.
See the link below for more information:
https://docs.djangoproject.com/en/1.9/ref/settings/#engine# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
postgresql_engine_names = [
'django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2',
]
if settings.DATABASES['default']['ENGINE'] in postgresql_engine_names:
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.postgresql':
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
<commit_msg>Check for older Postgresql engine name for JSONField
The Postgresql database engine name was changed from
'django.db.backends.postgresql_psycopg2' to
'django.db.backends.postgresql' in Django 1.9. However, the former name
still works in newer versions of Django for compatibility reasons. This
value should also be checked when deciding which JSONField to use, since
it is common in older projects that have upgraded from previous versions
of Django.
See the link below for more information:
https://docs.djangoproject.com/en/1.9/ref/settings/#engine<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
postgresql_engine_names = [
'django.db.backends.postgresql',
'django.db.backends.postgresql_psycopg2',
]
if settings.DATABASES['default']['ENGINE'] in postgresql_engine_names:
from django.contrib.postgres.fields import JSONField as _JSONField
else:
from jsonfield.fields import JSONField as _JSONField
class JSONField(_JSONField):
def __init__(self, *args, **kwargs):
kwargs.update({'default': {}})
super(JSONField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(JSONField, self).deconstruct()
del kwargs['default']
return name, path, args, kwargs
|
adc5c00f5496fed8b0b1b4c523737cfbaf688945
|
shortuuid/__init__.py
|
shortuuid/__init__.py
|
from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.2"
|
from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.3"
|
Change to the correct version.
|
Change to the correct version.
|
Python
|
bsd-3-clause
|
skorokithakis/shortuuid,stochastic-technologies/shortuuid
|
from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.2"
Change to the correct version.
|
from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.3"
|
<commit_before>from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.2"
<commit_msg>Change to the correct version.<commit_after>
|
from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.3"
|
from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.2"
Change to the correct version.from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.3"
|
<commit_before>from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.2"
<commit_msg>Change to the correct version.<commit_after>from shortuuid.main import (
encode,
decode,
uuid,
random,
get_alphabet,
set_alphabet,
ShortUUID,
)
__version__ = "0.4.3"
|
74f26f0c0a0cb014539212f5b7a703d436b29f29
|
backend/globaleaks/jobs/base.py
|
backend/globaleaks/jobs/base.py
|
# -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
try:
self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
def operation(self):
pass # dummy skel for GLJob objects
|
# -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
ret = None
try:
ret = self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
return ret
def operation(self):
pass # dummy skel for GLJob objects
|
Patch job scheduler avoiding possibilities for concurrent runs of the same
|
Patch job scheduler avoiding possibilities for concurrent runs of the same
|
Python
|
agpl-3.0
|
vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks
|
# -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
try:
self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
def operation(self):
pass # dummy skel for GLJob objects
Patch job scheduler avoiding possibilities for concurrent runs of the same
|
# -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
ret = None
try:
ret = self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
return ret
def operation(self):
pass # dummy skel for GLJob objects
|
<commit_before># -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
try:
self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
def operation(self):
pass # dummy skel for GLJob objects
<commit_msg>Patch job scheduler avoiding possibilities for concurrent runs of the same<commit_after>
|
# -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
ret = None
try:
ret = self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
return ret
def operation(self):
pass # dummy skel for GLJob objects
|
# -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
try:
self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
def operation(self):
pass # dummy skel for GLJob objects
Patch job scheduler avoiding possibilities for concurrent runs of the same# -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
ret = None
try:
ret = self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
return ret
def operation(self):
pass # dummy skel for GLJob objects
|
<commit_before># -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
try:
self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
def operation(self):
pass # dummy skel for GLJob objects
<commit_msg>Patch job scheduler avoiding possibilities for concurrent runs of the same<commit_after># -*- coding: UTF-8
# jobs/base
# *********
#
# Base class for implement the scheduled tasks
import sys
from twisted.internet import task
from twisted.python.failure import Failure
from globaleaks.utils.utility import log
from globaleaks.utils.mailutils import mail_exception
class GLJob(task.LoopingCall):
def __init__(self):
task.LoopingCall.__init__(self, self._operation)
def _operation(self):
ret = None
try:
ret = self.operation()
except Exception as e:
log.err("Exception while performin scheduled operation %s: %s" % \
(type(self).__name__, e))
try:
if isinstance(e, Failure):
exc_type = e.type
exc_value = e.value
exc_tb = e.getTracebackObject()
else:
exc_type, exc_value, exc_tb = sys.exc_info()
mail_exception(exc_type, exc_value, exc_tb)
except Exception:
pass
return ret
def operation(self):
pass # dummy skel for GLJob objects
|
0b53adc34259fedc23e42e7576517fb62f4cb33e
|
base_contact/models/ir_model.py
|
base_contact/models/ir_model.py
|
# -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.warning("This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
|
# -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.info("WARNING: This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
|
Downgrade to INFO, since runbots install this.
|
Downgrade to INFO, since runbots install this.
|
Python
|
agpl-3.0
|
open-synergy/partner-contact,acsone/partner-contact,diagramsoftware/partner-contact
|
# -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.warning("This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
Downgrade to INFO, since runbots install this.
|
# -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.info("WARNING: This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
|
<commit_before># -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.warning("This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
<commit_msg>Downgrade to INFO, since runbots install this.<commit_after>
|
# -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.info("WARNING: This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
|
# -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.warning("This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
Downgrade to INFO, since runbots install this.# -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.info("WARNING: This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
|
<commit_before># -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.warning("This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
<commit_msg>Downgrade to INFO, since runbots install this.<commit_after># -*- coding: utf-8 -*-
# © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import api, models
_logger = logging.getLogger(__name__)
class IrModel(models.Model):
_inherit = "ir.model"
@api.cr
def _register_hook(self, cr):
"""Only warn in installed instances."""
_logger.info("WARNING: This module is DEPRECATED. See README.")
return super(IrModel, self)._register_hook(cr)
|
4178bb331014089c69df81b8a99204c94b6e200f
|
eventsource_parser.py
|
eventsource_parser.py
|
from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
lines = source.splitlines()
for line in lines:
if dispatch:
extra += line + '\n'
continue
if not line:
dispatch = True
continue
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
|
from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
cursor = 0
lines = source.splitlines()
for line in lines:
if not line:
dispatch = True
extra = source[cursor+1:]
break
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
cursor += len(line) + 1
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
|
Fix extra in case of fragmented sources
|
Fix extra in case of fragmented sources
|
Python
|
apache-2.0
|
tOkeshu/eventsource-parser
|
from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
lines = source.splitlines()
for line in lines:
if dispatch:
extra += line + '\n'
continue
if not line:
dispatch = True
continue
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
Fix extra in case of fragmented sources
|
from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
cursor = 0
lines = source.splitlines()
for line in lines:
if not line:
dispatch = True
extra = source[cursor+1:]
break
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
cursor += len(line) + 1
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
|
<commit_before>from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
lines = source.splitlines()
for line in lines:
if dispatch:
extra += line + '\n'
continue
if not line:
dispatch = True
continue
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
<commit_msg>Fix extra in case of fragmented sources<commit_after>
|
from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
cursor = 0
lines = source.splitlines()
for line in lines:
if not line:
dispatch = True
extra = source[cursor+1:]
break
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
cursor += len(line) + 1
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
|
from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
lines = source.splitlines()
for line in lines:
if dispatch:
extra += line + '\n'
continue
if not line:
dispatch = True
continue
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
Fix extra in case of fragmented sourcesfrom collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
cursor = 0
lines = source.splitlines()
for line in lines:
if not line:
dispatch = True
extra = source[cursor+1:]
break
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
cursor += len(line) + 1
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
|
<commit_before>from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
lines = source.splitlines()
for line in lines:
if dispatch:
extra += line + '\n'
continue
if not line:
dispatch = True
continue
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
<commit_msg>Fix extra in case of fragmented sources<commit_after>from collections import namedtuple
Event = namedtuple('Event', ['id', 'type', 'data'])
def parse(source):
eid = None
etype = None
data = []
retry = None
extra = ''
dispatch = False
cursor = 0
lines = source.splitlines()
for line in lines:
if not line:
dispatch = True
extra = source[cursor+1:]
break
if not ':' in line:
field, value = line, ''
else:
field, value = line.split(':', 1)
if value and value[0] == ' ':
value = value[1:]
if field == 'data':
data.append(value)
elif field == 'event':
etype = value
elif field == 'id':
eid = value
elif field == 'retry':
retry = int(value)
cursor += len(line) + 1
if not dispatch:
return None, source
if data:
data = '\n'.join(data)
if retry:
if etype or data:
extra = ('retry: %s\n\n' % retry) + extra
else:
etype, data = 'retry', retry
return Event(eid, etype, data), extra
|
5e3a9ad00558547475e7b5674bb623cafc99643a
|
data_exploration.py
|
data_exploration.py
|
# importing modules/ libraries
import pandas as pd
import random
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
#n = 32434489
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__prior_df = pd.read_csv('Data/order_products__prior.csv')
print(order_products__prior_df.head())
#n = 1384617
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__train_df = pd.read_csv('Data/order_products__train.csv')
print(order_products__train_df.head())
#n = 3421083
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
orders_df = pd.read_csv('Data/orders.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())
|
# importing modules/ libraries
import pandas as pd
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
order_products__prior_df = pd.read_csv('Data/order_products__prior_sample.csv')
print(order_products__prior_df.head())
order_products__train_df = pd.read_csv('Data/order_products__train_sample.csv')
print(order_products__train_df.head())
orders_df = pd.read_csv('Data/orders_sample.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())
|
Update data explorations data sets to samples
|
fix: Update data explorations data sets to samples
|
Python
|
mit
|
rjegankumar/instacart_prediction_model
|
# importing modules/ libraries
import pandas as pd
import random
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
#n = 32434489
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__prior_df = pd.read_csv('Data/order_products__prior.csv')
print(order_products__prior_df.head())
#n = 1384617
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__train_df = pd.read_csv('Data/order_products__train.csv')
print(order_products__train_df.head())
#n = 3421083
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
orders_df = pd.read_csv('Data/orders.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())fix: Update data explorations data sets to samples
|
# importing modules/ libraries
import pandas as pd
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
order_products__prior_df = pd.read_csv('Data/order_products__prior_sample.csv')
print(order_products__prior_df.head())
order_products__train_df = pd.read_csv('Data/order_products__train_sample.csv')
print(order_products__train_df.head())
orders_df = pd.read_csv('Data/orders_sample.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())
|
<commit_before># importing modules/ libraries
import pandas as pd
import random
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
#n = 32434489
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__prior_df = pd.read_csv('Data/order_products__prior.csv')
print(order_products__prior_df.head())
#n = 1384617
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__train_df = pd.read_csv('Data/order_products__train.csv')
print(order_products__train_df.head())
#n = 3421083
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
orders_df = pd.read_csv('Data/orders.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())<commit_msg>fix: Update data explorations data sets to samples<commit_after>
|
# importing modules/ libraries
import pandas as pd
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
order_products__prior_df = pd.read_csv('Data/order_products__prior_sample.csv')
print(order_products__prior_df.head())
order_products__train_df = pd.read_csv('Data/order_products__train_sample.csv')
print(order_products__train_df.head())
orders_df = pd.read_csv('Data/orders_sample.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())
|
# importing modules/ libraries
import pandas as pd
import random
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
#n = 32434489
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__prior_df = pd.read_csv('Data/order_products__prior.csv')
print(order_products__prior_df.head())
#n = 1384617
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__train_df = pd.read_csv('Data/order_products__train.csv')
print(order_products__train_df.head())
#n = 3421083
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
orders_df = pd.read_csv('Data/orders.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())fix: Update data explorations data sets to samples# importing modules/ libraries
import pandas as pd
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
order_products__prior_df = pd.read_csv('Data/order_products__prior_sample.csv')
print(order_products__prior_df.head())
order_products__train_df = pd.read_csv('Data/order_products__train_sample.csv')
print(order_products__train_df.head())
orders_df = pd.read_csv('Data/orders_sample.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())
|
<commit_before># importing modules/ libraries
import pandas as pd
import random
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
#n = 32434489
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__prior_df = pd.read_csv('Data/order_products__prior.csv')
print(order_products__prior_df.head())
#n = 1384617
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
order_products__train_df = pd.read_csv('Data/order_products__train.csv')
print(order_products__train_df.head())
#n = 3421083
#s = round(0.1 * n)
#skip = sorted(random.sample(range(1,n), n-s))
orders_df = pd.read_csv('Data/orders.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())<commit_msg>fix: Update data explorations data sets to samples<commit_after># importing modules/ libraries
import pandas as pd
# loading the data
aisles_df = pd.read_csv('Data/aisles.csv')
print(aisles_df.head())
departments_df = pd.read_csv('Data/departments.csv')
print(departments_df.head())
order_products__prior_df = pd.read_csv('Data/order_products__prior_sample.csv')
print(order_products__prior_df.head())
order_products__train_df = pd.read_csv('Data/order_products__train_sample.csv')
print(order_products__train_df.head())
orders_df = pd.read_csv('Data/orders_sample.csv')
print(orders_df.head())
products_df = pd.read_csv('Data/products.csv')
print(products_df.head())
sample_submission_df = pd.read_csv('Data/sample_submission.csv')
print(sample_submission_df.head())
|
3c1203d5f4665873e34de9600c6cf18cbd7f7611
|
moa/tools.py
|
moa/tools.py
|
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
from functools import partial
to_list_pat = compile(', *')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, **kwargs):
def to_list(val):
if isinstance(val, list):
vals = val
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
if not isinstance(val, list):
val = [val]
return ConfigParserProperty(val, section, key, config, val_type=to_list,
**kwargs)
|
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, inner_list=False,
**kwargs):
''' Accepts either a list of a string. Nothing else.
'''
def to_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
def to_2d_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = [split(to_list_pat, line.strip(' []()'))
for line in val.strip(' []()').splitlines()]
for i, line in enumerate(vals):
for j, v in enumerate(line):
vals[i][j] = val_type(v)
return vals
if not isinstance(val, list):
val = [[val]] if inner_list else [val]
v_type = to_2d_list if inner_list else to_list
return ConfigParserProperty(val, section, key, config, val_type=v_type,
**kwargs)
|
Add 2d list to ConfigProperty.
|
Add 2d list to ConfigProperty.
|
Python
|
mit
|
matham/moa
|
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
from functools import partial
to_list_pat = compile(', *')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, **kwargs):
def to_list(val):
if isinstance(val, list):
vals = val
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
if not isinstance(val, list):
val = [val]
return ConfigParserProperty(val, section, key, config, val_type=to_list,
**kwargs)
Add 2d list to ConfigProperty.
|
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, inner_list=False,
**kwargs):
''' Accepts either a list of a string. Nothing else.
'''
def to_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
def to_2d_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = [split(to_list_pat, line.strip(' []()'))
for line in val.strip(' []()').splitlines()]
for i, line in enumerate(vals):
for j, v in enumerate(line):
vals[i][j] = val_type(v)
return vals
if not isinstance(val, list):
val = [[val]] if inner_list else [val]
v_type = to_2d_list if inner_list else to_list
return ConfigParserProperty(val, section, key, config, val_type=v_type,
**kwargs)
|
<commit_before>
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
from functools import partial
to_list_pat = compile(', *')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, **kwargs):
def to_list(val):
if isinstance(val, list):
vals = val
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
if not isinstance(val, list):
val = [val]
return ConfigParserProperty(val, section, key, config, val_type=to_list,
**kwargs)
<commit_msg>Add 2d list to ConfigProperty.<commit_after>
|
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, inner_list=False,
**kwargs):
''' Accepts either a list of a string. Nothing else.
'''
def to_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
def to_2d_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = [split(to_list_pat, line.strip(' []()'))
for line in val.strip(' []()').splitlines()]
for i, line in enumerate(vals):
for j, v in enumerate(line):
vals[i][j] = val_type(v)
return vals
if not isinstance(val, list):
val = [[val]] if inner_list else [val]
v_type = to_2d_list if inner_list else to_list
return ConfigParserProperty(val, section, key, config, val_type=v_type,
**kwargs)
|
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
from functools import partial
to_list_pat = compile(', *')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, **kwargs):
def to_list(val):
if isinstance(val, list):
vals = val
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
if not isinstance(val, list):
val = [val]
return ConfigParserProperty(val, section, key, config, val_type=to_list,
**kwargs)
Add 2d list to ConfigProperty.
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, inner_list=False,
**kwargs):
''' Accepts either a list of a string. Nothing else.
'''
def to_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
def to_2d_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = [split(to_list_pat, line.strip(' []()'))
for line in val.strip(' []()').splitlines()]
for i, line in enumerate(vals):
for j, v in enumerate(line):
vals[i][j] = val_type(v)
return vals
if not isinstance(val, list):
val = [[val]] if inner_list else [val]
v_type = to_2d_list if inner_list else to_list
return ConfigParserProperty(val, section, key, config, val_type=v_type,
**kwargs)
|
<commit_before>
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
from functools import partial
to_list_pat = compile(', *')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, **kwargs):
def to_list(val):
if isinstance(val, list):
vals = val
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
if not isinstance(val, list):
val = [val]
return ConfigParserProperty(val, section, key, config, val_type=to_list,
**kwargs)
<commit_msg>Add 2d list to ConfigProperty.<commit_after>
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, inner_list=False,
**kwargs):
''' Accepts either a list of a string. Nothing else.
'''
def to_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
def to_2d_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = [split(to_list_pat, line.strip(' []()'))
for line in val.strip(' []()').splitlines()]
for i, line in enumerate(vals):
for j, v in enumerate(line):
vals[i][j] = val_type(v)
return vals
if not isinstance(val, list):
val = [[val]] if inner_list else [val]
v_type = to_2d_list if inner_list else to_list
return ConfigParserProperty(val, section, key, config, val_type=v_type,
**kwargs)
|
e21fd90de3b97f3ea2564a8d2c35351f2136b4e5
|
feder/letters/tests/base.py
|
feder/letters/tests/base.py
|
import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open('git-lfs.github.com', 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
|
import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open(path, 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
|
Fix detect Git-LFS in tests
|
Fix detect Git-LFS in tests
|
Python
|
mit
|
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
|
import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open('git-lfs.github.com', 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
Fix detect Git-LFS in tests
|
import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open(path, 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
|
<commit_before>import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open('git-lfs.github.com', 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
<commit_msg>Fix detect Git-LFS in tests<commit_after>
|
import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open(path, 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
|
import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open('git-lfs.github.com', 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
Fix detect Git-LFS in testsimport email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open(path, 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
|
<commit_before>import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open('git-lfs.github.com', 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
<commit_msg>Fix detect Git-LFS in tests<commit_after>import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='from@example.com')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open(path, 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
|
c367d96cdfb7991cbabb38950cf08207f0662f20
|
flask_hal/document.py
|
flask_hal/document.py
|
#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
# Always add the self link
links.append(link.Self())
self.links = links
|
#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
Raises:
TypeError: If ``links`` is not a :class:`flask_hal.link.Collection`
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
else:
if not isinstance(links, link.Collection):
raise TypeError('links must be a flask_hal.link.Collection instance')
# Always add the self link
links.append(link.Self())
self.links = links
|
Raise TypeError if links is not a link.Collection
|
Raise TypeError if links is not a link.Collection
|
Python
|
unlicense
|
thisissoon/Flask-HAL,thisissoon/Flask-HAL
|
#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
# Always add the self link
links.append(link.Self())
self.links = links
Raise TypeError if links is not a link.Collection
|
#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
Raises:
TypeError: If ``links`` is not a :class:`flask_hal.link.Collection`
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
else:
if not isinstance(links, link.Collection):
raise TypeError('links must be a flask_hal.link.Collection instance')
# Always add the self link
links.append(link.Self())
self.links = links
|
<commit_before>#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
# Always add the self link
links.append(link.Self())
self.links = links
<commit_msg>Raise TypeError if links is not a link.Collection<commit_after>
|
#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
Raises:
TypeError: If ``links`` is not a :class:`flask_hal.link.Collection`
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
else:
if not isinstance(links, link.Collection):
raise TypeError('links must be a flask_hal.link.Collection instance')
# Always add the self link
links.append(link.Self())
self.links = links
|
#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
# Always add the self link
links.append(link.Self())
self.links = links
Raise TypeError if links is not a link.Collection#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
Raises:
TypeError: If ``links`` is not a :class:`flask_hal.link.Collection`
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
else:
if not isinstance(links, link.Collection):
raise TypeError('links must be a flask_hal.link.Collection instance')
# Always add the self link
links.append(link.Self())
self.links = links
|
<commit_before>#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
# Always add the self link
links.append(link.Self())
self.links = links
<commit_msg>Raise TypeError if links is not a link.Collection<commit_after>#!/usr/bin/env python
# encoding: utf-8
"""
flask_hal.document
==================
Module for constructing ``HAL`` documents.
Example:
>>> from flask_hal.document import Document
>>> d = Document()
>>> d.to_dict()
"""
# Third Party Libs
from flask_hal import link
class Document(object):
"""Constructs a ``HAL`` document.
"""
def __init__(self, data=None, links=None, embedded=None):
"""Initialises a new ``HAL`` Document instance. If no arguments are
proviced a minimal viable ``HAL`` Document is created.
Keyword Args:
data (dict): Data for the document
links (flask_hal.link.Collection): A collection of ``HAL`` links
embedded: TBC
Raises:
TypeError: If ``links`` is not a :class:`flask_hal.link.Collection`
"""
self.data = data
self.embedded = embedded # TODO: Embedded API TBC
# No links proviced, create an empty collection
if links is None:
links = link.Collection()
else:
if not isinstance(links, link.Collection):
raise TypeError('links must be a flask_hal.link.Collection instance')
# Always add the self link
links.append(link.Self())
self.links = links
|
b80e1facf3c47364384fa04f764838ba1b8cb55c
|
form_designer/apps.py
|
form_designer/apps.py
|
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
name = "form_designer"
verbose_name = _("Form Designer")
|
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "form_designer"
verbose_name = _("Form Designer")
|
Set the default auto field to be AutoField
|
Set the default auto field to be AutoField
On django 3.2 it creates a migration to be BigAutoField. This fixes it.
|
Python
|
bsd-3-clause
|
feincms/form_designer,feincms/form_designer
|
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
name = "form_designer"
verbose_name = _("Form Designer")
Set the default auto field to be AutoField
On django 3.2 it creates a migration to be BigAutoField. This fixes it.
|
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "form_designer"
verbose_name = _("Form Designer")
|
<commit_before>from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
name = "form_designer"
verbose_name = _("Form Designer")
<commit_msg>Set the default auto field to be AutoField
On django 3.2 it creates a migration to be BigAutoField. This fixes it.<commit_after>
|
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "form_designer"
verbose_name = _("Form Designer")
|
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
name = "form_designer"
verbose_name = _("Form Designer")
Set the default auto field to be AutoField
On django 3.2 it creates a migration to be BigAutoField. This fixes it.from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "form_designer"
verbose_name = _("Form Designer")
|
<commit_before>from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
name = "form_designer"
verbose_name = _("Form Designer")
<commit_msg>Set the default auto field to be AutoField
On django 3.2 it creates a migration to be BigAutoField. This fixes it.<commit_after>from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class FormDesignerConfig(AppConfig):
default_auto_field = "django.db.models.AutoField"
name = "form_designer"
verbose_name = _("Form Designer")
|
9c176de1fd280e72dd06c9eaa64060e52abca746
|
python/prebuild.py
|
python/prebuild.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
return eval('callable(mod.{})'.format(name), scope)
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
ignore_decorators = ['dedent','deprecated','silent_list', 'warn_deprecated']
return eval('callable(mod.{})'.format(name), scope) and name not in ignore_decorators
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
|
Remove python decorators from list
|
Remove python decorators from list
|
Python
|
mit
|
koji-kojiro/matplotlib-d
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
return eval('callable(mod.{})'.format(name), scope)
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
Remove python decorators from list
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
ignore_decorators = ['dedent','deprecated','silent_list', 'warn_deprecated']
return eval('callable(mod.{})'.format(name), scope) and name not in ignore_decorators
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
return eval('callable(mod.{})'.format(name), scope)
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
<commit_msg>Remove python decorators from list<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
ignore_decorators = ['dedent','deprecated','silent_list', 'warn_deprecated']
return eval('callable(mod.{})'.format(name), scope) and name not in ignore_decorators
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
return eval('callable(mod.{})'.format(name), scope)
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
Remove python decorators from list#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
ignore_decorators = ['dedent','deprecated','silent_list', 'warn_deprecated']
return eval('callable(mod.{})'.format(name), scope) and name not in ignore_decorators
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
return eval('callable(mod.{})'.format(name), scope)
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
<commit_msg>Remove python decorators from list<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
def extract_function_names(module):
'''
extract function names from attributes of 'module'.
'''
from importlib import import_module
mod = import_module(module.__name__)
attr_list = dir(mod)
scope = locals()
def iscallable(name):
ignore_decorators = ['dedent','deprecated','silent_list', 'warn_deprecated']
return eval('callable(mod.{})'.format(name), scope) and name not in ignore_decorators
return filter(iscallable, attr_list)
def gen_pyplot_functions(dub_root):
'''
generate 'pyplot_functions.txt' for matplotlibd.pyplot.
'''
import matplotlib.pyplot
from string import lowercase
functions = filter(lambda i: i[0] != '_' or i[0] in lowercase,
extract_function_names(matplotlib.pyplot))
with open(dub_root + "/views/pyplot_functions.txt", "w") as f:
f.write("\n".join(functions))
if __name__ == '__main__':
from sys import argv
gen_pyplot_functions(argv[1])
|
4c84dafeca9977543824653e354f113b5142d259
|
jsonsempai.py
|
jsonsempai.py
|
import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
|
import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in iter(d.items()):
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
|
Fix python 3 use of iteritems
|
Fix python 3 use of iteritems
|
Python
|
mit
|
kragniz/json-sempai
|
import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
Fix python 3 use of iteritems
|
import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in iter(d.items()):
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
|
<commit_before>import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
<commit_msg>Fix python 3 use of iteritems<commit_after>
|
import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in iter(d.items()):
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
|
import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
Fix python 3 use of iteritemsimport imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in iter(d.items()):
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
|
<commit_before>import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in d.iteritems():
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
<commit_msg>Fix python 3 use of iteritems<commit_after>import imp
import json
import os
import sys
class Dot(dict):
def __init__(self, d):
super(dict, self).__init__()
for k, v in iter(d.items()):
if isinstance(v, dict):
self[k] = Dot(v)
else:
self[k] = v
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError("'{}'".format(attr))
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
class SempaiLoader(object):
def find_module(self, name, path=None):
for d in sys.path:
self.json_path = os.path.join(d, '{}.json'.format(name))
if os.path.isfile(self.json_path):
return self
return None
def load_module(self, name):
mod = imp.new_module(name)
mod.__file__ = self.json_path
mod.__loader__ = self
try:
with open(self.json_path) as f:
d = json.load(f)
except ValueError:
raise ImportError(
'"{}" does not contain valid json.'.format(self.json_path))
except:
raise ImportError(
'Could not open "{}".'.format(self.json_path))
mod.__dict__.update(d)
for k, i in mod.__dict__.items():
if isinstance(i, dict):
mod.__dict__[k] = Dot(i)
return mod
sys.meta_path.append(SempaiLoader())
|
dcc32e96bccc0f679dc9d3330d3da7f3a7ec3983
|
fireplace/cards/tgt/mage.py
|
fireplace/cards/tgt/mage.py
|
from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST)))
)
|
from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST))),
Reveal(SELF)
)
|
Fix Effigy to properly reveal itself
|
Fix Effigy to properly reveal itself
|
Python
|
agpl-3.0
|
Meerkov/fireplace,Ragowit/fireplace,Ragowit/fireplace,jleclanche/fireplace,smallnamespace/fireplace,amw2104/fireplace,smallnamespace/fireplace,beheh/fireplace,Meerkov/fireplace,NightKev/fireplace,amw2104/fireplace
|
from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST)))
)
Fix Effigy to properly reveal itself
|
from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST))),
Reveal(SELF)
)
|
<commit_before>from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST)))
)
<commit_msg>Fix Effigy to properly reveal itself<commit_after>
|
from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST))),
Reveal(SELF)
)
|
from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST)))
)
Fix Effigy to properly reveal itselffrom ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST))),
Reveal(SELF)
)
|
<commit_before>from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST)))
)
<commit_msg>Fix Effigy to properly reveal itself<commit_after>from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_004:
play = Hit(TARGET, 2)
# Polymorph: Boar
class AT_005:
play = Morph(TARGET, "AT_005t")
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
Summon(CONTROLLER, RandomMinion(cost=Attr(Death.Args.ENTITY, GameTag.COST))),
Reveal(SELF)
)
|
0a7b83a2866b3988d7718efa8f7798fa9052f7ae
|
zeus/api/resources/build_details.py
|
zeus/api/resources/build_details.py
|
from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
def select_resource_for_update(self) -> bool:
return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
|
from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
# def select_resource_for_update(self) -> bool:
# return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
|
Disable select for update on build mutation
|
ref: Disable select for update on build mutation
|
Python
|
apache-2.0
|
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
|
from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
def select_resource_for_update(self) -> bool:
return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
ref: Disable select for update on build mutation
|
from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
# def select_resource_for_update(self) -> bool:
# return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
|
<commit_before>from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
def select_resource_for_update(self) -> bool:
return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
<commit_msg>ref: Disable select for update on build mutation<commit_after>
|
from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
# def select_resource_for_update(self) -> bool:
# return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
|
from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
def select_resource_for_update(self) -> bool:
return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
ref: Disable select for update on build mutationfrom zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
# def select_resource_for_update(self) -> bool:
# return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
|
<commit_before>from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
def select_resource_for_update(self) -> bool:
return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
<commit_msg>ref: Disable select for update on build mutation<commit_after>from zeus.config import db, nplusone
from zeus.models import Build, ItemStat, Revision
from zeus.pubsub.utils import publish
from .base_build import BaseBuildResource
from ..schemas import BuildSchema
build_schema = BuildSchema()
class BuildDetailsResource(BaseBuildResource):
# def select_resource_for_update(self) -> bool:
# return self.is_mutation()
def get(self, build: Build):
"""
Return a build.
"""
with nplusone.ignore("eager_load"):
build.revision = Revision.query.filter(
Revision.sha == build.revision_sha,
Revision.repository_id == build.repository_id,
).first()
build.stats = list(ItemStat.query.filter(ItemStat.item_id == build.id))
return self.respond_with_schema(build_schema, build)
def put(self, build: Build):
"""
Update a build.
"""
result = self.schema_from_request(build_schema, partial=True)
for key, value in result.items():
if getattr(build, key) != value:
setattr(build, key, value)
if db.session.is_modified(build):
db.session.add(build)
db.session.commit()
result = build_schema.dump(build)
publish("builds", "build.update", result)
return self.respond(result, 200)
|
37c0969db4459162b35b76da4142c290bd4a2fc7
|
Utilities/DefaultLoginInfoSetter.py
|
Utilities/DefaultLoginInfoSetter.py
|
#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', n)
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
|
#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', str(n))
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
|
Fix Bug: Encode an int
|
Fix Bug: Encode an int
|
Python
|
mit
|
nday-dev/FbSpider
|
#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', n)
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
Fix Bug: Encode an int
|
#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', str(n))
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
|
<commit_before>#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', n)
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
<commit_msg>Fix Bug: Encode an int<commit_after>
|
#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', str(n))
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
|
#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', n)
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
Fix Bug: Encode an int#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', str(n))
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
|
<commit_before>#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', n)
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
<commit_msg>Fix Bug: Encode an int<commit_after>#--coding:utf-8--
import getpass
import keyring
n = int(raw_input("Number of Accounts: "))
keyring.set_password('FbSpider', 'Account', str(n))
for i in range(0, n):
Email = raw_input("Email: ")
keyring.set_password('FbSpider', 'Account' + str(i), Email)
keyring.set_password('FbSpider', Email, getpass.getpass("Password: "))
|
cdd8b6a7b669dc81e360fa1bcc9b71b5e798cfd5
|
map_loader.py
|
map_loader.py
|
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
print('Loading map file [{}]'.format(map_name))
if not os.path.isfile(map_path):
print('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
|
import logging
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
if not os.path.isfile(map_path):
logging.error('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
|
Remove debug print and log properly
|
Remove debug print and log properly
|
Python
|
mit
|
supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai
|
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
print('Loading map file [{}]'.format(map_name))
if not os.path.isfile(map_path):
print('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
Remove debug print and log properly
|
import logging
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
if not os.path.isfile(map_path):
logging.error('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
|
<commit_before>import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
print('Loading map file [{}]'.format(map_name))
if not os.path.isfile(map_path):
print('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
<commit_msg>Remove debug print and log properly<commit_after>
|
import logging
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
if not os.path.isfile(map_path):
logging.error('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
|
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
print('Loading map file [{}]'.format(map_name))
if not os.path.isfile(map_path):
print('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
Remove debug print and log properlyimport logging
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
if not os.path.isfile(map_path):
logging.error('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
|
<commit_before>import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
print('Loading map file [{}]'.format(map_name))
if not os.path.isfile(map_path):
print('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
<commit_msg>Remove debug print and log properly<commit_after>import logging
import os
def read_map_file(map_name):
""" Load map data from disk. """
root = os.path.dirname(os.path.abspath(__file__))
map_path = os.path.join(root, 'maps', map_name + '.txt')
if not os.path.isfile(map_path):
logging.error('Map file [{}] does not exist'.format(map_path))
else:
try:
with open(map_path, 'r') as f:
return f.read()
except IOError:
print('IOError exception reading map file [{}]'.format(map_path))
|
d0f2b11fb67655b884f298bd8c1bf6be8396de4f
|
mail/email.py
|
mail/email.py
|
from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'
)
mail_api.mark_sent(email_uri)
|
from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'.format(email['sequence'])
)
mail_api.mark_sent(email_uri)
|
Fix bug with campaign id
|
Fix bug with campaign id
|
Python
|
mit
|
p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc,p2pu/mechanical-mooc
|
from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'
)
mail_api.mark_sent(email_uri)
Fix bug with campaign id
|
from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'.format(email['sequence'])
)
mail_api.mark_sent(email_uri)
|
<commit_before>from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'
)
mail_api.mark_sent(email_uri)
<commit_msg>Fix bug with campaign id<commit_after>
|
from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'.format(email['sequence'])
)
mail_api.mark_sent(email_uri)
|
from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'
)
mail_api.mark_sent(email_uri)
Fix bug with campaign idfrom django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'.format(email['sequence'])
)
mail_api.mark_sent(email_uri)
|
<commit_before>from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'
)
mail_api.mark_sent(email_uri)
<commit_msg>Fix bug with campaign id<commit_after>from django.conf import settings
from mail import models as mail_api
from groups import models as group_api
from mailgun import api as mailgun_api
def send_email( email_uri ):
""" Send the email to the intended target audience """
email = mail_api.get_email(email_uri)
if email['audience'] == 'groups':
to_address = ','.join([g['address'] for g in group_api.get_groups(email['sequence'])])
elif email['audience'] == 'individuals':
to_address = 'sequence-{0}-all@{1}'.format(email['sequence'], settings.EMAIL_DOMAIN)
mailgun_api.send_email(
to_address,
settings.DEFAULT_FROM_EMAIL,
email['subject'],
email['text_body'],
email['html_body'],
email['tags'].split(','),
'sequence-{0}-campaign'.format(email['sequence'])
)
mail_api.mark_sent(email_uri)
|
48ff585da5f499abeedb73d1e131a6d488644a05
|
file_transfer/datamover/__init__.py
|
file_transfer/datamover/__init__.py
|
from .connectors import (GithubConnector, S3Connector,
BaltradFTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
|
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
|
Fix namespace bug of FTPconnector
|
Fix namespace bug of FTPconnector
|
Python
|
mit
|
enram/infrastructure,enram/data-repository,enram/data-repository,enram/data-repository,enram/data-repository,enram/infrastructure
|
from .connectors import (GithubConnector, S3Connector,
BaltradFTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
Fix namespace bug of FTPconnector
|
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
|
<commit_before>
from .connectors import (GithubConnector, S3Connector,
BaltradFTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
<commit_msg>Fix namespace bug of FTPconnector<commit_after>
|
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
|
from .connectors import (GithubConnector, S3Connector,
BaltradFTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
Fix namespace bug of FTPconnector
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
|
<commit_before>
from .connectors import (GithubConnector, S3Connector,
BaltradFTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
<commit_msg>Fix namespace bug of FTPconnector<commit_after>
from .connectors import (GithubConnector, S3Connector,
FTPConnector, LocalConnector)
from .transporters import (BaltradToS3, LocalToS3)
from .s3enram import S3EnramHandler
from .utils import (parse_filename, extract_month_updates,
parse_coverage_month, coverage_to_csv)
|
8be701cabf05e62385f5cc2eaf008b0d0da93d9c
|
pww/inputs.py
|
pww/inputs.py
|
# coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
return input('{0} [{1}]: '.format(name, default_value))
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
|
# coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
value = input('{0} [{1}]: '.format(name, default_value))
return value if value else default_value
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
|
Modify that using default value when input value is None.
|
Modify that using default value when input value is None.
|
Python
|
mit
|
meganehouser/pww
|
# coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
return input('{0} [{1}]: '.format(name, default_value))
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
Modify that using default value when input value is None.
|
# coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
value = input('{0} [{1}]: '.format(name, default_value))
return value if value else default_value
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
|
<commit_before># coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
return input('{0} [{1}]: '.format(name, default_value))
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
<commit_msg>Modify that using default value when input value is None.<commit_after>
|
# coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
value = input('{0} [{1}]: '.format(name, default_value))
return value if value else default_value
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
|
# coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
return input('{0} [{1}]: '.format(name, default_value))
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
Modify that using default value when input value is None.# coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
value = input('{0} [{1}]: '.format(name, default_value))
return value if value else default_value
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
|
<commit_before># coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
return input('{0} [{1}]: '.format(name, default_value))
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
<commit_msg>Modify that using default value when input value is None.<commit_after># coding: utf-8
from getpass import getpass
class CLIInput():
def get_user_name(self):
return input('user name: ')
def get_password(self):
return getpass()
def entry_selector(self, entries):
if not entries:
return None, None
titles = list(entries.keys())
for i, title in enumerate(titles):
print('[{0}] {1}'.format(i, title))
number = input('> ')
if number.isdigit() and int(number) <= len(titles):
title = titles[int(number)]
return title, entries[title]
else:
return None, None
def get_entry_info(self, default={}):
entry = {}
def getter(name):
default_value = default.get(name)
default_value = default_value if default_value else ''
value = input('{0} [{1}]: '.format(name, default_value))
return value if value else default_value
title = getter('title')
keys = ['user', 'password', 'other']
for key in keys:
entry[key] = getter(key)
return title, entry
|
043b5e7026663c8fdae8df4f27d3887ef881d405
|
src/viewsapp/views.py
|
src/viewsapp/views.py
|
from django.shortcuts import (
get_object_or_404, redirect, render)
from django.views.generic import View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(View):
def get(self, request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = get_object_or_404(
ExampleModel, slug=request_slug)
return render(
request,
'viewsapp/detail.html',
{'object': example_obj})
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
|
from django.shortcuts import redirect, render
from django.views.generic import DetailView, View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(DetailView):
model = ExampleModel
template_name = 'viewsapp/detail.html'
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
|
Refactor ModelDetail to inherit DetailView GCBV.
|
Refactor ModelDetail to inherit DetailView GCBV.
|
Python
|
bsd-2-clause
|
jambonrose/djangocon2015-views,jambonrose/djangocon2015-views
|
from django.shortcuts import (
get_object_or_404, redirect, render)
from django.views.generic import View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(View):
def get(self, request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = get_object_or_404(
ExampleModel, slug=request_slug)
return render(
request,
'viewsapp/detail.html',
{'object': example_obj})
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
Refactor ModelDetail to inherit DetailView GCBV.
|
from django.shortcuts import redirect, render
from django.views.generic import DetailView, View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(DetailView):
model = ExampleModel
template_name = 'viewsapp/detail.html'
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
|
<commit_before>from django.shortcuts import (
get_object_or_404, redirect, render)
from django.views.generic import View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(View):
def get(self, request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = get_object_or_404(
ExampleModel, slug=request_slug)
return render(
request,
'viewsapp/detail.html',
{'object': example_obj})
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
<commit_msg>Refactor ModelDetail to inherit DetailView GCBV.<commit_after>
|
from django.shortcuts import redirect, render
from django.views.generic import DetailView, View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(DetailView):
model = ExampleModel
template_name = 'viewsapp/detail.html'
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
|
from django.shortcuts import (
get_object_or_404, redirect, render)
from django.views.generic import View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(View):
def get(self, request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = get_object_or_404(
ExampleModel, slug=request_slug)
return render(
request,
'viewsapp/detail.html',
{'object': example_obj})
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
Refactor ModelDetail to inherit DetailView GCBV.from django.shortcuts import redirect, render
from django.views.generic import DetailView, View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(DetailView):
model = ExampleModel
template_name = 'viewsapp/detail.html'
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
|
<commit_before>from django.shortcuts import (
get_object_or_404, redirect, render)
from django.views.generic import View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(View):
def get(self, request, *args, **kwargs):
request_slug = kwargs.get('slug')
example_obj = get_object_or_404(
ExampleModel, slug=request_slug)
return render(
request,
'viewsapp/detail.html',
{'object': example_obj})
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
<commit_msg>Refactor ModelDetail to inherit DetailView GCBV.<commit_after>from django.shortcuts import redirect, render
from django.views.generic import DetailView, View
from .forms import ExampleForm
from .models import ExampleModel
class ModelDetail(DetailView):
model = ExampleModel
template_name = 'viewsapp/detail.html'
class ModelCreate(View):
context_object_name = 'form'
form_class = ExampleForm
template_name = 'viewsapp/form.html'
def get(self, request, *args, **kwargs):
return render(
request,
self.template_name,
{self.context_object_name:
self.form_class()})
def post(self, request, *args, **kwargs):
bound_form = self.form_class(request.POST)
if bound_form.is_valid():
new_obj = bound_form.save()
return redirect(new_obj)
return render(
request,
self.template_name,
{self.context_object_name:
bound_form})
|
59426d66a252a5f53fab2d56d1f88883b743f097
|
gears/processors/hexdigest_paths.py
|
gears/processors/hexdigest_paths.py
|
import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
return os.path.relpath(asset.hexdigest_path, self.current_dir)
|
import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
relpath = str(os.path.relpath(asset.hexdigest_path, self.current_dir))
return relpath.encode('string-escape')
|
Convert string to raw string, in order to print "\\" in css. Otherwise the browse cannot reach the file.
|
Convert string to raw string, in order to print "\\" in css. Otherwise the browse cannot reach the file.
|
Python
|
isc
|
gears/gears,gears/gears,gears/gears
|
import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
return os.path.relpath(asset.hexdigest_path, self.current_dir)
Convert string to raw string, in order to print "\\" in css. Otherwise the browse cannot reach the file.
|
import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
relpath = str(os.path.relpath(asset.hexdigest_path, self.current_dir))
return relpath.encode('string-escape')
|
<commit_before>import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
return os.path.relpath(asset.hexdigest_path, self.current_dir)
<commit_msg>Convert string to raw string, in order to print "\\" in css. Otherwise the browse cannot reach the file.<commit_after>
|
import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
relpath = str(os.path.relpath(asset.hexdigest_path, self.current_dir))
return relpath.encode('string-escape')
|
import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
return os.path.relpath(asset.hexdigest_path, self.current_dir)
Convert string to raw string, in order to print "\\" in css. Otherwise the browse cannot reach the file.import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
relpath = str(os.path.relpath(asset.hexdigest_path, self.current_dir))
return relpath.encode('string-escape')
|
<commit_before>import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
return os.path.relpath(asset.hexdigest_path, self.current_dir)
<commit_msg>Convert string to raw string, in order to print "\\" in css. Otherwise the browse cannot reach the file.<commit_after>import os
import re
from ..assets import build_asset
from ..exceptions import FileNotFound
from .base import BaseProcessor
URL_RE = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def rewrite_paths(source, func):
repl = lambda match: 'url({quote}{path}{quote})'.format(
quote=match.group(1),
path=func(match.group(2)),
)
return URL_RE.sub(repl, source)
class HexdigestPathsProcessor(BaseProcessor):
url_re = re.compile(r"""url\((['"]?)\s*(.*?)\s*\1\)""")
def __call__(self, asset):
self.asset = asset
self.environment = self.asset.attributes.environment
self.current_dir = self.asset.attributes.dirname
self.process()
def process(self):
if self.environment.fingerprinting:
self.asset.processed_source = rewrite_paths(
self.asset.processed_source,
self.rewrite_path,
)
def rewrite_path(self, path):
logical_path = os.path.normpath(os.path.join(self.current_dir, path))
try:
asset = build_asset(self.environment, logical_path)
except FileNotFound:
return path
self.asset.dependencies.add(asset.absolute_path)
relpath = str(os.path.relpath(asset.hexdigest_path, self.current_dir))
return relpath.encode('string-escape')
|
0eb1b641f55a43e83ccc098a0ee33ec2620a86ce
|
glue/utils/qt/qmessagebox_widget.py
|
glue/utils/qt/qmessagebox_widget.py
|
# A patched version of QMessageBox that allows copying the error
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
clipboard.setText(selected_text)
|
# A patched version of QMessageBox that allows copying the error
import os
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
# Newlines are unicode, so need to normalize them to ASCII
selected_text = os.linesep.join(selected_text.splitlines())
clipboard.setText(selected_text)
|
Fix newlines in copying of errors
|
Fix newlines in copying of errors
|
Python
|
bsd-3-clause
|
JudoWill/glue,stscieisenhamer/glue,stscieisenhamer/glue,saimn/glue,saimn/glue,JudoWill/glue
|
# A patched version of QMessageBox that allows copying the error
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
clipboard.setText(selected_text)
Fix newlines in copying of errors
|
# A patched version of QMessageBox that allows copying the error
import os
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
# Newlines are unicode, so need to normalize them to ASCII
selected_text = os.linesep.join(selected_text.splitlines())
clipboard.setText(selected_text)
|
<commit_before># A patched version of QMessageBox that allows copying the error
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
clipboard.setText(selected_text)
<commit_msg>Fix newlines in copying of errors<commit_after>
|
# A patched version of QMessageBox that allows copying the error
import os
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
# Newlines are unicode, so need to normalize them to ASCII
selected_text = os.linesep.join(selected_text.splitlines())
clipboard.setText(selected_text)
|
# A patched version of QMessageBox that allows copying the error
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
clipboard.setText(selected_text)
Fix newlines in copying of errors# A patched version of QMessageBox that allows copying the error
import os
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
# Newlines are unicode, so need to normalize them to ASCII
selected_text = os.linesep.join(selected_text.splitlines())
clipboard.setText(selected_text)
|
<commit_before># A patched version of QMessageBox that allows copying the error
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
clipboard.setText(selected_text)
<commit_msg>Fix newlines in copying of errors<commit_after># A patched version of QMessageBox that allows copying the error
import os
from ...external.qt import QtGui
__all__ = ['QMessageBoxPatched']
class QMessageBoxPatched(QtGui.QMessageBox):
def __init__(self, *args, **kwargs):
super(QMessageBoxPatched, self).__init__(*args, **kwargs)
copy_action = QtGui.QAction('&Copy', self)
copy_action.setShortcut(QtGui.QKeySequence.Copy)
copy_action.triggered.connect(self.copy_detailed)
select_all = QtGui.QAction('Select &All', self)
select_all.setShortcut(QtGui.QKeySequence.SelectAll)
select_all.triggered.connect(self.select_all)
menubar = QtGui.QMenuBar()
editMenu = menubar.addMenu('&Edit')
editMenu.addAction(copy_action)
editMenu.addAction(select_all)
self.layout().setMenuBar(menubar)
@property
def detailed_text_widget(self):
return self.findChild(QtGui.QTextEdit)
def select_all(self):
self.detailed_text_widget.selectAll()
def copy_detailed(self):
clipboard = QtGui.QApplication.clipboard()
selected_text = self.detailed_text_widget.textCursor().selectedText()
# Newlines are unicode, so need to normalize them to ASCII
selected_text = os.linesep.join(selected_text.splitlines())
clipboard.setText(selected_text)
|
8aed9b9402446a311f1f3f93c9bac4416ea114d9
|
server/response.py
|
server/response.py
|
class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
if len(self.body):
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
h = '%s%s' % (h, self.body)
return h
|
class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
if len(self.body):
h = '%s%s' % (h, self.body)
return h
|
Set Content-Length to 0 when no body is set
|
Set Content-Length to 0 when no body is set
|
Python
|
apache-2.0
|
USMediaConsulting/pywebev
|
class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
if len(self.body):
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
h = '%s%s' % (h, self.body)
return h
Set Content-Length to 0 when no body is set
|
class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
if len(self.body):
h = '%s%s' % (h, self.body)
return h
|
<commit_before>class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
if len(self.body):
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
h = '%s%s' % (h, self.body)
return h
<commit_msg>Set Content-Length to 0 when no body is set<commit_after>
|
class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
if len(self.body):
h = '%s%s' % (h, self.body)
return h
|
class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
if len(self.body):
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
h = '%s%s' % (h, self.body)
return h
Set Content-Length to 0 when no body is setclass HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
if len(self.body):
h = '%s%s' % (h, self.body)
return h
|
<commit_before>class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
if len(self.body):
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
h = '%s%s' % (h, self.body)
return h
<commit_msg>Set Content-Length to 0 when no body is set<commit_after>class HttpResponse(object):
def __init__(self):
self.body = ''
self.headers = {}
self.status_code = 200
self.status_string = 'OK'
self.version = 'HTTP/1.1'
def to_string(self):
h = '%s %d %s\r\n' % (
self.version, self.status_code, self.status_string)
for k,v in self.headers.iteritems():
h = '%s%s: %s\r\n' % (h, k, v)
h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body))
if len(self.body):
h = '%s%s' % (h, self.body)
return h
|
12d5915c8ee3503770c387b0b6d623e53aef4915
|
catalyst/constants.py
|
catalyst/constants.py
|
# -*- coding: utf-8 -*-
import logbook
LOG_LEVEL = logbook.DEBUG
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = False
|
# -*- coding: utf-8 -*-
import os
import logbook
''' You can override the LOG level from your environment.
For example, if you want to see the DEBUG messages, run:
$ export CATALYST_LOG_LEVEL=10
'''
LOG_LEVEL = int(os.environ.get('CATALYST_LOG_LEVEL', logbook.INFO))
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = False
|
DEBUG level can be easily overriden from the local environment
|
ENH: DEBUG level can be easily overriden from the local environment
|
Python
|
apache-2.0
|
enigmampc/catalyst,enigmampc/catalyst
|
# -*- coding: utf-8 -*-
import logbook
LOG_LEVEL = logbook.DEBUG
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = FalseENH: DEBUG level can be easily overriden from the local environment
|
# -*- coding: utf-8 -*-
import os
import logbook
''' You can override the LOG level from your environment.
For example, if you want to see the DEBUG messages, run:
$ export CATALYST_LOG_LEVEL=10
'''
LOG_LEVEL = int(os.environ.get('CATALYST_LOG_LEVEL', logbook.INFO))
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = False
|
<commit_before># -*- coding: utf-8 -*-
import logbook
LOG_LEVEL = logbook.DEBUG
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = False<commit_msg>ENH: DEBUG level can be easily overriden from the local environment<commit_after>
|
# -*- coding: utf-8 -*-
import os
import logbook
''' You can override the LOG level from your environment.
For example, if you want to see the DEBUG messages, run:
$ export CATALYST_LOG_LEVEL=10
'''
LOG_LEVEL = int(os.environ.get('CATALYST_LOG_LEVEL', logbook.INFO))
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = False
|
# -*- coding: utf-8 -*-
import logbook
LOG_LEVEL = logbook.DEBUG
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = FalseENH: DEBUG level can be easily overriden from the local environment# -*- coding: utf-8 -*-
import os
import logbook
''' You can override the LOG level from your environment.
For example, if you want to see the DEBUG messages, run:
$ export CATALYST_LOG_LEVEL=10
'''
LOG_LEVEL = int(os.environ.get('CATALYST_LOG_LEVEL', logbook.INFO))
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = False
|
<commit_before># -*- coding: utf-8 -*-
import logbook
LOG_LEVEL = logbook.DEBUG
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = False<commit_msg>ENH: DEBUG level can be easily overriden from the local environment<commit_after># -*- coding: utf-8 -*-
import os
import logbook
''' You can override the LOG level from your environment.
For example, if you want to see the DEBUG messages, run:
$ export CATALYST_LOG_LEVEL=10
'''
LOG_LEVEL = int(os.environ.get('CATALYST_LOG_LEVEL', logbook.INFO))
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
AUTO_INGEST = False
|
7af01726bbfe1474efdb0fdca58ce83975e6918e
|
submit_mpi.py
|
submit_mpi.py
|
import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
|
import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
for line in stdout:
print line
|
Print stdout, forgot about that.
|
Print stdout, forgot about that.
|
Python
|
mit
|
Johanu/submit_mpi
|
import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
Print stdout, forgot about that.
|
import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
for line in stdout:
print line
|
<commit_before>import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
<commit_msg>Print stdout, forgot about that.<commit_after>
|
import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
for line in stdout:
print line
|
import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
Print stdout, forgot about that.import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
for line in stdout:
print line
|
<commit_before>import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
<commit_msg>Print stdout, forgot about that.<commit_after>import subprocess
def read_node_status():
process = subprocess.Popen('pestat -f', shell=True,
stdout=subprocess.PIPE)
process.wait()
return process.stdout
if __name__ == '__main__':
stdout = read_node_status()
for line in stdout:
print line
|
e7a6c4f669c31bc25ac0eb738e9b6584793db5dc
|
indra/reach/reach_reader.py
|
indra/reach/reach_reader.py
|
from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('edu.arizona.sista.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
|
from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('org.clulab.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
|
Update REACH reader to new API class path
|
Update REACH reader to new API class path
|
Python
|
bsd-2-clause
|
johnbachman/belpy,bgyori/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,jmuhlich/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,jmuhlich/indra,bgyori/indra,sorgerlab/indra,jmuhlich/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra
|
from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('edu.arizona.sista.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
Update REACH reader to new API class path
|
from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('org.clulab.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
|
<commit_before>from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('edu.arizona.sista.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
<commit_msg>Update REACH reader to new API class path<commit_after>
|
from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('org.clulab.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
|
from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('edu.arizona.sista.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
Update REACH reader to new API class pathfrom indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('org.clulab.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
|
<commit_before>from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : edu.arizona.sista.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('edu.arizona.sista.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
<commit_msg>Update REACH reader to new API class path<commit_after>from indra.java_vm import autoclass, JavaException
class ReachReader(object):
"""The ReachReaader wraps a singleton instance of the REACH reader.
This allows calling the reader many times without having to wait for it to
start up each time.
Attributes
----------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
def __init__(self):
self.api_ruler = None
def get_api_ruler(self):
"""Return the existing reader if it exists or launch a new one.
Returns
-------
api_ruler : org.clulab.reach.apis.ApiRuler
An instance of the REACH ApiRuler class (java object).
"""
if self.api_ruler is None:
try:
self.api_ruler =\
autoclass('org.clulab.reach.apis.ApiRuler')
except JavaException:
try:
autoclass('java.lang.String')
except JavaException:
pass
return None
return self.api_ruler
|
1937d8ad8a98058b00d48af4a56f8dd4c6a2176d
|
tests/__init__.py
|
tests/__init__.py
|
"""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
|
"""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
db.session.bind.dispose()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
|
Fix database connection leak in tests
|
Fix database connection leak in tests
Without this, each flask app created in tests will hold
one database connection until all tests are finished. This may result
in test failure if database limits number of concurrent connections.
|
Python
|
agpl-3.0
|
snip/skylines,Turbo87/skylines,RBE-Avionik/skylines,Turbo87/skylines,shadowoneau/skylines,TobiasLohner/SkyLines,TobiasLohner/SkyLines,Turbo87/skylines,snip/skylines,Harry-R/skylines,shadowoneau/skylines,TobiasLohner/SkyLines,Turbo87/skylines,skylines-project/skylines,RBE-Avionik/skylines,kerel-fs/skylines,shadowoneau/skylines,skylines-project/skylines,kerel-fs/skylines,RBE-Avionik/skylines,Harry-R/skylines,shadowoneau/skylines,Harry-R/skylines,skylines-project/skylines,RBE-Avionik/skylines,Harry-R/skylines,skylines-project/skylines,kerel-fs/skylines,snip/skylines
|
"""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
Fix database connection leak in tests
Without this, each flask app created in tests will hold
one database connection until all tests are finished. This may result
in test failure if database limits number of concurrent connections.
|
"""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
db.session.bind.dispose()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
|
<commit_before>"""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
<commit_msg>Fix database connection leak in tests
Without this, each flask app created in tests will hold
one database connection until all tests are finished. This may result
in test failure if database limits number of concurrent connections.<commit_after>
|
"""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
db.session.bind.dispose()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
|
"""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
Fix database connection leak in tests
Without this, each flask app created in tests will hold
one database connection until all tests are finished. This may result
in test failure if database limits number of concurrent connections."""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
db.session.bind.dispose()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
|
<commit_before>"""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
<commit_msg>Fix database connection leak in tests
Without this, each flask app created in tests will hold
one database connection until all tests are finished. This may result
in test failure if database limits number of concurrent connections.<commit_after>"""Unit and functional test suite for SkyLines."""
import os
import shutil
from skylines.model import db
from tests.data.bootstrap import bootstrap
__all__ = ['setup_db', 'setup_app', 'teardown_db']
def setup_db():
"""Method used to build a database"""
db.create_all()
def setup_dirs(app):
filesdir = app.config['SKYLINES_FILES_PATH']
if os.path.exists(filesdir):
shutil.rmtree(filesdir)
os.makedirs(filesdir)
def setup_app(app):
setup_db()
setup_dirs(app)
def teardown_db():
"""Method used to destroy a database"""
db.session.remove()
db.drop_all()
db.session.bind.dispose()
def clean_db():
"""Clean all data, leaving schema as is
Suitable to be run before each db-aware test. This is much faster than
dropping whole schema an recreating from scratch.
"""
for table in reversed(db.metadata.sorted_tables):
db.session.execute(table.delete())
def clean_db_and_bootstrap():
clean_db()
bootstrap()
db.session.commit()
|
f1a5b1b9c5d56c12292ac2cdd42c2b7eff2dc1fc
|
tests/__init__.py
|
tests/__init__.py
|
#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(name, value) for name, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
|
#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(key, value) for key, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
|
Rename a variable in Matcher.__repr__() to make the code less confusing.
|
Rename a variable in Matcher.__repr__() to make the code less confusing.
Even though there is technically no name clash, the code is now less confusing.
|
Python
|
mit
|
s3rvac/retdec-python
|
#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(name, value) for name, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
Rename a variable in Matcher.__repr__() to make the code less confusing.
Even though there is technically no name clash, the code is now less confusing.
|
#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(key, value) for key, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
|
<commit_before>#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(name, value) for name, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
<commit_msg>Rename a variable in Matcher.__repr__() to make the code less confusing.
Even though there is technically no name clash, the code is now less confusing.<commit_after>
|
#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(key, value) for key, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
|
#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(name, value) for name, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
Rename a variable in Matcher.__repr__() to make the code less confusing.
Even though there is technically no name clash, the code is now less confusing.#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(key, value) for key, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
|
<commit_before>#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(name, value) for name, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
<commit_msg>Rename a variable in Matcher.__repr__() to make the code less confusing.
Even though there is technically no name clash, the code is now less confusing.<commit_after>#
# Project: retdec-python
# Copyright: (c) 2015 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tests for the library and tools."""
import abc
class Matcher(metaclass=abc.ABCMeta):
"""A base class of all matchers."""
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not self == other
def __repr__(self):
name = self.__class__.__qualname__
attr_list = ', '.join(
'{}={!r}'.format(key, value) for key, value in self.__dict__.items()
)
return '{}({})'.format(name, attr_list)
class Anything(Matcher):
"""A matcher that matches anything."""
def __eq__(self, other):
return True
class AnyDictWith(Matcher):
"""A matcher that matches and ``dict`` with the given keys and values.
The ``dict`` may also have other keys and values, which are not considered
during the matching.
"""
def __init__(self, **kwargs):
self.__dict__ = kwargs
def __eq__(self, other):
if not isinstance(other, dict):
return False
for name, value in self.__dict__.items():
if name not in other or other[name] != value:
return False
return True
|
4d547ffa4112412e340abd6231cd406d14b8ff35
|
l10n_lu_ecdf/__openerp__.py
|
l10n_lu_ecdf/__openerp__.py
|
{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
|
{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_ext",
"l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
|
Add dependency on l10n_lu_ext, for the field l10n_lu_matricule
|
[FIX] Add dependency on l10n_lu_ext, for the field l10n_lu_matricule
|
Python
|
agpl-3.0
|
acsone/l10n-luxemburg
|
{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
[FIX] Add dependency on l10n_lu_ext, for the field l10n_lu_matricule
|
{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_ext",
"l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
|
<commit_before>{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
<commit_msg>[FIX] Add dependency on l10n_lu_ext, for the field l10n_lu_matricule<commit_after>
|
{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_ext",
"l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
|
{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
[FIX] Add dependency on l10n_lu_ext, for the field l10n_lu_matricule{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_ext",
"l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
|
<commit_before>{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
<commit_msg>[FIX] Add dependency on l10n_lu_ext, for the field l10n_lu_matricule<commit_after>{
"name": "eCDF annual reports",
"version": "8.0.1.0.0",
"author": "ACSONE SA/NV",
"license": "AGPL-3",
"category": "Accounting & Finance",
"website": "http://acsone.eu",
"depends": ["l10n_lu_ext",
"l10n_lu_mis_reports",
"mis_builder"],
"module": "",
"summary": "Generates XML eCDF annual financial reports",
"data": [
"views/res_company.xml",
"wizard/ecdf_report_view.xml",
],
"installable": True,
}
|
d93628d8cc63301148a139a6c1c354620e5e57d1
|
tests/settings.py
|
tests/settings.py
|
SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
DEBUG = True
STATIC_URL = "/static/"
|
SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
DEBUG = True
STATIC_URL = "/static/"
|
Add new required middleware to make tests pass on Django 1.7
|
Add new required middleware to make tests pass on Django 1.7
|
Python
|
mit
|
suutari-ai/django-enumfields,jackyyf/django-enumfields,bxm156/django-enumfields,jessamynsmith/django-enumfields
|
SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
DEBUG = True
STATIC_URL = "/static/"Add new required middleware to make tests pass on Django 1.7
|
SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
DEBUG = True
STATIC_URL = "/static/"
|
<commit_before>SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
DEBUG = True
STATIC_URL = "/static/"<commit_msg>Add new required middleware to make tests pass on Django 1.7<commit_after>
|
SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
DEBUG = True
STATIC_URL = "/static/"
|
SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
DEBUG = True
STATIC_URL = "/static/"Add new required middleware to make tests pass on Django 1.7SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
DEBUG = True
STATIC_URL = "/static/"
|
<commit_before>SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
DEBUG = True
STATIC_URL = "/static/"<commit_msg>Add new required middleware to make tests pass on Django 1.7<commit_after>SECRET_KEY = 'SEKRIT'
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'tests',
)
ROOT_URLCONF = 'tests.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'enumfields.db',
'TEST_NAME': 'enumfields.db',
},
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
DEBUG = True
STATIC_URL = "/static/"
|
e6d7181ababaa9f08602c48e03d6557ddb6a4deb
|
tests/test_gio.py
|
tests/test_gio.py
|
# -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testWrite(self):
self.assertEquals(self.stream.read(), "testing")
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
def testWriteAsync(self):
def callback(stream, result):
loop.quit()
f = gio.file_new_for_path("outputstream.txt")
stream = f.read()
stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
|
# -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testRead(self):
self.assertEquals(self.stream.read(), "testing")
def testReadAsync(self):
def callback(stream, result):
self.assertEquals(stream.read_finish(result), len("testing"))
loop.quit()
self.stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
self._f.flush()
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
|
Reorganize tests and make them test more useful things
|
Reorganize tests and make them test more useful things
svn path=/trunk/; revision=738
|
Python
|
lgpl-2.1
|
pexip/pygobject,GNOME/pygobject,davibe/pygobject,alexef/pygobject,davidmalcolm/pygobject,MathieuDuponchelle/pygobject,davidmalcolm/pygobject,Distrotech/pygobject,choeger/pygobject-cmake,sfeltman/pygobject,Distrotech/pygobject,MathieuDuponchelle/pygobject,GNOME/pygobject,thiblahute/pygobject,jdahlin/pygobject,atizo/pygobject,alexef/pygobject,jdahlin/pygobject,choeger/pygobject-cmake,thiblahute/pygobject,GNOME/pygobject,nzjrs/pygobject,Distrotech/pygobject,pexip/pygobject,pexip/pygobject,atizo/pygobject,davibe/pygobject,choeger/pygobject-cmake,alexef/pygobject,davibe/pygobject,davibe/pygobject,MathieuDuponchelle/pygobject,Distrotech/pygobject,jdahlin/pygobject,sfeltman/pygobject,nzjrs/pygobject,thiblahute/pygobject,atizo/pygobject,nzjrs/pygobject,davidmalcolm/pygobject,sfeltman/pygobject
|
# -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testWrite(self):
self.assertEquals(self.stream.read(), "testing")
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
def testWriteAsync(self):
def callback(stream, result):
loop.quit()
f = gio.file_new_for_path("outputstream.txt")
stream = f.read()
stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
Reorganize tests and make them test more useful things
svn path=/trunk/; revision=738
|
# -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testRead(self):
self.assertEquals(self.stream.read(), "testing")
def testReadAsync(self):
def callback(stream, result):
self.assertEquals(stream.read_finish(result), len("testing"))
loop.quit()
self.stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
self._f.flush()
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
|
<commit_before># -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testWrite(self):
self.assertEquals(self.stream.read(), "testing")
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
def testWriteAsync(self):
def callback(stream, result):
loop.quit()
f = gio.file_new_for_path("outputstream.txt")
stream = f.read()
stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
<commit_msg>Reorganize tests and make them test more useful things
svn path=/trunk/; revision=738<commit_after>
|
# -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testRead(self):
self.assertEquals(self.stream.read(), "testing")
def testReadAsync(self):
def callback(stream, result):
self.assertEquals(stream.read_finish(result), len("testing"))
loop.quit()
self.stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
self._f.flush()
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
|
# -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testWrite(self):
self.assertEquals(self.stream.read(), "testing")
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
def testWriteAsync(self):
def callback(stream, result):
loop.quit()
f = gio.file_new_for_path("outputstream.txt")
stream = f.read()
stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
Reorganize tests and make them test more useful things
svn path=/trunk/; revision=738# -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testRead(self):
self.assertEquals(self.stream.read(), "testing")
def testReadAsync(self):
def callback(stream, result):
self.assertEquals(stream.read_finish(result), len("testing"))
loop.quit()
self.stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
self._f.flush()
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
|
<commit_before># -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testWrite(self):
self.assertEquals(self.stream.read(), "testing")
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
def testWriteAsync(self):
def callback(stream, result):
loop.quit()
f = gio.file_new_for_path("outputstream.txt")
stream = f.read()
stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
<commit_msg>Reorganize tests and make them test more useful things
svn path=/trunk/; revision=738<commit_after># -*- Mode: Python -*-
import os
import unittest
from common import gio, gobject
class TestInputStream(unittest.TestCase):
def setUp(self):
f = open("inputstream.txt", "w")
f.write("testing")
self._f = open("inputstream.txt", "r")
self.stream = gio.unix.InputStream(self._f.fileno(), False)
def tearDown(self):
self._f.close()
os.unlink("inputstream.txt")
def testRead(self):
self.assertEquals(self.stream.read(), "testing")
def testReadAsync(self):
def callback(stream, result):
self.assertEquals(stream.read_finish(result), len("testing"))
loop.quit()
self.stream.read_async(10240, 0, None, callback)
loop = gobject.MainLoop()
loop.run()
class TestOutputStream(unittest.TestCase):
def setUp(self):
self._f = open("outputstream.txt", "w")
self.stream = gio.unix.OutputStream(self._f.fileno(), False)
self._f.flush()
def tearDown(self):
self._f.close()
os.unlink("outputstream.txt")
def testWrite(self):
self.stream.write("testing")
self.stream.close()
self.failUnless(os.path.exists("outputstream.txt"))
self.assertEquals(open("outputstream.txt").read(), "testing")
|
4db16ece582e8f0a81e032ea1a37c9cbf344a261
|
couchdb/tests/testutil.py
|
couchdb/tests/testutil.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import uuid
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
name = 'couchdb-python/' + uuid.uuid4().hex
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import random
import sys
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
# Find an unused database name
while True:
name = 'couchdb-python/%d' % random.randint(0, sys.maxint)
if name not in self.temp_dbs:
break
print '%s already used' % name
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
|
Use a random number instead of uuid for temp database name.
|
Use a random number instead of uuid for temp database name.
|
Python
|
bsd-3-clause
|
zielmicha/couchdb-python,ajmirsky/couchdb-python
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import uuid
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
name = 'couchdb-python/' + uuid.uuid4().hex
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
Use a random number instead of uuid for temp database name.
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import random
import sys
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
# Find an unused database name
while True:
name = 'couchdb-python/%d' % random.randint(0, sys.maxint)
if name not in self.temp_dbs:
break
print '%s already used' % name
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import uuid
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
name = 'couchdb-python/' + uuid.uuid4().hex
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
<commit_msg>Use a random number instead of uuid for temp database name.<commit_after>
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import random
import sys
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
# Find an unused database name
while True:
name = 'couchdb-python/%d' % random.randint(0, sys.maxint)
if name not in self.temp_dbs:
break
print '%s already used' % name
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import uuid
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
name = 'couchdb-python/' + uuid.uuid4().hex
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
Use a random number instead of uuid for temp database name.# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import random
import sys
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
# Find an unused database name
while True:
name = 'couchdb-python/%d' % random.randint(0, sys.maxint)
if name not in self.temp_dbs:
break
print '%s already used' % name
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
|
<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import uuid
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
name = 'couchdb-python/' + uuid.uuid4().hex
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
<commit_msg>Use a random number instead of uuid for temp database name.<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 Christopher Lenz
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import random
import sys
from couchdb import client
class TempDatabaseMixin(object):
temp_dbs = None
_db = None
def setUp(self):
self.server = client.Server(full_commit=False)
def tearDown(self):
if self.temp_dbs:
for name in self.temp_dbs:
self.server.delete(name)
def temp_db(self):
if self.temp_dbs is None:
self.temp_dbs = {}
# Find an unused database name
while True:
name = 'couchdb-python/%d' % random.randint(0, sys.maxint)
if name not in self.temp_dbs:
break
print '%s already used' % name
db = self.server.create(name)
self.temp_dbs[name] = db
return name, db
def del_db(self, name):
del self.temp_dbs[name]
self.server.delete(name)
@property
def db(self):
if self._db is None:
name, self._db = self.temp_db()
return self._db
|
66a6d66ccdc14ca5ad8c2870b18318c5c94524c6
|
src/romaine/core.py
|
src/romaine/core.py
|
import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = []
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.extend(feature_candidates)
return feature_candidates
|
import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = set()
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.update(feature_candidates)
return feature_candidates
|
Make feature_file_paths have no duplicates
|
Make feature_file_paths have no duplicates
|
Python
|
mit
|
trojjer/romaine,london-python-project-nights/romaine,london-python-project-nights/romaine
|
import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = []
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.extend(feature_candidates)
return feature_candidates
Make feature_file_paths have no duplicates
|
import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = set()
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.update(feature_candidates)
return feature_candidates
|
<commit_before>import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = []
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.extend(feature_candidates)
return feature_candidates
<commit_msg>Make feature_file_paths have no duplicates<commit_after>
|
import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = set()
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.update(feature_candidates)
return feature_candidates
|
import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = []
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.extend(feature_candidates)
return feature_candidates
Make feature_file_paths have no duplicatesimport os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = set()
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.update(feature_candidates)
return feature_candidates
|
<commit_before>import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = []
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.extend(feature_candidates)
return feature_candidates
<commit_msg>Make feature_file_paths have no duplicates<commit_after>import os
class Core(object):
"""
The core of the Romaine, provides BDD test API.
"""
# All located features
feature_file_paths = set()
instance = None
def __init__(self):
"""
Initialise Romaine core.
"""
self.steps = {}
Core.instance = self
def locate_features(self, path):
"""
Locate any features given a path.
Keyword arguments:
path -- The path to search for features, recursively.
Returns:
List of features located in the path given.
"""
walked_paths = os.walk(path)
# Features in this path are stored in an intermediate list before
# being added to the class variable so that we can return only the
# ones we find on this invocation of locate_features
feature_candidates = []
for walked_path in walked_paths:
base_directory, sub_directories, feature_files = walked_path
for feature_file in feature_files:
feature_candidates.append(
os.path.join(
base_directory,
feature_file
)
)
self.feature_file_paths.update(feature_candidates)
return feature_candidates
|
38bb089a4885053c2058ba65ea9380fcc7c99f62
|
ulp/urlextract.py
|
ulp/urlextract.py
|
# coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.getenv('HOME'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
|
# coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.path.expanduser('~'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
|
Use expanduser instead of env
|
Use expanduser instead of env
|
Python
|
mit
|
victal/ulp,victal/ulp
|
# coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.getenv('HOME'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
Use expanduser instead of env
|
# coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.path.expanduser('~'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
|
<commit_before># coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.getenv('HOME'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
<commit_msg>Use expanduser instead of env<commit_after>
|
# coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.path.expanduser('~'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
|
# coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.getenv('HOME'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
Use expanduser instead of env# coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.path.expanduser('~'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
|
<commit_before># coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.getenv('HOME'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
<commit_msg>Use expanduser instead of env<commit_after># coding=utf-8
import re
import os
import sys
# Regex for matching URLs
# See https://mathiasbynens.be/demo/url-regex
url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)")
ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE)
INPUT_FILE = os.path.join(os.path.expanduser('~'), '.cache', 'ulp', 'links')
def escape_ansi(text):
return ansi_escape_regex.sub("", text)
def parse_stdin():
lines = [line.strip() for line in sys.stdin]
print(os.linesep.join(lines).strip(), file=sys.stderr)
return parse_input(os.linesep.join(lines))
def parse_input(text):
matches = url_regex.findall(escape_ansi(text.strip()))
return [result[0] for result in matches]
def read_inputfile():
with open(INPUT_FILE) as f:
return [l.strip() for l in f.readlines()]
def main():
#If we are not being piped, exit
if sys.stdin.isatty():
sys.exit(1)
result = parse_stdin()
for url in result:
print(url)
if __name__ == '__main__':
main()
|
32c7baf89057741a898b10a01a7535c4af3f41b3
|
maestro/exceptions.py
|
maestro/exceptions.py
|
# Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
|
# Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class EnvironmentConfigurationException(MaestroException):
"""Error in the Maestro environment description file."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
|
Add exception to denote YAML environment configuration issues
|
Add exception to denote YAML environment configuration issues
Signed-off-by: Maxime Petazzoni <0706025b2bbcec1ed8d64822f4eccd96314938d0@signalfuse.com>
|
Python
|
apache-2.0
|
jorge-marques/maestro-ng,jorge-marques/maestro-ng,signalfuse/maestro-ng,signalfx/maestro-ng,Anvil/maestro-ng,Anvil/maestro-ng,ivotron/maestro-ng,signalfuse/maestro-ng,ivotron/maestro-ng,signalfx/maestro-ng,zsuzhengdu/maestro-ng,zsuzhengdu/maestro-ng
|
# Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
Add exception to denote YAML environment configuration issues
Signed-off-by: Maxime Petazzoni <0706025b2bbcec1ed8d64822f4eccd96314938d0@signalfuse.com>
|
# Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class EnvironmentConfigurationException(MaestroException):
"""Error in the Maestro environment description file."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
|
<commit_before># Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
<commit_msg>Add exception to denote YAML environment configuration issues
Signed-off-by: Maxime Petazzoni <0706025b2bbcec1ed8d64822f4eccd96314938d0@signalfuse.com><commit_after>
|
# Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class EnvironmentConfigurationException(MaestroException):
"""Error in the Maestro environment description file."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
|
# Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
Add exception to denote YAML environment configuration issues
Signed-off-by: Maxime Petazzoni <0706025b2bbcec1ed8d64822f4eccd96314938d0@signalfuse.com># Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class EnvironmentConfigurationException(MaestroException):
"""Error in the Maestro environment description file."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
|
<commit_before># Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
<commit_msg>Add exception to denote YAML environment configuration issues
Signed-off-by: Maxime Petazzoni <0706025b2bbcec1ed8d64822f4eccd96314938d0@signalfuse.com><commit_after># Copyright (C) 2013 SignalFuse, Inc.
#
# Docker container orchestration utility.
class MaestroException(Exception):
"""Base class for Maestro exceptions."""
pass
class DependencyException(MaestroException):
"""Dependency resolution error."""
pass
class ParameterException(MaestroException):
"""Invalid parameter passed to Maestro."""
pass
class EnvironmentConfigurationException(MaestroException):
"""Error in the Maestro environment description file."""
pass
class OrchestrationException(MaestroException):
"""Error during the execution of the orchestration score."""
pass
class InvalidPortSpecException(MaestroException):
"Error thrown when a port spec is in an invalid format."""
pass
class InvalidLifecycleCheckConfigurationException(MaestroException):
"Error thrown when a lifecycle check isn't configured properly."""
pass
|
9120cfa9bb31e1cca5adba77ac7a872ed3b8dc99
|
tweets/models.py
|
tweets/models.py
|
from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages")
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in")
hash_tags = models.ManyToManyField(HashTag)
def __str__(self):
return self.text
|
from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages", blank=True)
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in", blank=True)
hash_tags = models.ManyToManyField(HashTag, blank=True)
def __str__(self):
return self.text
|
Add blank to allow no stars/tags in admin
|
Add blank to allow no stars/tags in admin
|
Python
|
mit
|
pennomi/openwest2015-twitter-clone,pennomi/openwest2015-twitter-clone,pennomi/openwest2015-twitter-clone
|
from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages")
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in")
hash_tags = models.ManyToManyField(HashTag)
def __str__(self):
return self.textAdd blank to allow no stars/tags in admin
|
from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages", blank=True)
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in", blank=True)
hash_tags = models.ManyToManyField(HashTag, blank=True)
def __str__(self):
return self.text
|
<commit_before>from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages")
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in")
hash_tags = models.ManyToManyField(HashTag)
def __str__(self):
return self.text<commit_msg>Add blank to allow no stars/tags in admin<commit_after>
|
from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages", blank=True)
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in", blank=True)
hash_tags = models.ManyToManyField(HashTag, blank=True)
def __str__(self):
return self.text
|
from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages")
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in")
hash_tags = models.ManyToManyField(HashTag)
def __str__(self):
return self.textAdd blank to allow no stars/tags in adminfrom django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages", blank=True)
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in", blank=True)
hash_tags = models.ManyToManyField(HashTag, blank=True)
def __str__(self):
return self.text
|
<commit_before>from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages")
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in")
hash_tags = models.ManyToManyField(HashTag)
def __str__(self):
return self.text<commit_msg>Add blank to allow no stars/tags in admin<commit_after>from django.conf import settings
from django.db import models
class HashTag(models.Model):
# The hash tag length can't be more than the body length minus the `#`
text = models.CharField(max_length=139)
def __str__(self):
return self.text
class Message(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="messages")
text = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
stars = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="starred_messages", blank=True)
tagged_users = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="messages_tagged_in", blank=True)
hash_tags = models.ManyToManyField(HashTag, blank=True)
def __str__(self):
return self.text
|
fd4dc4bdd32283b67577630c38624d3df705efd3
|
mathphys/functions.py
|
mathphys/functions.py
|
"""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials, algorithm='lstsq'):
"""Implement Custom polyfit."""
X = _np.zeros((len(x), len(monomials)))
N = _np.zeros((len(x), len(monomials)))
for i in range(X.shape[1]):
X[:, i] = x
N[:, i] = monomials[i]
XN = X ** N
y_ = _np.zeros((len(y), 1))
y_[:, 0] = y
XNt = _np.transpose(XN)
b = _np.dot(XNt, y_)
X = _np.dot(XNt, XN)
if algorithm is 'lstsq':
r = _np.linalg.lstsq(X, b)
coeffs = r[0][:, 0]
else:
r = _np.linalg.solve(X, b)
coeffs = r[:, 0]
# finds maximum diff and its base value
y_fitted = _np.dot(XN, coeffs)
y_diff = abs(y_fitted - y_[:, 0])
max_error = max(y_diff)
idx = [i for i, value in enumerate(y_diff) if value == max_error]
base_value = y_[idx[0], 0]
return (coeffs, (max_error, base_value))
|
"""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials):
"""Implement Custom polyfit."""
coef = _np.polynomial.polynomial.polyfit(x, y, deg=monomials)
# finds maximum diff and its base value
y_fitted = _np.polynomial.polynomial.polyval(x, coef)
y_diff = abs(y_fitted - y)
idx = _np.argmax(y_diff)
coeffs = coef[monomials]
return (coeffs, (y_diff[idx], y[idx]))
|
Change implementaton of polyfit method.
|
API: Change implementaton of polyfit method.
Use new numpy.polynomial.polynomial.polyfit instead of implementing leastsquares by hand. This method is supposed to be more robust to numerical errors.
With this change, the keyword argument algorithm was removed.
|
Python
|
mit
|
lnls-fac/mathphys
|
"""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials, algorithm='lstsq'):
"""Implement Custom polyfit."""
X = _np.zeros((len(x), len(monomials)))
N = _np.zeros((len(x), len(monomials)))
for i in range(X.shape[1]):
X[:, i] = x
N[:, i] = monomials[i]
XN = X ** N
y_ = _np.zeros((len(y), 1))
y_[:, 0] = y
XNt = _np.transpose(XN)
b = _np.dot(XNt, y_)
X = _np.dot(XNt, XN)
if algorithm is 'lstsq':
r = _np.linalg.lstsq(X, b)
coeffs = r[0][:, 0]
else:
r = _np.linalg.solve(X, b)
coeffs = r[:, 0]
# finds maximum diff and its base value
y_fitted = _np.dot(XN, coeffs)
y_diff = abs(y_fitted - y_[:, 0])
max_error = max(y_diff)
idx = [i for i, value in enumerate(y_diff) if value == max_error]
base_value = y_[idx[0], 0]
return (coeffs, (max_error, base_value))
API: Change implementaton of polyfit method.
Use new numpy.polynomial.polynomial.polyfit instead of implementing leastsquares by hand. This method is supposed to be more robust to numerical errors.
With this change, the keyword argument algorithm was removed.
|
"""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials):
"""Implement Custom polyfit."""
coef = _np.polynomial.polynomial.polyfit(x, y, deg=monomials)
# finds maximum diff and its base value
y_fitted = _np.polynomial.polynomial.polyval(x, coef)
y_diff = abs(y_fitted - y)
idx = _np.argmax(y_diff)
coeffs = coef[monomials]
return (coeffs, (y_diff[idx], y[idx]))
|
<commit_before>"""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials, algorithm='lstsq'):
"""Implement Custom polyfit."""
X = _np.zeros((len(x), len(monomials)))
N = _np.zeros((len(x), len(monomials)))
for i in range(X.shape[1]):
X[:, i] = x
N[:, i] = monomials[i]
XN = X ** N
y_ = _np.zeros((len(y), 1))
y_[:, 0] = y
XNt = _np.transpose(XN)
b = _np.dot(XNt, y_)
X = _np.dot(XNt, XN)
if algorithm is 'lstsq':
r = _np.linalg.lstsq(X, b)
coeffs = r[0][:, 0]
else:
r = _np.linalg.solve(X, b)
coeffs = r[:, 0]
# finds maximum diff and its base value
y_fitted = _np.dot(XN, coeffs)
y_diff = abs(y_fitted - y_[:, 0])
max_error = max(y_diff)
idx = [i for i, value in enumerate(y_diff) if value == max_error]
base_value = y_[idx[0], 0]
return (coeffs, (max_error, base_value))
<commit_msg>API: Change implementaton of polyfit method.
Use new numpy.polynomial.polynomial.polyfit instead of implementing leastsquares by hand. This method is supposed to be more robust to numerical errors.
With this change, the keyword argument algorithm was removed.<commit_after>
|
"""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials):
"""Implement Custom polyfit."""
coef = _np.polynomial.polynomial.polyfit(x, y, deg=monomials)
# finds maximum diff and its base value
y_fitted = _np.polynomial.polynomial.polyval(x, coef)
y_diff = abs(y_fitted - y)
idx = _np.argmax(y_diff)
coeffs = coef[monomials]
return (coeffs, (y_diff[idx], y[idx]))
|
"""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials, algorithm='lstsq'):
"""Implement Custom polyfit."""
X = _np.zeros((len(x), len(monomials)))
N = _np.zeros((len(x), len(monomials)))
for i in range(X.shape[1]):
X[:, i] = x
N[:, i] = monomials[i]
XN = X ** N
y_ = _np.zeros((len(y), 1))
y_[:, 0] = y
XNt = _np.transpose(XN)
b = _np.dot(XNt, y_)
X = _np.dot(XNt, XN)
if algorithm is 'lstsq':
r = _np.linalg.lstsq(X, b)
coeffs = r[0][:, 0]
else:
r = _np.linalg.solve(X, b)
coeffs = r[:, 0]
# finds maximum diff and its base value
y_fitted = _np.dot(XN, coeffs)
y_diff = abs(y_fitted - y_[:, 0])
max_error = max(y_diff)
idx = [i for i, value in enumerate(y_diff) if value == max_error]
base_value = y_[idx[0], 0]
return (coeffs, (max_error, base_value))
API: Change implementaton of polyfit method.
Use new numpy.polynomial.polynomial.polyfit instead of implementing leastsquares by hand. This method is supposed to be more robust to numerical errors.
With this change, the keyword argument algorithm was removed."""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials):
"""Implement Custom polyfit."""
coef = _np.polynomial.polynomial.polyfit(x, y, deg=monomials)
# finds maximum diff and its base value
y_fitted = _np.polynomial.polynomial.polyval(x, coef)
y_diff = abs(y_fitted - y)
idx = _np.argmax(y_diff)
coeffs = coef[monomials]
return (coeffs, (y_diff[idx], y[idx]))
|
<commit_before>"""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials, algorithm='lstsq'):
"""Implement Custom polyfit."""
X = _np.zeros((len(x), len(monomials)))
N = _np.zeros((len(x), len(monomials)))
for i in range(X.shape[1]):
X[:, i] = x
N[:, i] = monomials[i]
XN = X ** N
y_ = _np.zeros((len(y), 1))
y_[:, 0] = y
XNt = _np.transpose(XN)
b = _np.dot(XNt, y_)
X = _np.dot(XNt, XN)
if algorithm is 'lstsq':
r = _np.linalg.lstsq(X, b)
coeffs = r[0][:, 0]
else:
r = _np.linalg.solve(X, b)
coeffs = r[:, 0]
# finds maximum diff and its base value
y_fitted = _np.dot(XN, coeffs)
y_diff = abs(y_fitted - y_[:, 0])
max_error = max(y_diff)
idx = [i for i, value in enumerate(y_diff) if value == max_error]
base_value = y_[idx[0], 0]
return (coeffs, (max_error, base_value))
<commit_msg>API: Change implementaton of polyfit method.
Use new numpy.polynomial.polynomial.polyfit instead of implementing leastsquares by hand. This method is supposed to be more robust to numerical errors.
With this change, the keyword argument algorithm was removed.<commit_after>"""Useful functions."""
import numpy as _np
def polyfit(x, y, monomials):
"""Implement Custom polyfit."""
coef = _np.polynomial.polynomial.polyfit(x, y, deg=monomials)
# finds maximum diff and its base value
y_fitted = _np.polynomial.polynomial.polyval(x, coef)
y_diff = abs(y_fitted - y)
idx = _np.argmax(y_diff)
coeffs = coef[monomials]
return (coeffs, (y_diff[idx], y[idx]))
|
0fb6842a85056b16b4bc4f4d48edcc4b0d749b94
|
src/pi/wemo_proxy.py
|
src/pi/wemo_proxy.py
|
"""Wemo proxy code."""
import logging
import sys
import threading
from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
|
"""Wemo proxy code."""
import logging
import sys
import threading
#from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
|
Comment out wemo stuff for now.
|
Comment out wemo stuff for now.
|
Python
|
mit
|
tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation
|
"""Wemo proxy code."""
import logging
import sys
import threading
from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
Comment out wemo stuff for now.
|
"""Wemo proxy code."""
import logging
import sys
import threading
#from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
|
<commit_before>"""Wemo proxy code."""
import logging
import sys
import threading
from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
<commit_msg>Comment out wemo stuff for now.<commit_after>
|
"""Wemo proxy code."""
import logging
import sys
import threading
#from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
|
"""Wemo proxy code."""
import logging
import sys
import threading
from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
Comment out wemo stuff for now."""Wemo proxy code."""
import logging
import sys
import threading
#from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
|
<commit_before>"""Wemo proxy code."""
import logging
import sys
import threading
from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
<commit_msg>Comment out wemo stuff for now.<commit_after>"""Wemo proxy code."""
import logging
import sys
import threading
#from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
|
4a0516e6f7abee9378a5c46b7a262848a76d7f49
|
employees/serializers.py
|
employees/serializers.py
|
from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'categories',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
|
from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
|
Remove categories from employee serializer
|
Remove categories from employee serializer
|
Python
|
apache-2.0
|
belatrix/BackendAllStars
|
from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'categories',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
Remove categories from employee serializer
|
from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
|
<commit_before>from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'categories',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
<commit_msg>Remove categories from employee serializer<commit_after>
|
from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
|
from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'categories',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
Remove categories from employee serializerfrom .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
|
<commit_before>from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'categories',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
<commit_msg>Remove categories from employee serializer<commit_after>from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'role',
'skype_id',
'last_month_score',
'current_month_score',
'level',
'score',
'is_active',
'last_login')
class EmployeeListSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk',
'username',
'email',
'first_name',
'last_name',
'level',
'avatar',
'score')
class EmployeeAvatarSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ('pk', 'avatar')
|
5ee949626b2d5b132f8ec1ce7d597a7ad401cfa5
|
epydemiology/__init__.py
|
epydemiology/__init__.py
|
# These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjGetCollapsedPatientDataframeColumns
|
# These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjCollapseOnPatientID
|
Add phjCollapseOnPatientID and remove phjGetCollapsedPatientDataframeColumns
|
Add phjCollapseOnPatientID and remove phjGetCollapsedPatientDataframeColumns
|
Python
|
mit
|
lvphj/epydemiology
|
# These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjGetCollapsedPatientDataframeColumns
Add phjCollapseOnPatientID and remove phjGetCollapsedPatientDataframeColumns
|
# These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjCollapseOnPatientID
|
<commit_before># These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjGetCollapsedPatientDataframeColumns
<commit_msg>Add phjCollapseOnPatientID and remove phjGetCollapsedPatientDataframeColumns<commit_after>
|
# These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjCollapseOnPatientID
|
# These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjGetCollapsedPatientDataframeColumns
Add phjCollapseOnPatientID and remove phjGetCollapsedPatientDataframeColumns# These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjCollapseOnPatientID
|
<commit_before># These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjGetCollapsedPatientDataframeColumns
<commit_msg>Add phjCollapseOnPatientID and remove phjGetCollapsedPatientDataframeColumns<commit_after># These are the functions that can be accessed from epydemiology.
# Other functions that are used internally cannot be accessed
# directly by end-users.
from .phjCalculateProportions import phjCalculateBinomialProportions
from .phjCalculateProportions import phjCalculateMultinomialProportions
from .phjCleanData import phjParseDateVar
from .phjCleanUKPostcodes import phjCleanUKPostcodeVariable
from .phjCleanUKPostcodes import phjPostcodeFormat7
from .phjExploreData import phjViewLogOdds
from .phjExploreData import phjCategoriseContinuousVariable
from .phjExtFuncs import getJenksBreaks
from .phjGetData import phjReadDataFromExcelNamedCellRange
from .phjGetDBData import phjGetDataFromDatabase
from .phjMatrices import phjBinaryVarsToSquareMatrix
from .phjMiscFuncs import phjGetStrFromArgOrFile
from .phjMiscFuncs import phjReadTextFromFile
from .phjMiscFuncs import phjCreateNamedGroupRegex
from .phjMiscFuncs import phjFindRegexNamedGroups
from .phjMiscFuncs import phjMaxLevelOfTaxonomicDetail
from .phjRROR import phjOddsRatio
from .phjRROR import phjRelativeRisk
from .phjSelectData import phjSelectCaseControlDataset
from .phjSelectData import phjGenerateCaseControlDataset
from .phjSelectData import phjCollapseOnPatientID
|
c147751066d8fb4e36a30f26d0acc614f0b2275f
|
transfers/models.py
|
transfers/models.py
|
import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Boolean, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Text())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
|
import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Binary, Boolean, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Binary())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
|
Automate Transfers: Paths stored as binary to handle encodings
|
Automate Transfers: Paths stored as binary to handle encodings
|
Python
|
agpl-3.0
|
artefactual/automation-tools,finoradin/automation-tools,artefactual/automation-tools
|
import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Boolean, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Text())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
Automate Transfers: Paths stored as binary to handle encodings
|
import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Binary, Boolean, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Binary())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
|
<commit_before>import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Boolean, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Text())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
<commit_msg>Automate Transfers: Paths stored as binary to handle encodings<commit_after>
|
import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Binary, Boolean, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Binary())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
|
import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Boolean, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Text())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
Automate Transfers: Paths stored as binary to handle encodingsimport os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Binary, Boolean, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Binary())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
|
<commit_before>import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Boolean, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Text())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
<commit_msg>Automate Transfers: Paths stored as binary to handle encodings<commit_after>import os
from sqlalchemy import create_engine
from sqlalchemy import Sequence
from sqlalchemy import Column, Binary, Boolean, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
db_path = os.path.join(os.path.dirname(__file__), 'transfers.db')
engine = create_engine('sqlite:///{}'.format(db_path), echo=False)
Session = sessionmaker(bind=engine)
Base = declarative_base()
class Unit(Base):
__tablename__ = 'unit'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
uuid = Column(String(36))
path = Column(Binary())
unit_type = Column(String(10)) # ingest or transfer
status = Column(String(20), nullable=True)
current = Column(Boolean(create_constraint=False))
def __repr__(self):
return "<Unit(id={s.id}, uuid={s.uuid}, unit_type={s.unit_type}, path={s.path}, status={s.status}, current={s.current})>".format(s=self)
Base.metadata.create_all(engine)
|
22173c249ea0ee8eeceb9238f8f7418b7c3b29d8
|
misp_modules/modules/expansion/hashdd.py
|
misp_modules/modules/expansion/hashdd.py
|
import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5'], 'output': ['text']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
request = json.loads(q)
if not request.get('md5'):
misperrors['error'] = 'MD5 hash value is missing missing'
return misperrors
v = request.get('md5').upper()
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5', 'sha1', 'sha256'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
v = None
request = json.loads(q)
for input_type in mispattributes['input']:
if request.get(input_type):
v = request[input_type].upper()
break
if v is None:
misperrors['error'] = 'Hash value is missing.'
return misperrors
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
Update to support sha1 & sha256 attributes
|
add: Update to support sha1 & sha256 attributes
|
Python
|
agpl-3.0
|
VirusTotal/misp-modules,amuehlem/misp-modules,MISP/misp-modules,amuehlem/misp-modules,MISP/misp-modules,MISP/misp-modules,VirusTotal/misp-modules,VirusTotal/misp-modules,amuehlem/misp-modules
|
import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5'], 'output': ['text']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
request = json.loads(q)
if not request.get('md5'):
misperrors['error'] = 'MD5 hash value is missing missing'
return misperrors
v = request.get('md5').upper()
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
add: Update to support sha1 & sha256 attributes
|
import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5', 'sha1', 'sha256'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
v = None
request = json.loads(q)
for input_type in mispattributes['input']:
if request.get(input_type):
v = request[input_type].upper()
break
if v is None:
misperrors['error'] = 'Hash value is missing.'
return misperrors
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
<commit_before>import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5'], 'output': ['text']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
request = json.loads(q)
if not request.get('md5'):
misperrors['error'] = 'MD5 hash value is missing missing'
return misperrors
v = request.get('md5').upper()
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
<commit_msg>add: Update to support sha1 & sha256 attributes<commit_after>
|
import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5', 'sha1', 'sha256'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
v = None
request = json.loads(q)
for input_type in mispattributes['input']:
if request.get(input_type):
v = request[input_type].upper()
break
if v is None:
misperrors['error'] = 'Hash value is missing.'
return misperrors
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5'], 'output': ['text']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
request = json.loads(q)
if not request.get('md5'):
misperrors['error'] = 'MD5 hash value is missing missing'
return misperrors
v = request.get('md5').upper()
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
add: Update to support sha1 & sha256 attributesimport json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5', 'sha1', 'sha256'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
v = None
request = json.loads(q)
for input_type in mispattributes['input']:
if request.get(input_type):
v = request[input_type].upper()
break
if v is None:
misperrors['error'] = 'Hash value is missing.'
return misperrors
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
<commit_before>import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5'], 'output': ['text']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
request = json.loads(q)
if not request.get('md5'):
misperrors['error'] = 'MD5 hash value is missing missing'
return misperrors
v = request.get('md5').upper()
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
<commit_msg>add: Update to support sha1 & sha256 attributes<commit_after>import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5', 'sha1', 'sha256'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = []
hashddapi_url = 'https://api.hashdd.com/'
def handler(q=False):
if q is False:
return False
v = None
request = json.loads(q)
for input_type in mispattributes['input']:
if request.get(input_type):
v = request[input_type].upper()
break
if v is None:
misperrors['error'] = 'Hash value is missing.'
return misperrors
r = requests.post(hashddapi_url, data={'hash':v})
if r.status_code == 200:
state = json.loads(r.text)
if state:
if state.get(v):
summary = state[v]['known_level']
else:
summary = 'Unknown hash'
else:
misperrors['error'] = '{} API not accessible'.format(hashddapi_url)
return misperrors['error']
r = {'results': [{'types': mispattributes['output'], 'values': summary}]}
return r
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo
|
abf48b4c3ab7c78e44bc2d28ef6f3271c00abc42
|
ylio/__init__.py
|
ylio/__init__.py
|
from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('DEBUG', False):
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
|
from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('SERVER_NAME') is None:
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
|
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False
|
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False
|
Python
|
mit
|
joealcorn/yl.io,joealcorn/yl.io
|
from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('DEBUG', False):
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False
|
from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('SERVER_NAME') is None:
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
|
<commit_before>from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('DEBUG', False):
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
<commit_msg>Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False<commit_after>
|
from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('SERVER_NAME') is None:
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
|
from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('DEBUG', False):
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is Falsefrom flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('SERVER_NAME') is None:
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
|
<commit_before>from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('DEBUG', False):
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
<commit_msg>Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False<commit_after>from flask import Flask
from flask.ext.assets import Environment, Bundle
app = Flask(__name__, static_folder=None)
app.config.from_pyfile('config.py')
# Route static folder to /static in dev
# and a subdomain in production
app.static_folder = 'static'
static_path = '/<path:filename>'
static_subdomain = 'static'
if app.config.get('SERVER_NAME') is None:
static_path = '/static/<path:filename>'
static_subdomain = None
app.add_url_rule(
static_path,
endpoint='static',
subdomain=static_subdomain,
view_func=app.send_static_file
)
assets = Environment(app)
js = Bundle(
'js/colorpicker.js',
'js/modernizr.js',
'js/lightordark.js',
'js/ylio.js',
filters='jsmin',
output='scripts.js'
)
css = Bundle(
'css/colorpicker.css',
'css/ylio.css',
filters='cssmin',
output='styles.css'
)
assets.register('js', js)
assets.register('css', css)
import ylio.views
|
d002011c68032dc2255f83f39c03da61c3f72525
|
yolk/__init__.py
|
yolk/__init__.py
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.5'
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.6'
|
Increment patch version to 0.8.6
|
Increment patch version to 0.8.6
|
Python
|
bsd-3-clause
|
myint/yolk,myint/yolk
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.5'
Increment patch version to 0.8.6
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.6'
|
<commit_before>"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.5'
<commit_msg>Increment patch version to 0.8.6<commit_after>
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.6'
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.5'
Increment patch version to 0.8.6"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.6'
|
<commit_before>"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.5'
<commit_msg>Increment patch version to 0.8.6<commit_after>"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.6'
|
c3c1234fb566ad20d7e67e55f8d8d908dbda55ad
|
post/urls.py
|
post/urls.py
|
from django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
|
from django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<category_slug>[\w-]+)/(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_categorized_object_detail'
),
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
|
Add post categorized view urlconf
|
Add post categorized view urlconf
|
Python
|
bsd-3-clause
|
praekelt/jmbo-post,praekelt/jmbo-post
|
from django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
Add post categorized view urlconf
|
from django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<category_slug>[\w-]+)/(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_categorized_object_detail'
),
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
|
<commit_before>from django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
<commit_msg>Add post categorized view urlconf<commit_after>
|
from django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<category_slug>[\w-]+)/(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_categorized_object_detail'
),
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
|
from django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
Add post categorized view urlconffrom django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<category_slug>[\w-]+)/(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_categorized_object_detail'
),
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
|
<commit_before>from django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
<commit_msg>Add post categorized view urlconf<commit_after>from django.conf.urls import patterns, include, url
from jmbo.urls import v1_api
from jmbo.views import ObjectDetail
from post.api import PostResource
v1_api.register(PostResource())
# xxx: may need to include ckeditor urls here. check!
urlpatterns = patterns(
'',
url(
r'^(?P<category_slug>[\w-]+)/(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_categorized_object_detail'
),
url(
r'^(?P<slug>[\w-]+)/$',
ObjectDetail.as_view(),
name='post_object_detail'
),
)
|
63109e4d91f66c135c634752d3feb0e6dd4b9b97
|
nn/models/char2doc.py
|
nn/models/char2doc.py
|
import tensorflow as tf
from ..embedding import embeddings_to_embedding, ids_to_embeddings, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(forward_document,
backward_document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
def char_ids_to_doc_embedding(document):
return embeddings_to_embedding(
ids_to_embeddings(document, char_embeddings),
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
document_embedding = tf.concat(
1,
list(map(char_ids_to_doc_embedding,
[forward_document, backward_document])))
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
|
import tensorflow as tf
from ..embedding import id_sequence_to_embedding, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
document_embedding = id_sequence_to_embedding(
document,
char_embeddings,
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
|
Use id_sequence_to_embedding and only forward document
|
Use id_sequence_to_embedding and only forward document
|
Python
|
unlicense
|
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
|
import tensorflow as tf
from ..embedding import embeddings_to_embedding, ids_to_embeddings, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(forward_document,
backward_document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
def char_ids_to_doc_embedding(document):
return embeddings_to_embedding(
ids_to_embeddings(document, char_embeddings),
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
document_embedding = tf.concat(
1,
list(map(char_ids_to_doc_embedding,
[forward_document, backward_document])))
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
Use id_sequence_to_embedding and only forward document
|
import tensorflow as tf
from ..embedding import id_sequence_to_embedding, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
document_embedding = id_sequence_to_embedding(
document,
char_embeddings,
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
|
<commit_before>import tensorflow as tf
from ..embedding import embeddings_to_embedding, ids_to_embeddings, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(forward_document,
backward_document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
def char_ids_to_doc_embedding(document):
return embeddings_to_embedding(
ids_to_embeddings(document, char_embeddings),
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
document_embedding = tf.concat(
1,
list(map(char_ids_to_doc_embedding,
[forward_document, backward_document])))
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
<commit_msg>Use id_sequence_to_embedding and only forward document<commit_after>
|
import tensorflow as tf
from ..embedding import id_sequence_to_embedding, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
document_embedding = id_sequence_to_embedding(
document,
char_embeddings,
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
|
import tensorflow as tf
from ..embedding import embeddings_to_embedding, ids_to_embeddings, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(forward_document,
backward_document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
def char_ids_to_doc_embedding(document):
return embeddings_to_embedding(
ids_to_embeddings(document, char_embeddings),
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
document_embedding = tf.concat(
1,
list(map(char_ids_to_doc_embedding,
[forward_document, backward_document])))
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
Use id_sequence_to_embedding and only forward documentimport tensorflow as tf
from ..embedding import id_sequence_to_embedding, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
document_embedding = id_sequence_to_embedding(
document,
char_embeddings,
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
|
<commit_before>import tensorflow as tf
from ..embedding import embeddings_to_embedding, ids_to_embeddings, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(forward_document,
backward_document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
def char_ids_to_doc_embedding(document):
return embeddings_to_embedding(
ids_to_embeddings(document, char_embeddings),
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
document_embedding = tf.concat(
1,
list(map(char_ids_to_doc_embedding,
[forward_document, backward_document])))
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
<commit_msg>Use id_sequence_to_embedding and only forward document<commit_after>import tensorflow as tf
from ..embedding import id_sequence_to_embedding, embeddings
from ..linear import linear
from ..dropout import dropout
def char2doc(document,
*,
char_space_size,
char_embedding_size,
document_embedding_size,
dropout_prob,
hidden_layer_size,
output_layer_size,
context_vector_size):
with tf.variable_scope("char2doc"):
char_embeddings = embeddings(id_space_size=char_space_size,
embedding_size=char_embedding_size)
document_embedding = id_sequence_to_embedding(
document,
char_embeddings,
output_embedding_size=document_embedding_size,
context_vector_size=context_vector_size)
hidden_layer = dropout(_activate(linear(_activate(document_embedding),
hidden_layer_size)),
dropout_prob)
return linear(hidden_layer, output_layer_size)
def _activate(tensor):
return tf.nn.elu(tensor)
|
76bc58d577e6d529dff3fc770667897bc48f6bfc
|
mainPage.py
|
mainPage.py
|
import sys
from Tkinter import *
mainWindow = Tk()
windowWidth = 700
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
|
import sys
from Tkinter import *
# Define click functions
def clickHome():
topLabelText.set("Home Screen")
return
def clickConstraint():
topLabelText.set("Constraint Screen")
return
def clickView():
topLabelText.set("View Screen")
return
def clickMisc():
topLabelText.set("Misc Screen")
return
def clickRun():
# run the scheduler
topLabelText.set("Scheduler should be running...")
return
mainWindow = Tk()
windowWidth = 850
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
topLabelText = StringVar()
topLabelText.set("You have just begun!")
topLabel = Label(mainWindow, textvariable = topLabelText)
topLabel.grid(row = 0, column = 2)
homeButton = Button(mainWindow, text = "Home", width = 15, height = 5, command = clickHome)
homeButton.grid(row = 0, column = 0)
constraintButton = Button(mainWindow, text = "Constraint", width = 15, height = 5, command = clickConstraint)
constraintButton.grid(row = 1, column = 0)
viewButton = Button(mainWindow, text = "View", width = 15, height = 5, command = clickView)
viewButton.grid(row = 2, column = 0)
miscButton = Button(mainWindow, text = "...", width = 15, height = 5, command = clickMisc)
miscButton.grid(row = 3, column = 0)
runButton = Button(mainWindow, text = "RUN", width = 15, height = 10, bg = "green", command = clickRun)
runButton.grid(row = 4, column = 0)
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
|
Add side buttons, changing header label on click
|
Add side buttons, changing header label on click
|
Python
|
mit
|
donnell74/CSC-450-Scheduler
|
import sys
from Tkinter import *
mainWindow = Tk()
windowWidth = 700
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
Add side buttons, changing header label on click
|
import sys
from Tkinter import *
# Define click functions
def clickHome():
topLabelText.set("Home Screen")
return
def clickConstraint():
topLabelText.set("Constraint Screen")
return
def clickView():
topLabelText.set("View Screen")
return
def clickMisc():
topLabelText.set("Misc Screen")
return
def clickRun():
# run the scheduler
topLabelText.set("Scheduler should be running...")
return
mainWindow = Tk()
windowWidth = 850
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
topLabelText = StringVar()
topLabelText.set("You have just begun!")
topLabel = Label(mainWindow, textvariable = topLabelText)
topLabel.grid(row = 0, column = 2)
homeButton = Button(mainWindow, text = "Home", width = 15, height = 5, command = clickHome)
homeButton.grid(row = 0, column = 0)
constraintButton = Button(mainWindow, text = "Constraint", width = 15, height = 5, command = clickConstraint)
constraintButton.grid(row = 1, column = 0)
viewButton = Button(mainWindow, text = "View", width = 15, height = 5, command = clickView)
viewButton.grid(row = 2, column = 0)
miscButton = Button(mainWindow, text = "...", width = 15, height = 5, command = clickMisc)
miscButton.grid(row = 3, column = 0)
runButton = Button(mainWindow, text = "RUN", width = 15, height = 10, bg = "green", command = clickRun)
runButton.grid(row = 4, column = 0)
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
|
<commit_before>import sys
from Tkinter import *
mainWindow = Tk()
windowWidth = 700
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
<commit_msg>Add side buttons, changing header label on click<commit_after>
|
import sys
from Tkinter import *
# Define click functions
def clickHome():
topLabelText.set("Home Screen")
return
def clickConstraint():
topLabelText.set("Constraint Screen")
return
def clickView():
topLabelText.set("View Screen")
return
def clickMisc():
topLabelText.set("Misc Screen")
return
def clickRun():
# run the scheduler
topLabelText.set("Scheduler should be running...")
return
mainWindow = Tk()
windowWidth = 850
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
topLabelText = StringVar()
topLabelText.set("You have just begun!")
topLabel = Label(mainWindow, textvariable = topLabelText)
topLabel.grid(row = 0, column = 2)
homeButton = Button(mainWindow, text = "Home", width = 15, height = 5, command = clickHome)
homeButton.grid(row = 0, column = 0)
constraintButton = Button(mainWindow, text = "Constraint", width = 15, height = 5, command = clickConstraint)
constraintButton.grid(row = 1, column = 0)
viewButton = Button(mainWindow, text = "View", width = 15, height = 5, command = clickView)
viewButton.grid(row = 2, column = 0)
miscButton = Button(mainWindow, text = "...", width = 15, height = 5, command = clickMisc)
miscButton.grid(row = 3, column = 0)
runButton = Button(mainWindow, text = "RUN", width = 15, height = 10, bg = "green", command = clickRun)
runButton.grid(row = 4, column = 0)
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
|
import sys
from Tkinter import *
mainWindow = Tk()
windowWidth = 700
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
Add side buttons, changing header label on clickimport sys
from Tkinter import *
# Define click functions
def clickHome():
topLabelText.set("Home Screen")
return
def clickConstraint():
topLabelText.set("Constraint Screen")
return
def clickView():
topLabelText.set("View Screen")
return
def clickMisc():
topLabelText.set("Misc Screen")
return
def clickRun():
# run the scheduler
topLabelText.set("Scheduler should be running...")
return
mainWindow = Tk()
windowWidth = 850
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
topLabelText = StringVar()
topLabelText.set("You have just begun!")
topLabel = Label(mainWindow, textvariable = topLabelText)
topLabel.grid(row = 0, column = 2)
homeButton = Button(mainWindow, text = "Home", width = 15, height = 5, command = clickHome)
homeButton.grid(row = 0, column = 0)
constraintButton = Button(mainWindow, text = "Constraint", width = 15, height = 5, command = clickConstraint)
constraintButton.grid(row = 1, column = 0)
viewButton = Button(mainWindow, text = "View", width = 15, height = 5, command = clickView)
viewButton.grid(row = 2, column = 0)
miscButton = Button(mainWindow, text = "...", width = 15, height = 5, command = clickMisc)
miscButton.grid(row = 3, column = 0)
runButton = Button(mainWindow, text = "RUN", width = 15, height = 10, bg = "green", command = clickRun)
runButton.grid(row = 4, column = 0)
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
|
<commit_before>import sys
from Tkinter import *
mainWindow = Tk()
windowWidth = 700
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
<commit_msg>Add side buttons, changing header label on click<commit_after>import sys
from Tkinter import *
# Define click functions
def clickHome():
topLabelText.set("Home Screen")
return
def clickConstraint():
topLabelText.set("Constraint Screen")
return
def clickView():
topLabelText.set("View Screen")
return
def clickMisc():
topLabelText.set("Misc Screen")
return
def clickRun():
# run the scheduler
topLabelText.set("Scheduler should be running...")
return
mainWindow = Tk()
windowWidth = 850
windowHeight = 600
screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2)
screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2)
mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\
'+' + str(screenXpos) + '+' + str(screenYpos))
mainWindow.title('CSC Scheduler')
topLabelText = StringVar()
topLabelText.set("You have just begun!")
topLabel = Label(mainWindow, textvariable = topLabelText)
topLabel.grid(row = 0, column = 2)
homeButton = Button(mainWindow, text = "Home", width = 15, height = 5, command = clickHome)
homeButton.grid(row = 0, column = 0)
constraintButton = Button(mainWindow, text = "Constraint", width = 15, height = 5, command = clickConstraint)
constraintButton.grid(row = 1, column = 0)
viewButton = Button(mainWindow, text = "View", width = 15, height = 5, command = clickView)
viewButton.grid(row = 2, column = 0)
miscButton = Button(mainWindow, text = "...", width = 15, height = 5, command = clickMisc)
miscButton.grid(row = 3, column = 0)
runButton = Button(mainWindow, text = "RUN", width = 15, height = 10, bg = "green", command = clickRun)
runButton.grid(row = 4, column = 0)
mainWindow.mainloop() # NEED FOR MAC OSX AND WINDOWS
|
9bc3b7b24e185b1dd8bf8f979c8341fb332a401f
|
mm1_main.py
|
mm1_main.py
|
#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
seed = args.seed
### Params
# Mean interarrival rate of customers per second;
# hence, 0.05 <=> 3 people/minute
interarrival_rate = 0.05
# Mean service rate by the teller per second;
# hence, 0.1 <=> 6 people/minute
service_rate = 0.1
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
|
#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('int_rate', metavar='interarrival_rate',
type=int, help='mean packet interarrival rate in seconds')
parser.add_argument('sr_rate', metavar='service_rate',
type=int, help='mean packet service rate in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
interarrival_rate = args.int_rate
service_rate = args.sr_rate
seed = args.seed
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
|
Add arguments for interarrival and service rates.
|
Add arguments for interarrival and service rates.
|
Python
|
mit
|
kubkon/des-in-python
|
#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
seed = args.seed
### Params
# Mean interarrival rate of customers per second;
# hence, 0.05 <=> 3 people/minute
interarrival_rate = 0.05
# Mean service rate by the teller per second;
# hence, 0.1 <=> 6 people/minute
service_rate = 0.1
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
Add arguments for interarrival and service rates.
|
#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('int_rate', metavar='interarrival_rate',
type=int, help='mean packet interarrival rate in seconds')
parser.add_argument('sr_rate', metavar='service_rate',
type=int, help='mean packet service rate in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
interarrival_rate = args.int_rate
service_rate = args.sr_rate
seed = args.seed
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
|
<commit_before>#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
seed = args.seed
### Params
# Mean interarrival rate of customers per second;
# hence, 0.05 <=> 3 people/minute
interarrival_rate = 0.05
# Mean service rate by the teller per second;
# hence, 0.1 <=> 6 people/minute
service_rate = 0.1
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
<commit_msg>Add arguments for interarrival and service rates.<commit_after>
|
#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('int_rate', metavar='interarrival_rate',
type=int, help='mean packet interarrival rate in seconds')
parser.add_argument('sr_rate', metavar='service_rate',
type=int, help='mean packet service rate in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
interarrival_rate = args.int_rate
service_rate = args.sr_rate
seed = args.seed
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
|
#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
seed = args.seed
### Params
# Mean interarrival rate of customers per second;
# hence, 0.05 <=> 3 people/minute
interarrival_rate = 0.05
# Mean service rate by the teller per second;
# hence, 0.1 <=> 6 people/minute
service_rate = 0.1
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
Add arguments for interarrival and service rates.#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('int_rate', metavar='interarrival_rate',
type=int, help='mean packet interarrival rate in seconds')
parser.add_argument('sr_rate', metavar='service_rate',
type=int, help='mean packet service rate in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
interarrival_rate = args.int_rate
service_rate = args.sr_rate
seed = args.seed
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
|
<commit_before>#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
seed = args.seed
### Params
# Mean interarrival rate of customers per second;
# hence, 0.05 <=> 3 people/minute
interarrival_rate = 0.05
# Mean service rate by the teller per second;
# hence, 0.1 <=> 6 people/minute
service_rate = 0.1
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
<commit_msg>Add arguments for interarrival and service rates.<commit_after>#!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simulation duration in seconds')
parser.add_argument('int_rate', metavar='interarrival_rate',
type=int, help='mean packet interarrival rate in seconds')
parser.add_argument('sr_rate', metavar='service_rate',
type=int, help='mean packet service rate in seconds')
parser.add_argument('--seed', dest='seed', default=int(round(time.time())),
type=int, help='seed for the PRNG (default: current system timestamp)')
args = parser.parse_args()
sim_duration = args.sim_duration
interarrival_rate = args.int_rate
service_rate = args.sr_rate
seed = args.seed
### Initialize
# Create new simulation engine
se = sim.SimulationEngine()
# Seed default PRNG
se.prng.seed = seed
# Create MM1 specific event handler
event_handler = mm1.MM1EventHandler()
event_handler.interarrival_rate = interarrival_rate
event_handler.service_rate = service_rate
### Simulate
# Schedule finishing event
se.stop(sim_duration)
# Start simulating
se.start()
|
1eb20f6d1a946acbf05be003c597e40aa1782b4d
|
engine/plugins/https.py
|
engine/plugins/https.py
|
from .. import config
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
print(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
print("Timeout")
return False
print("Bad checksum")
return False
|
from .. import config
import logging
logger=logging.getLogger(__name__)
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
logger.debug(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
logger.debug("Timeout")
return False
logger.debug("Bad checksum")
return False
|
Use logger rather than raw print
|
Use logger rather than raw print
|
Python
|
mit
|
ainterr/scoring_engine,ainterr/scoring_engine,ainterr/scoring_engine,ainterr/scoring_engine
|
from .. import config
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
print(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
print("Timeout")
return False
print("Bad checksum")
return False
Use logger rather than raw print
|
from .. import config
import logging
logger=logging.getLogger(__name__)
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
logger.debug(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
logger.debug("Timeout")
return False
logger.debug("Bad checksum")
return False
|
<commit_before>from .. import config
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
print(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
print("Timeout")
return False
print("Bad checksum")
return False
<commit_msg>Use logger rather than raw print<commit_after>
|
from .. import config
import logging
logger=logging.getLogger(__name__)
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
logger.debug(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
logger.debug("Timeout")
return False
logger.debug("Bad checksum")
return False
|
from .. import config
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
print(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
print("Timeout")
return False
print("Bad checksum")
return False
Use logger rather than raw printfrom .. import config
import logging
logger=logging.getLogger(__name__)
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
logger.debug(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
logger.debug("Timeout")
return False
logger.debug("Bad checksum")
return False
|
<commit_before>from .. import config
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
print(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
print("Timeout")
return False
print("Bad checksum")
return False
<commit_msg>Use logger rather than raw print<commit_after>from .. import config
import logging
logger=logging.getLogger(__name__)
import requests
from requests.exceptions import *
import hashlib, random
def run(options):
ip = options['ip']
port = options['port']
test = random.choice(config.HTTPS_PAGES)
try:
r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2)
if r.status_code is not 200:
logger.debug(r.status_code)
return False
sha1 = hashlib.sha1()
sha1.update(r.content)
checksum = sha1.hexdigest()
if checksum == test['checksum']:
return True
except Timeout:
logger.debug("Timeout")
return False
logger.debug("Bad checksum")
return False
|
051695d90b241323e650cd4931187de1750d924b
|
dataportal/tests/test_broker.py
|
dataportal/tests/test_broker.py
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..broker.simple_broker import POPULAR_CHANNELS
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(POPULAR_CHANNELS, start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
Update tests after major broker refactor.
|
FIX: Update tests after major broker refactor.
|
Python
|
bsd-3-clause
|
NSLS-II/dataportal,ericdill/datamuxer,ericdill/datamuxer,danielballan/datamuxer,danielballan/datamuxer,NSLS-II/datamuxer,danielballan/dataportal,tacaswell/dataportal,tacaswell/dataportal,ericdill/databroker,ericdill/databroker,danielballan/dataportal,NSLS-II/dataportal
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..broker.simple_broker import POPULAR_CHANNELS
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(POPULAR_CHANNELS, start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
FIX: Update tests after major broker refactor.
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
<commit_before>import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..broker.simple_broker import POPULAR_CHANNELS
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(POPULAR_CHANNELS, start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
<commit_msg>FIX: Update tests after major broker refactor.<commit_after>
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..broker.simple_broker import POPULAR_CHANNELS
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(POPULAR_CHANNELS, start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
FIX: Update tests after major broker refactor.import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
<commit_before>import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..broker.simple_broker import POPULAR_CHANNELS
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(POPULAR_CHANNELS, start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
<commit_msg>FIX: Update tests after major broker refactor.<commit_after>import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
eed413229978523b41a637c68c34100a31270643
|
scripts/TestHarness/testers/RavenUtils.py
|
scripts/TestHarness/testers/RavenUtils.py
|
import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.4")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
|
import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.3")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
|
Decrease the needed matplotlib to 1.3, to make it easier to get installed.
|
Decrease the needed matplotlib to 1.3, to make it easier to get installed.
|
Python
|
apache-2.0
|
joshua-cogliati-inl/raven,idaholab/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,idaholab/raven,idaholab/raven,idaholab/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,idaholab/raven
|
import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.4")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
Decrease the needed matplotlib to 1.3, to make it easier to get installed.
|
import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.3")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
|
<commit_before>import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.4")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
<commit_msg>Decrease the needed matplotlib to 1.3, to make it easier to get installed.<commit_after>
|
import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.3")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
|
import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.4")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
Decrease the needed matplotlib to 1.3, to make it easier to get installed.import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.3")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
|
<commit_before>import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.4")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
<commit_msg>Decrease the needed matplotlib to 1.3, to make it easier to get installed.<commit_after>import os
import subprocess
def inPython3():
return os.environ.get("CHECK_PYTHON3","0") == "1"
def checkForMissingModules():
missing = []
too_old = []
to_try = [("numpy",'numpy.version.version',"1.7"),
("h5py",'',''),
("scipy",'scipy.__version__',"0.12"),
("sklearn",'sklearn.__version__',"0.14"),
("matplotlib",'matplotlib.__version__',"1.3")]
for i,fv,ev in to_try:
if len(fv) > 0:
check = ';import sys; sys.exit(not '+fv+' >= "'+ev+'")'
else:
check = ''
if inPython3():
python = 'python3'
else:
python = 'python'
result = subprocess.call([python,'-c','import '+i])
if result != 0:
missing.append(i)
else:
result = subprocess.call([python,'-c','import '+i+check])
if result != 0:
too_old.append(i+" should be at least version "+ev)
return missing,too_old
|
453abc420db1a9daf3b8d92d7f8ee8a8ace5bf9f
|
07/test_address.py
|
07/test_address.py
|
import unittest
from address import has_reflection, is_compatible
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
|
import unittest
from address import has_reflection, is_compatible, load_addresses
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
assert is_compatible('aba[bab]xyz', protocol=2) == True
assert is_compatible('xyx[xyx]xyx', protocol=2) == False
assert is_compatible('aaa[kek]eke', protocol=2) == True
assert is_compatible('zazbz[bzb]cdb', protocol=2) == True
def test_load_addresses(self):
assert len(load_addresses())
|
Add tests for second protocol.
|
Add tests for second protocol.
|
Python
|
mit
|
machinelearningdeveloper/aoc_2016
|
import unittest
from address import has_reflection, is_compatible
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
Add tests for second protocol.
|
import unittest
from address import has_reflection, is_compatible, load_addresses
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
assert is_compatible('aba[bab]xyz', protocol=2) == True
assert is_compatible('xyx[xyx]xyx', protocol=2) == False
assert is_compatible('aaa[kek]eke', protocol=2) == True
assert is_compatible('zazbz[bzb]cdb', protocol=2) == True
def test_load_addresses(self):
assert len(load_addresses())
|
<commit_before>import unittest
from address import has_reflection, is_compatible
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
<commit_msg>Add tests for second protocol.<commit_after>
|
import unittest
from address import has_reflection, is_compatible, load_addresses
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
assert is_compatible('aba[bab]xyz', protocol=2) == True
assert is_compatible('xyx[xyx]xyx', protocol=2) == False
assert is_compatible('aaa[kek]eke', protocol=2) == True
assert is_compatible('zazbz[bzb]cdb', protocol=2) == True
def test_load_addresses(self):
assert len(load_addresses())
|
import unittest
from address import has_reflection, is_compatible
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
Add tests for second protocol.import unittest
from address import has_reflection, is_compatible, load_addresses
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
assert is_compatible('aba[bab]xyz', protocol=2) == True
assert is_compatible('xyx[xyx]xyx', protocol=2) == False
assert is_compatible('aaa[kek]eke', protocol=2) == True
assert is_compatible('zazbz[bzb]cdb', protocol=2) == True
def test_load_addresses(self):
assert len(load_addresses())
|
<commit_before>import unittest
from address import has_reflection, is_compatible
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
<commit_msg>Add tests for second protocol.<commit_after>import unittest
from address import has_reflection, is_compatible, load_addresses
class TestAddress(unittest.TestCase):
def test_has_reflection(self):
assert has_reflection(['mnop']) == False
assert has_reflection(['abba', 'qrst']) == True
def test_is_compatible(self):
assert is_compatible('abba[mnop]qrst') == True
assert is_compatible('abcd[bddb]xyyx') == False
assert is_compatible('aaaa[qwer]tyui') == False
assert is_compatible('ioxxoj[asdfgh]zxcvbn') == True
assert is_compatible('aba[bab]xyz', protocol=2) == True
assert is_compatible('xyx[xyx]xyx', protocol=2) == False
assert is_compatible('aaa[kek]eke', protocol=2) == True
assert is_compatible('zazbz[bzb]cdb', protocol=2) == True
def test_load_addresses(self):
assert len(load_addresses())
|
e152213012c95dd820b341d11d940a172ca467d0
|
ethereum/tests/test_tester.py
|
ethereum/tests/test_tester.py
|
# -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import get_solidity, compile_file
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
simple_compiled = compile_file(contract_path)
simple_address = tester_state.evm(simple_compiled['Simple']['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_compiled['Simple']['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
|
# -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import (
get_solidity,
compile_file,
solidity_get_contract_data,
)
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
contract_name = 'Simple'
simple_compiled = compile_file(contract_path)
simple_data = solidity_get_contract_data(
simple_compiled,
contract_path,
contract_name,
)
simple_address = tester_state.evm(simple_data['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_data['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
|
Adjust test to new compiler versions
|
Adjust test to new compiler versions
|
Python
|
mit
|
ethereum/pyethereum,ethereum/pyethereum,karlfloersch/pyethereum,karlfloersch/pyethereum
|
# -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import get_solidity, compile_file
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
simple_compiled = compile_file(contract_path)
simple_address = tester_state.evm(simple_compiled['Simple']['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_compiled['Simple']['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
Adjust test to new compiler versions
|
# -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import (
get_solidity,
compile_file,
solidity_get_contract_data,
)
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
contract_name = 'Simple'
simple_compiled = compile_file(contract_path)
simple_data = solidity_get_contract_data(
simple_compiled,
contract_path,
contract_name,
)
simple_address = tester_state.evm(simple_data['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_data['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
|
<commit_before># -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import get_solidity, compile_file
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
simple_compiled = compile_file(contract_path)
simple_address = tester_state.evm(simple_compiled['Simple']['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_compiled['Simple']['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
<commit_msg>Adjust test to new compiler versions<commit_after>
|
# -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import (
get_solidity,
compile_file,
solidity_get_contract_data,
)
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
contract_name = 'Simple'
simple_compiled = compile_file(contract_path)
simple_data = solidity_get_contract_data(
simple_compiled,
contract_path,
contract_name,
)
simple_address = tester_state.evm(simple_data['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_data['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
|
# -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import get_solidity, compile_file
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
simple_compiled = compile_file(contract_path)
simple_address = tester_state.evm(simple_compiled['Simple']['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_compiled['Simple']['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
Adjust test to new compiler versions# -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import (
get_solidity,
compile_file,
solidity_get_contract_data,
)
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
contract_name = 'Simple'
simple_compiled = compile_file(contract_path)
simple_data = solidity_get_contract_data(
simple_compiled,
contract_path,
contract_name,
)
simple_address = tester_state.evm(simple_data['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_data['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
|
<commit_before># -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import get_solidity, compile_file
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
simple_compiled = compile_file(contract_path)
simple_address = tester_state.evm(simple_compiled['Simple']['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_compiled['Simple']['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
<commit_msg>Adjust test to new compiler versions<commit_after># -*- coding: utf8 -*-
import json
from os import path
import pytest
from ethereum.tester import state, ABIContract
from ethereum._solidity import (
get_solidity,
compile_file,
solidity_get_contract_data,
)
SOLIDITY_AVAILABLE = get_solidity() is not None
CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts')
@pytest.mark.skipif(not SOLIDITY_AVAILABLE, reason='solc compiler not available')
def test_abicontract_interface():
""" Test for issue #370. """
tester_state = state()
contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol')
contract_name = 'Simple'
simple_compiled = compile_file(contract_path)
simple_data = solidity_get_contract_data(
simple_compiled,
contract_path,
contract_name,
)
simple_address = tester_state.evm(simple_data['bin'])
# ABIContract class must accept json_abi
abi_json = json.dumps(simple_data['abi']).encode('utf-8')
abi = ABIContract(
_state=tester_state,
_abi=abi_json,
address=simple_address,
listen=False,
log_listener=None,
default_key=None,
)
assert abi.test() == 1 # pylint: disable=no-member
|
c297b219c7ae4f3e6ad3428425950c66f2832ff7
|
xgds_video/tests.py
|
xgds_video/tests.py
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(False)
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(True)
|
Change assert(False) to assert(True) to avoid having test fail no matter what
|
Change assert(False) to assert(True) to avoid having test fail no matter what
|
Python
|
apache-2.0
|
xgds/xgds_video,xgds/xgds_video,xgds/xgds_video
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(False)
Change assert(False) to assert(True) to avoid having test fail no matter what
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(True)
|
<commit_before># __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(False)
<commit_msg>Change assert(False) to assert(True) to avoid having test fail no matter what<commit_after>
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(True)
|
# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(False)
Change assert(False) to assert(True) to avoid having test fail no matter what# __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(True)
|
<commit_before># __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(False)
<commit_msg>Change assert(False) to assert(True) to avoid having test fail no matter what<commit_after># __BEGIN_LICENSE__
# Copyright (C) 2008-2010 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from django.test import TestCase
class xgds_videoTest(TestCase):
"""
Tests for xgds_video
"""
def test_xgds_video(self):
print "testing git hook 7 in xgds_video"
assert(True)
|
11d25c3f4391d3e9eb95c5b8fb1a2b73cbf123a0
|
cli/commands/cmd_stripe.py
|
cli/commands/cmd_stripe.py
|
import logging
import click
import stripe
from config import settings
from catwatch.blueprints.billing.services import StripePlan
from catwatch.app import create_app
app = create_app()
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = app.config.get('STRIPE_SECRET_KEY', None)
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
|
import logging
import click
import stripe
from config import settings as settings_
from catwatch.blueprints.billing.services import StripePlan
try:
from instance import settings
except ImportError:
logging.error('Your instance/ folder must contain an __init__.py file')
exit(1)
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = settings.STRIPE_SECRET_KEY
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings_.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
|
Remove the need to create an app in the stripe CLI
|
Remove the need to create an app in the stripe CLI
|
Python
|
mit
|
nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask
|
import logging
import click
import stripe
from config import settings
from catwatch.blueprints.billing.services import StripePlan
from catwatch.app import create_app
app = create_app()
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = app.config.get('STRIPE_SECRET_KEY', None)
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
Remove the need to create an app in the stripe CLI
|
import logging
import click
import stripe
from config import settings as settings_
from catwatch.blueprints.billing.services import StripePlan
try:
from instance import settings
except ImportError:
logging.error('Your instance/ folder must contain an __init__.py file')
exit(1)
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = settings.STRIPE_SECRET_KEY
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings_.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
|
<commit_before>import logging
import click
import stripe
from config import settings
from catwatch.blueprints.billing.services import StripePlan
from catwatch.app import create_app
app = create_app()
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = app.config.get('STRIPE_SECRET_KEY', None)
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
<commit_msg>Remove the need to create an app in the stripe CLI<commit_after>
|
import logging
import click
import stripe
from config import settings as settings_
from catwatch.blueprints.billing.services import StripePlan
try:
from instance import settings
except ImportError:
logging.error('Your instance/ folder must contain an __init__.py file')
exit(1)
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = settings.STRIPE_SECRET_KEY
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings_.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
|
import logging
import click
import stripe
from config import settings
from catwatch.blueprints.billing.services import StripePlan
from catwatch.app import create_app
app = create_app()
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = app.config.get('STRIPE_SECRET_KEY', None)
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
Remove the need to create an app in the stripe CLIimport logging
import click
import stripe
from config import settings as settings_
from catwatch.blueprints.billing.services import StripePlan
try:
from instance import settings
except ImportError:
logging.error('Your instance/ folder must contain an __init__.py file')
exit(1)
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = settings.STRIPE_SECRET_KEY
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings_.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
|
<commit_before>import logging
import click
import stripe
from config import settings
from catwatch.blueprints.billing.services import StripePlan
from catwatch.app import create_app
app = create_app()
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = app.config.get('STRIPE_SECRET_KEY', None)
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
<commit_msg>Remove the need to create an app in the stripe CLI<commit_after>import logging
import click
import stripe
from config import settings as settings_
from catwatch.blueprints.billing.services import StripePlan
try:
from instance import settings
except ImportError:
logging.error('Your instance/ folder must contain an __init__.py file')
exit(1)
@click.group()
def cli():
""" Perform various tasks with Stripe's API. """
stripe.api_key = settings.STRIPE_SECRET_KEY
@click.command()
def sync_plans():
"""
Sync (upsert) STRIPE_PLANS to Stripe.
"""
plans = settings_.STRIPE_PLANS
for _, value in plans.iteritems():
plan = StripePlan.retrieve(value['id'])
if plan:
StripePlan.update(value)
else:
StripePlan.create(value)
@click.command()
@click.argument('plan_ids', nargs=-1)
def delete_plans(plan_ids):
"""
Delete 1 or more plans from Stripe.
"""
for plan_id in plan_ids:
StripePlan.delete(plan_id)
@click.command()
def list_plans():
"""
List all existing plans on Stripe.
"""
logging.info(StripePlan.list())
cli.add_command(sync_plans)
cli.add_command(delete_plans)
cli.add_command(list_plans)
|
bb23c2bfa31913658b526b9dbaf812c749e9523c
|
pentai/gui/goodbye_screen.py
|
pentai/gui/goodbye_screen.py
|
import kivy.core.window
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
|
import kivy.core.window
from kivy.clock import Clock
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
# Was getting part of the wooden board on the screen
Clock.schedule_once(self.shutdown, 0.1)
def shutdown(self, ignored):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
|
Fix prob with wooden board leftover.
|
Fix prob with wooden board leftover.
|
Python
|
mit
|
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
|
import kivy.core.window
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
Fix prob with wooden board leftover.
|
import kivy.core.window
from kivy.clock import Clock
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
# Was getting part of the wooden board on the screen
Clock.schedule_once(self.shutdown, 0.1)
def shutdown(self, ignored):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
|
<commit_before>import kivy.core.window
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
<commit_msg>Fix prob with wooden board leftover.<commit_after>
|
import kivy.core.window
from kivy.clock import Clock
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
# Was getting part of the wooden board on the screen
Clock.schedule_once(self.shutdown, 0.1)
def shutdown(self, ignored):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
|
import kivy.core.window
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
Fix prob with wooden board leftover.import kivy.core.window
from kivy.clock import Clock
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
# Was getting part of the wooden board on the screen
Clock.schedule_once(self.shutdown, 0.1)
def shutdown(self, ignored):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
|
<commit_before>import kivy.core.window
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
<commit_msg>Fix prob with wooden board leftover.<commit_after>import kivy.core.window
from kivy.clock import Clock
import pentai.db.zodb_dict as z_m
from pentai.gui.screen import Screen
class GoodByeScreen(Screen):
def __init__(self, *args, **kwargs):
super(GoodByeScreen, self).__init__(*args, **kwargs)
print "init goodbye screen"
def on_enter(self, *args, **kwargs):
# Was getting part of the wooden board on the screen
Clock.schedule_once(self.shutdown, 0.1)
def shutdown(self, ignored):
app = self.app
app_width, app_height = kivy.core.window.Window.size
app.config.set("PentAI", "app_width", str(app_width))
app.config.set("PentAI", "app_height", str(app_height))
app.config.write()
z_m.sync()
z_m.pack()
self.on_pre_leave()
self.on_leave()
app.stop()
|
6203b25a2d8d742f066917dd7e5f2c8dc0ee9e7c
|
pavement.py
|
pavement.py
|
import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
|
import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
@task
def tail():
"""Follow the device's log."""
call('palm-log', '--device=emulator', '--system-log-level', 'info')
call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain')
|
Add a task for tailing the app's log on the emulator
|
Add a task for tailing the app's log on the emulator
|
Python
|
mit
|
markpasc/paperplain,markpasc/paperplain
|
import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
Add a task for tailing the app's log on the emulator
|
import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
@task
def tail():
"""Follow the device's log."""
call('palm-log', '--device=emulator', '--system-log-level', 'info')
call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain')
|
<commit_before>import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
<commit_msg>Add a task for tailing the app's log on the emulator<commit_after>
|
import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
@task
def tail():
"""Follow the device's log."""
call('palm-log', '--device=emulator', '--system-log-level', 'info')
call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain')
|
import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
Add a task for tailing the app's log on the emulatorimport subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
@task
def tail():
"""Follow the device's log."""
call('palm-log', '--device=emulator', '--system-log-level', 'info')
call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain')
|
<commit_before>import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
<commit_msg>Add a task for tailing the app's log on the emulator<commit_after>import subprocess
from paver.easy import *
def call(*args, **kwargs):
return subprocess.call(args, **kwargs)
@task
def push():
"""Install the app and start it."""
call('palm-package', '.')
call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain')
call('palm-install', '--device=emulator', 'org.markpasc.paperplain_1.0.0_all.ipk')
call('palm-launch', '--device=emulator', 'org.markpasc.paperplain')
@task
def tail():
"""Follow the device's log."""
call('palm-log', '--device=emulator', '--system-log-level', 'info')
call('palm-log', '--device=emulator', '-f', 'org.markpasc.paperplain')
|
0925c1f2ab3332ddfaeefed81f379dc72dd41644
|
openid/test/test_urinorm.py
|
openid/test/test_urinorm.py
|
import os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8')
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
|
import os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8') if isinstance(case, bytes) else case
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(pyUnitTests())
|
Make urinorm tests runnable on their own
|
Make urinorm tests runnable on their own
|
Python
|
apache-2.0
|
misli/python3-openid,misli/python3-openid,moreati/python3-openid,misli/python3-openid,necaris/python3-openid,isagalaev/sm-openid,moreati/python3-openid,moreati/python3-openid,necaris/python3-openid
|
import os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8')
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
Make urinorm tests runnable on their own
|
import os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8') if isinstance(case, bytes) else case
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(pyUnitTests())
|
<commit_before>import os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8')
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
<commit_msg>Make urinorm tests runnable on their own<commit_after>
|
import os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8') if isinstance(case, bytes) else case
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(pyUnitTests())
|
import os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8')
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
Make urinorm tests runnable on their ownimport os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8') if isinstance(case, bytes) else case
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(pyUnitTests())
|
<commit_before>import os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8')
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
<commit_msg>Make urinorm tests runnable on their own<commit_after>import os
import unittest
import openid.urinorm
class UrinormTest(unittest.TestCase):
def __init__(self, desc, case, expected):
unittest.TestCase.__init__(self)
self.desc = desc
self.case = case
self.expected = expected
def shortDescription(self):
return self.desc
def runTest(self):
try:
actual = openid.urinorm.urinorm(self.case)
except ValueError as why:
self.assertEqual(self.expected, 'fail', why)
else:
self.assertEqual(actual, self.expected)
def parse(cls, full_case):
desc, case, expected = full_case.split('\n')
case = str(case, 'utf-8') if isinstance(case, bytes) else case
return cls(desc, case, expected)
parse = classmethod(parse)
def parseTests(test_data):
result = []
cases = test_data.split('\n\n')
for case in cases:
case = case.strip()
if case:
result.append(UrinormTest.parse(case))
return result
def pyUnitTests():
here = os.path.dirname(os.path.abspath(__file__))
test_data_file_name = os.path.join(here, 'urinorm.txt')
test_data_file = open(test_data_file_name)
test_data = test_data_file.read()
test_data_file.close()
tests = parseTests(test_data)
return unittest.TestSuite(tests)
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(pyUnitTests())
|
bb602407a176813cc1727423e1b344f0a1b0bea7
|
tests/test_Science.py
|
tests/test_Science.py
|
"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
def tearDown(self):
pass
def test_round_trip(self):
Lets = desc.slcosmo.SLCosmo()
Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
Lets.draw_some_prior_samples(Npriorsamples=100)
Lets.compute_the_joint_log_likelihood()
Lets.report_the_inferred_cosmological_parameters()
Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(Lets.cosmotruth['H0'], lower_limit)
self.assertLess(Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
|
"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import os
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
self.Lets = desc.slcosmo.SLCosmo()
def tearDown(self):
"Clean up any mock data files created by the tests."
for mock_file in self.Lets.mock_files:
os.remove(mock_file)
def test_round_trip(self):
self.Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
self.Lets.draw_some_prior_samples(Npriorsamples=100)
self.Lets.compute_the_joint_log_likelihood()
self.Lets.report_the_inferred_cosmological_parameters()
self.Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = self.Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(self.Lets.cosmotruth['H0'], lower_limit)
self.assertLess(self.Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
|
Clean up after science test
|
Clean up after science test
|
Python
|
bsd-3-clause
|
DarkEnergyScienceCollaboration/SLCosmo,DarkEnergyScienceCollaboration/SLCosmo
|
"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
def tearDown(self):
pass
def test_round_trip(self):
Lets = desc.slcosmo.SLCosmo()
Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
Lets.draw_some_prior_samples(Npriorsamples=100)
Lets.compute_the_joint_log_likelihood()
Lets.report_the_inferred_cosmological_parameters()
Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(Lets.cosmotruth['H0'], lower_limit)
self.assertLess(Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
Clean up after science test
|
"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import os
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
self.Lets = desc.slcosmo.SLCosmo()
def tearDown(self):
"Clean up any mock data files created by the tests."
for mock_file in self.Lets.mock_files:
os.remove(mock_file)
def test_round_trip(self):
self.Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
self.Lets.draw_some_prior_samples(Npriorsamples=100)
self.Lets.compute_the_joint_log_likelihood()
self.Lets.report_the_inferred_cosmological_parameters()
self.Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = self.Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(self.Lets.cosmotruth['H0'], lower_limit)
self.assertLess(self.Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
|
<commit_before>"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
def tearDown(self):
pass
def test_round_trip(self):
Lets = desc.slcosmo.SLCosmo()
Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
Lets.draw_some_prior_samples(Npriorsamples=100)
Lets.compute_the_joint_log_likelihood()
Lets.report_the_inferred_cosmological_parameters()
Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(Lets.cosmotruth['H0'], lower_limit)
self.assertLess(Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
<commit_msg>Clean up after science test<commit_after>
|
"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import os
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
self.Lets = desc.slcosmo.SLCosmo()
def tearDown(self):
"Clean up any mock data files created by the tests."
for mock_file in self.Lets.mock_files:
os.remove(mock_file)
def test_round_trip(self):
self.Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
self.Lets.draw_some_prior_samples(Npriorsamples=100)
self.Lets.compute_the_joint_log_likelihood()
self.Lets.report_the_inferred_cosmological_parameters()
self.Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = self.Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(self.Lets.cosmotruth['H0'], lower_limit)
self.assertLess(self.Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
|
"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
def tearDown(self):
pass
def test_round_trip(self):
Lets = desc.slcosmo.SLCosmo()
Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
Lets.draw_some_prior_samples(Npriorsamples=100)
Lets.compute_the_joint_log_likelihood()
Lets.report_the_inferred_cosmological_parameters()
Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(Lets.cosmotruth['H0'], lower_limit)
self.assertLess(Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
Clean up after science test"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import os
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
self.Lets = desc.slcosmo.SLCosmo()
def tearDown(self):
"Clean up any mock data files created by the tests."
for mock_file in self.Lets.mock_files:
os.remove(mock_file)
def test_round_trip(self):
self.Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
self.Lets.draw_some_prior_samples(Npriorsamples=100)
self.Lets.compute_the_joint_log_likelihood()
self.Lets.report_the_inferred_cosmological_parameters()
self.Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = self.Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(self.Lets.cosmotruth['H0'], lower_limit)
self.assertLess(self.Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
|
<commit_before>"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
def tearDown(self):
pass
def test_round_trip(self):
Lets = desc.slcosmo.SLCosmo()
Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
Lets.draw_some_prior_samples(Npriorsamples=100)
Lets.compute_the_joint_log_likelihood()
Lets.report_the_inferred_cosmological_parameters()
Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(Lets.cosmotruth['H0'], lower_limit)
self.assertLess(Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
<commit_msg>Clean up after science test<commit_after>"""
Scientific tests for SLCosmo package
"""
import matplotlib
matplotlib.use('Agg')
import os
import unittest
import desc.slcosmo
class SLCosmoScienceTestCase(unittest.TestCase):
def setUp(self):
self.message = 'Testing SLCosmo - For Science!'
self.Lets = desc.slcosmo.SLCosmo()
def tearDown(self):
"Clean up any mock data files created by the tests."
for mock_file in self.Lets.mock_files:
os.remove(mock_file)
def test_round_trip(self):
self.Lets.make_some_mock_data(Nlenses=10, Nsamples=20)
self.Lets.draw_some_prior_samples(Npriorsamples=100)
self.Lets.compute_the_joint_log_likelihood()
self.Lets.report_the_inferred_cosmological_parameters()
self.Lets.plot_the_inferred_cosmological_parameters()
H0, sigma = self.Lets.estimate_H0()
lower_limit = H0 - 3.0*sigma
upper_limit = H0 + 3.0*sigma
self.assertGreater(self.Lets.cosmotruth['H0'], lower_limit)
self.assertLess(self.Lets.cosmotruth['H0'], upper_limit)
if __name__ == '__main__':
unittest.main()
|
ade960c76de6773a176d2cd982ac9a26a2d072ae
|
tests/unit/network/CubicTemplateTest.py
|
tests/unit/network/CubicTemplateTest.py
|
import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
|
import numpy as np
import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
def test_labels(self):
template = np.array(
[[1, 1, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 0, 1, 1]]
)
net = op.network.CubicTemplate(template=template)
# Test "surface" label
Ps_surf_desired = np.array([0, 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 14, 15, 16, 17])
Ps_surf = net.pores("surface")
np.testing.assert_allclose(Ps_surf, Ps_surf_desired)
# Test "internal_surface" label
Ps_int_surf_desired = np.array([6, 7, 10])
Ps_int_surf = net.pores("internal_surface")
np.testing.assert_allclose(Ps_int_surf, Ps_int_surf_desired)
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
|
Add test for CubicTemplate to ensure proper labeling
|
Add test for CubicTemplate to ensure proper labeling
|
Python
|
mit
|
TomTranter/OpenPNM,PMEAL/OpenPNM
|
import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
Add test for CubicTemplate to ensure proper labeling
|
import numpy as np
import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
def test_labels(self):
template = np.array(
[[1, 1, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 0, 1, 1]]
)
net = op.network.CubicTemplate(template=template)
# Test "surface" label
Ps_surf_desired = np.array([0, 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 14, 15, 16, 17])
Ps_surf = net.pores("surface")
np.testing.assert_allclose(Ps_surf, Ps_surf_desired)
# Test "internal_surface" label
Ps_int_surf_desired = np.array([6, 7, 10])
Ps_int_surf = net.pores("internal_surface")
np.testing.assert_allclose(Ps_int_surf, Ps_int_surf_desired)
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
|
<commit_before>import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
<commit_msg>Add test for CubicTemplate to ensure proper labeling<commit_after>
|
import numpy as np
import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
def test_labels(self):
template = np.array(
[[1, 1, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 0, 1, 1]]
)
net = op.network.CubicTemplate(template=template)
# Test "surface" label
Ps_surf_desired = np.array([0, 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 14, 15, 16, 17])
Ps_surf = net.pores("surface")
np.testing.assert_allclose(Ps_surf, Ps_surf_desired)
# Test "internal_surface" label
Ps_int_surf_desired = np.array([6, 7, 10])
Ps_int_surf = net.pores("internal_surface")
np.testing.assert_allclose(Ps_int_surf, Ps_int_surf_desired)
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
|
import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
Add test for CubicTemplate to ensure proper labelingimport numpy as np
import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
def test_labels(self):
template = np.array(
[[1, 1, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 0, 1, 1]]
)
net = op.network.CubicTemplate(template=template)
# Test "surface" label
Ps_surf_desired = np.array([0, 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 14, 15, 16, 17])
Ps_surf = net.pores("surface")
np.testing.assert_allclose(Ps_surf, Ps_surf_desired)
# Test "internal_surface" label
Ps_int_surf_desired = np.array([6, 7, 10])
Ps_int_surf = net.pores("internal_surface")
np.testing.assert_allclose(Ps_int_surf, Ps_int_surf_desired)
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
|
<commit_before>import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
<commit_msg>Add test for CubicTemplate to ensure proper labeling<commit_after>import numpy as np
import openpnm as op
from skimage.morphology import ball, disk
class CubicTemplateTest:
def setup_class(self):
pass
def teardown_class(self):
pass
def test_2D_template(self):
net = op.network.CubicTemplate(template=disk(10), spacing=1)
assert net.Np == 317
assert net.Nt == 592
def test_3D_template(self):
net = op.network.CubicTemplate(template=ball(5), spacing=1)
assert net.Np == 515
assert net.Nt == 1302
def test_labels(self):
template = np.array(
[[1, 1, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 0, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 0, 1, 1]]
)
net = op.network.CubicTemplate(template=template)
# Test "surface" label
Ps_surf_desired = np.array([0, 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 14, 15, 16, 17])
Ps_surf = net.pores("surface")
np.testing.assert_allclose(Ps_surf, Ps_surf_desired)
# Test "internal_surface" label
Ps_int_surf_desired = np.array([6, 7, 10])
Ps_int_surf = net.pores("internal_surface")
np.testing.assert_allclose(Ps_int_surf, Ps_int_surf_desired)
if __name__ == '__main__':
t = CubicTemplateTest()
t.setup_class()
self = t
for item in t.__dir__():
if item.startswith('test'):
print('running test: '+item)
t.__getattribute__(item)()
|
a4d0bc42cf28351e24d6239f42b51c4cc77961ff
|
tests/test_helpers.py
|
tests/test_helpers.py
|
import os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in'))
==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
|
import os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in')) ==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
|
Fix an old flake8 error
|
style: Fix an old flake8 error
|
Python
|
mit
|
frigg/frigg-settings
|
import os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in'))
==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
style: Fix an old flake8 error
|
import os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in')) ==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
|
<commit_before>import os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in'))
==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
<commit_msg>style: Fix an old flake8 error<commit_after>
|
import os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in')) ==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
|
import os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in'))
==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
style: Fix an old flake8 errorimport os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in')) ==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
|
<commit_before>import os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in'))
==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
<commit_msg>style: Fix an old flake8 error<commit_after>import os
from frigg_settings.helpers import FileSystemWrapper
def path(*args):
return os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
def test_filesystemwrapper_list_files():
wrapper = FileSystemWrapper()
files = wrapper.list_files(path())
# This check cannot check the exact files because of
# generated coverage files.
assert '.frigg.yml' in files
assert '.gitignore' in files
assert 'frigg_settings' not in files
assert 'tests' not in files
def test_filesystemwrapper_read_file():
wrapper = FileSystemWrapper()
assert(
wrapper.read_file(path('MANIFEST.in')) ==
'include setup.py README.md MANIFEST.in LICENSE\n'
)
def test_filesystemwrapper_file_exist():
wrapper = FileSystemWrapper()
assert wrapper.file_exist(path('setup.py'))
assert not wrapper.file_exist(path('non-exsting'))
assert not wrapper.file_exist(path('tests'))
|
44f232e179a2fe152ef6a7aa9e6e5cd52a4f201e
|
plasmapy/physics/__init__.py
|
plasmapy/physics/__init__.py
|
from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
|
# 'physics' is a tentative name for this subpackage. Another
# possibility is 'plasma'. The organization is to be decided by v0.1.
from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
|
Comment that physics is a tentative subpackage name
|
Comment that physics is a tentative subpackage name
|
Python
|
bsd-3-clause
|
StanczakDominik/PlasmaPy
|
from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
Comment that physics is a tentative subpackage name
|
# 'physics' is a tentative name for this subpackage. Another
# possibility is 'plasma'. The organization is to be decided by v0.1.
from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
|
<commit_before>from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
<commit_msg>Comment that physics is a tentative subpackage name<commit_after>
|
# 'physics' is a tentative name for this subpackage. Another
# possibility is 'plasma'. The organization is to be decided by v0.1.
from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
|
from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
Comment that physics is a tentative subpackage name# 'physics' is a tentative name for this subpackage. Another
# possibility is 'plasma'. The organization is to be decided by v0.1.
from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
|
<commit_before>from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
<commit_msg>Comment that physics is a tentative subpackage name<commit_after># 'physics' is a tentative name for this subpackage. Another
# possibility is 'plasma'. The organization is to be decided by v0.1.
from .parameters import (Alfven_speed,
ion_sound_speed,
electron_thermal_speed,
ion_thermal_speed,
electron_gyrofrequency,
ion_gyrofrequency,
electron_gyroradius,
ion_gyroradius,
electron_plasma_frequency,
ion_plasma_frequency,
Debye_length,
Debye_number,
ion_inertial_length,
electron_inertial_length,
magnetic_pressure,
magnetic_energy_density,
)
|
10ae930f6f14c2840d0b87cbec17054b4cc318d2
|
facebook_auth/models.py
|
facebook_auth/models.py
|
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
|
from uuid import uuid1
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
def get_auth_address(request, redirect_to, scope=''):
state = unicode(uuid1())
request.session['state'] = state
return 'https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s&state=%s' % (
settings.FACEBOOK_APP_ID, redirect_to, scope, state
)
|
Add support for server side authentication.
|
Add support for server side authentication.
Change-Id: Iff45fa00b5a5b389f998570827e33d9d232f5d1e
Reviewed-on: http://review.pozytywnie.pl:8080/5087
Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
|
Python
|
mit
|
pozytywnie/django-facebook-auth,pozytywnie/django-facebook-auth,jgoclawski/django-facebook-auth,jgoclawski/django-facebook-auth
|
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
Add support for server side authentication.
Change-Id: Iff45fa00b5a5b389f998570827e33d9d232f5d1e
Reviewed-on: http://review.pozytywnie.pl:8080/5087
Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
|
from uuid import uuid1
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
def get_auth_address(request, redirect_to, scope=''):
state = unicode(uuid1())
request.session['state'] = state
return 'https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s&state=%s' % (
settings.FACEBOOK_APP_ID, redirect_to, scope, state
)
|
<commit_before>from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
<commit_msg>Add support for server side authentication.
Change-Id: Iff45fa00b5a5b389f998570827e33d9d232f5d1e
Reviewed-on: http://review.pozytywnie.pl:8080/5087
Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com><commit_after>
|
from uuid import uuid1
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
def get_auth_address(request, redirect_to, scope=''):
state = unicode(uuid1())
request.session['state'] = state
return 'https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s&state=%s' % (
settings.FACEBOOK_APP_ID, redirect_to, scope, state
)
|
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
Add support for server side authentication.
Change-Id: Iff45fa00b5a5b389f998570827e33d9d232f5d1e
Reviewed-on: http://review.pozytywnie.pl:8080/5087
Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>from uuid import uuid1
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
def get_auth_address(request, redirect_to, scope=''):
state = unicode(uuid1())
request.session['state'] = state
return 'https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s&state=%s' % (
settings.FACEBOOK_APP_ID, redirect_to, scope, state
)
|
<commit_before>from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
<commit_msg>Add support for server side authentication.
Change-Id: Iff45fa00b5a5b389f998570827e33d9d232f5d1e
Reviewed-on: http://review.pozytywnie.pl:8080/5087
Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com><commit_after>from uuid import uuid1
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.db import models
import facepy
import simplejson
from facebook_auth import utils
class FacebookUser(auth_models.User):
user_id = models.BigIntegerField(unique=True)
access_token = models.TextField(blank=True, null=True)
app_friends = models.ManyToManyField('self')
@property
def graph(self):
return facepy.GraphAPI(self.access_token)
@property
def js_session(self):
return simplejson.dumps({
'access_token': self.access_token,
'uid': self.user_id
})
@property
def friends(self):
return utils.get_from_graph_api(self.graph, "me/friends")['data']
def update_app_friends(self):
friends = self.friends
friends_ids = [f['id'] for f in friends]
self.app_friends.clear()
self.app_friends.add(*FacebookUser.objects.filter(user_id__in=friends_ids))
def get_auth_address(request, redirect_to, scope=''):
state = unicode(uuid1())
request.session['state'] = state
return 'https://www.facebook.com/dialog/oauth?client_id=%s&redirect_uri=%s&scope=%s&state=%s' % (
settings.FACEBOOK_APP_ID, redirect_to, scope, state
)
|
c182e5c8cef76c852d7ae41c2fc8b8266f17c728
|
extensions/ExtGameController.py
|
extensions/ExtGameController.py
|
from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__()
self.add_mode(self.additional_modes)
|
from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__(game=None)
self.add_mode(self.additional_modes)
|
Remove ability to instantiate with game.
|
Remove ability to instantiate with game.
|
Python
|
apache-2.0
|
dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server
|
from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__()
self.add_mode(self.additional_modes)
Remove ability to instantiate with game.
|
from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__(game=None)
self.add_mode(self.additional_modes)
|
<commit_before>from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__()
self.add_mode(self.additional_modes)
<commit_msg>Remove ability to instantiate with game.<commit_after>
|
from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__(game=None)
self.add_mode(self.additional_modes)
|
from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__()
self.add_mode(self.additional_modes)
Remove ability to instantiate with game.from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__(game=None)
self.add_mode(self.additional_modes)
|
<commit_before>from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__()
self.add_mode(self.additional_modes)
<commit_msg>Remove ability to instantiate with game.<commit_after>from python_cowbull_game.GameController import GameController
from python_cowbull_game.GameMode import GameMode
class ExtGameController(GameController):
additional_modes = [
# GameMode(mode="SuperTough", priority=6, digits=10, digit_type=0),
# GameMode(mode="hexTough", priority=5, digits=3, guesses_allowed=3, digit_type=1)
]
def __init__(self):
super(ExtGameController, self).__init__(game=None)
self.add_mode(self.additional_modes)
|
dc88dca696d25a5ea5793aa48fae390469f0d829
|
phi/flow.py
|
phi/flow.py
|
# pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
|
# pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import Tensor, DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
|
Add Tensor to standard imports
|
[Φ] Add Tensor to standard imports
|
Python
|
mit
|
tum-pbs/PhiFlow,tum-pbs/PhiFlow
|
# pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
[Φ] Add Tensor to standard imports
|
# pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import Tensor, DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
|
<commit_before># pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
<commit_msg>[Φ] Add Tensor to standard imports<commit_after>
|
# pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import Tensor, DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
|
# pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
[Φ] Add Tensor to standard imports# pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import Tensor, DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
|
<commit_before># pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
<commit_msg>[Φ] Add Tensor to standard imports<commit_after># pylint: disable-msg = unused-import
"""
*Main PhiFlow import:* `from phi.flow import *`
Imports important functions and classes from
`math`, `geom`, `field`, `physics` and `vis` (including sub-modules)
as well as the modules and sub-modules themselves.
See `phi.tf.flow`, `phi.torch.flow`, `phi.jax.flow`.
"""
# Modules
import numpy
import numpy as np
import phi
from . import math, geom, field, physics, vis
from .math import extrapolation, backend
from .physics import fluid, flip, advect, diffuse
# Classes
from .math import Tensor, DType, Solve
from .geom import Geometry, Sphere, Box, Cuboid
from .field import Grid, CenteredGrid, StaggeredGrid, GeometryMask, SoftGeometryMask, HardGeometryMask, Noise, PointCloud, Scene
from .vis import view, Viewer, control
from .physics._boundaries import Obstacle
# Constants
from .math import PI, INF, NAN
# Functions
from .math import wrap, tensor, spatial, channel, batch, instance
from .geom import union
from .vis import show
# Exceptions
from .math import ConvergenceException, NotConverged, Diverged
|
887149522b4cbce5e84fe25897358600e88be29d
|
inbox/notify/__init__.py
|
inbox/notify/__init__.py
|
from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
import json
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=6379, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
pipeline.execute()
pipeline.reset()
|
import json
from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
from nylas.logging import get_logger
log = get_logger()
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_PORT = int(config.get('NOTIFY_QUEUE_REDIS_PORT', 6379))
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=REDIS_PORT, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
log.info('Transaction prepared to enqueue',
transaction_id=transaction.record_id)
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
try:
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
log.info('Transaction enqueued',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job)
pipeline.execute()
pipeline.reset()
except Exception as e:
log.error('Transaction not enqueued!',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job,
error=e)
raise e
|
Add logger an try/except logic
|
Add logger an try/except logic
|
Python
|
agpl-3.0
|
jobscore/sync-engine,jobscore/sync-engine,jobscore/sync-engine,jobscore/sync-engine
|
from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
import json
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=6379, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
pipeline.execute()
pipeline.reset()
Add logger an try/except logic
|
import json
from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
from nylas.logging import get_logger
log = get_logger()
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_PORT = int(config.get('NOTIFY_QUEUE_REDIS_PORT', 6379))
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=REDIS_PORT, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
log.info('Transaction prepared to enqueue',
transaction_id=transaction.record_id)
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
try:
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
log.info('Transaction enqueued',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job)
pipeline.execute()
pipeline.reset()
except Exception as e:
log.error('Transaction not enqueued!',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job,
error=e)
raise e
|
<commit_before>from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
import json
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=6379, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
pipeline.execute()
pipeline.reset()
<commit_msg>Add logger an try/except logic<commit_after>
|
import json
from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
from nylas.logging import get_logger
log = get_logger()
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_PORT = int(config.get('NOTIFY_QUEUE_REDIS_PORT', 6379))
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=REDIS_PORT, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
log.info('Transaction prepared to enqueue',
transaction_id=transaction.record_id)
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
try:
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
log.info('Transaction enqueued',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job)
pipeline.execute()
pipeline.reset()
except Exception as e:
log.error('Transaction not enqueued!',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job,
error=e)
raise e
|
from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
import json
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=6379, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
pipeline.execute()
pipeline.reset()
Add logger an try/except logicimport json
from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
from nylas.logging import get_logger
log = get_logger()
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_PORT = int(config.get('NOTIFY_QUEUE_REDIS_PORT', 6379))
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=REDIS_PORT, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
log.info('Transaction prepared to enqueue',
transaction_id=transaction.record_id)
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
try:
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
log.info('Transaction enqueued',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job)
pipeline.execute()
pipeline.reset()
except Exception as e:
log.error('Transaction not enqueued!',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job,
error=e)
raise e
|
<commit_before>from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
import json
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=6379, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
pipeline.execute()
pipeline.reset()
<commit_msg>Add logger an try/except logic<commit_after>import json
from redis import StrictRedis, BlockingConnectionPool
from inbox.config import config
from nylas.logging import get_logger
log = get_logger()
REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME')
REDIS_PORT = int(config.get('NOTIFY_QUEUE_REDIS_PORT', 6379))
REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB'))
MAX_CONNECTIONS = 40
redis_pool = BlockingConnectionPool(
max_connections=MAX_CONNECTIONS,
host=REDIS_HOSTNAME, port=REDIS_PORT, db=REDIS_DB)
def notify_transaction(transaction, db_session):
from inbox.models import Namespace
# We're only interested in "message created" events
if transaction.command != 'insert' or transaction.object_type != 'message':
return
log.info('Transaction prepared to enqueue',
transaction_id=transaction.record_id)
namespace = db_session.query(Namespace).get(transaction.namespace_id)
redis_client = StrictRedis(connection_pool=redis_pool)
job = {
'class': 'ProcessMessageQueue',
'args': [
'nylas_notification',
namespace.public_id,
transaction.object_public_id
]
}
try:
pipeline = redis_client.pipeline()
pipeline.sadd('resque:queues', 'nylas_default')
pipeline.lpush('resque:queue:nylas_default', json.dumps(job))
log.info('Transaction enqueued',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job)
pipeline.execute()
pipeline.reset()
except Exception as e:
log.error('Transaction not enqueued!',
transaction_id=transaction.record_id,
namespace_id=transaction.namespace_id,
job_details=job,
error=e)
raise e
|
d09379bbc6898b696e762d1bb06404eb613c59f3
|
tests/main.py
|
tests/main.py
|
"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
program.run("fab --version", exit=False)
expected = r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip()
assert_contains(sys.stdout.getvalue(), expected)
@trap
def help_output_says_fab(self):
program.run("fab --help", exit=False)
assert "Usage: fab " in sys.stdout.getvalue()
|
"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program as fab_program
# TODO: figure out a non shite way to share Invoke's more beefy copy of same.
def expect(invocation, out, program=None, test=None):
if program is None:
program = fab_program
program.run("fab {0}".format(invocation), exit=False)
(test or eq_)(sys.stdout.getvalue(), out)
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
expect(
"--version",
r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip(),
test=assert_contains
)
@trap
def help_output_says_fab(self):
expect("--help", "Usage: fab", test=assert_contains)
|
Use stripped-down version of invoke test expect()
|
Use stripped-down version of invoke test expect()
|
Python
|
bsd-2-clause
|
fabric/fabric
|
"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
program.run("fab --version", exit=False)
expected = r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip()
assert_contains(sys.stdout.getvalue(), expected)
@trap
def help_output_says_fab(self):
program.run("fab --help", exit=False)
assert "Usage: fab " in sys.stdout.getvalue()
Use stripped-down version of invoke test expect()
|
"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program as fab_program
# TODO: figure out a non shite way to share Invoke's more beefy copy of same.
def expect(invocation, out, program=None, test=None):
if program is None:
program = fab_program
program.run("fab {0}".format(invocation), exit=False)
(test or eq_)(sys.stdout.getvalue(), out)
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
expect(
"--version",
r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip(),
test=assert_contains
)
@trap
def help_output_says_fab(self):
expect("--help", "Usage: fab", test=assert_contains)
|
<commit_before>"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
program.run("fab --version", exit=False)
expected = r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip()
assert_contains(sys.stdout.getvalue(), expected)
@trap
def help_output_says_fab(self):
program.run("fab --help", exit=False)
assert "Usage: fab " in sys.stdout.getvalue()
<commit_msg>Use stripped-down version of invoke test expect()<commit_after>
|
"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program as fab_program
# TODO: figure out a non shite way to share Invoke's more beefy copy of same.
def expect(invocation, out, program=None, test=None):
if program is None:
program = fab_program
program.run("fab {0}".format(invocation), exit=False)
(test or eq_)(sys.stdout.getvalue(), out)
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
expect(
"--version",
r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip(),
test=assert_contains
)
@trap
def help_output_says_fab(self):
expect("--help", "Usage: fab", test=assert_contains)
|
"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
program.run("fab --version", exit=False)
expected = r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip()
assert_contains(sys.stdout.getvalue(), expected)
@trap
def help_output_says_fab(self):
program.run("fab --help", exit=False)
assert "Usage: fab " in sys.stdout.getvalue()
Use stripped-down version of invoke test expect()"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program as fab_program
# TODO: figure out a non shite way to share Invoke's more beefy copy of same.
def expect(invocation, out, program=None, test=None):
if program is None:
program = fab_program
program.run("fab {0}".format(invocation), exit=False)
(test or eq_)(sys.stdout.getvalue(), out)
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
expect(
"--version",
r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip(),
test=assert_contains
)
@trap
def help_output_says_fab(self):
expect("--help", "Usage: fab", test=assert_contains)
|
<commit_before>"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
program.run("fab --version", exit=False)
expected = r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip()
assert_contains(sys.stdout.getvalue(), expected)
@trap
def help_output_says_fab(self):
program.run("fab --help", exit=False)
assert "Usage: fab " in sys.stdout.getvalue()
<commit_msg>Use stripped-down version of invoke test expect()<commit_after>"""
Tests concerned with the ``fab`` tool & how it overrides Invoke defaults.
"""
import re
import sys
from spec import Spec, trap, assert_contains
from fabric.main import program as fab_program
# TODO: figure out a non shite way to share Invoke's more beefy copy of same.
def expect(invocation, out, program=None, test=None):
if program is None:
program = fab_program
program.run("fab {0}".format(invocation), exit=False)
(test or eq_)(sys.stdout.getvalue(), out)
class Fab_(Spec):
@trap
def version_output_contains_our_name_plus_deps(self):
expect(
"--version",
r"""
Fabric .+
Paramiko .+
Invoke .+
""".strip(),
test=assert_contains
)
@trap
def help_output_says_fab(self):
expect("--help", "Usage: fab", test=assert_contains)
|
6a410b9079cffec380ac44cf390be381be929e5d
|
autoencoder/api.py
|
autoencoder/api.py
|
from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu',
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=False)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
|
from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=testset)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
|
Make preprocess testset argument accessible through API
|
Make preprocess testset argument accessible through API
|
Python
|
apache-2.0
|
theislab/dca,theislab/dca,theislab/dca
|
from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu',
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=False)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
Make preprocess testset argument accessible through API
|
from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=testset)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
|
<commit_before>from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu',
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=False)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
<commit_msg>Make preprocess testset argument accessible through API<commit_after>
|
from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=testset)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
|
from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu',
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=False)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
Make preprocess testset argument accessible through APIfrom .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=testset)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
|
<commit_before>from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu',
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=False)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
<commit_msg>Make preprocess testset argument accessible through API<commit_after>from .io import preprocess
from .train import train
from .network import autoencoder
from .encode import encode
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epochs=200, **kwargs):
x = preprocess(count_matrix, kfold=kfold, mask=mask, testset=testset)
model, encoder, decoder, loss, extras = \
autoencoder(x['shape'][1],
hidden_size=hidden_size,
l2_coef=l2_coef,
activation=activation,
masking=(mask is not None),
aetype=type)
losses = train(x, model,
learning_rate=learning_rate,
epochs=epochs, **kwargs)
ret = {'model': model,
'encoder': encoder,
'decoder': decoder,
'extra_models': extras,
'losses': losses}
if dimreduce:
ret['reduced'] = encoder.predict(count_matrix)
if reconstruct:
ret['reconstructed'] = model.predict(count_matrix)
return ret
|
aaa74513f8b947cf542b59408816be9ed1867644
|
atc/atcd/setup.py
|
atc/atcd/setup.py
|
#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
# FIXME: add atc_thrift dependency once package is published to pip
install_requires=install_requires,
tests_require=tests_require,
)
|
#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'atc_thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
install_requires=install_requires,
tests_require=tests_require,
)
|
Make atcd depends on atc_thrift package implicitely
|
Make atcd depends on atc_thrift package implicitely
|
Python
|
bsd-3-clause
|
jamesblunt/augmented-traffic-control,linearregression/augmented-traffic-control,biddyweb/augmented-traffic-control,beni55/augmented-traffic-control,linearregression/augmented-traffic-control,duydb2/ZTC,shinyvince/augmented-traffic-control,Endika/augmented-traffic-control,drptbl/augmented-traffic-control,shinyvince/augmented-traffic-control,liwangdong/augmented-traffic-control,duydb2/ZTC,Endika/augmented-traffic-control,guker/augmented-traffic-control,yershalom/augmented-traffic-control,beni55/augmented-traffic-control,venkateshdaram434/augmented-traffic-control,duydb2/ZTC,drptbl/augmented-traffic-control,venkateshdaram434/augmented-traffic-control,drptbl/augmented-traffic-control,iver333/augmented-traffic-control,beni55/augmented-traffic-control,venkateshdaram434/augmented-traffic-control,liwangdong/augmented-traffic-control,biddyweb/augmented-traffic-control,Endika/augmented-traffic-control,liwangdong/augmented-traffic-control,yershalom/augmented-traffic-control,linearregression/augmented-traffic-control,yershalom/augmented-traffic-control,zfjagann/augmented-traffic-control,zfjagann/augmented-traffic-control,iver333/augmented-traffic-control,misfitdavidl/augmented-traffic-control,guker/augmented-traffic-control,guker/augmented-traffic-control,Endika/augmented-traffic-control,shinyvince/augmented-traffic-control,chantra/augmented-traffic-control,chantra/augmented-traffic-control,hai8108/augmented-traffic-control,Endika/augmented-traffic-control,yershalom/augmented-traffic-control,hai8108/augmented-traffic-control,zfjagann/augmented-traffic-control,guker/augmented-traffic-control,hai8108/augmented-traffic-control,iver333/augmented-traffic-control,zfjagann/augmented-traffic-control,jamesblunt/augmented-traffic-control,iver333/augmented-traffic-control,liwangdong/augmented-traffic-control,jamesblunt/augmented-traffic-control,biddyweb/augmented-traffic-control,duydb2/ZTC,linearregression/augmented-traffic-control,hai8108/augmented-traffic-control,shinyvince/augmented-traffic-control,drptbl/augmented-traffic-control,biddyweb/augmented-traffic-control,hai8108/augmented-traffic-control,drptbl/augmented-traffic-control,venkateshdaram434/augmented-traffic-control,chantra/augmented-traffic-control,linearregression/augmented-traffic-control,guker/augmented-traffic-control,chantra/augmented-traffic-control,duydb2/ZTC,jamesblunt/augmented-traffic-control,liwangdong/augmented-traffic-control,zfjagann/augmented-traffic-control,jamesblunt/augmented-traffic-control,chantra/augmented-traffic-control,misfitdavidl/augmented-traffic-control,misfitdavidl/augmented-traffic-control,biddyweb/augmented-traffic-control,iver333/augmented-traffic-control,yershalom/augmented-traffic-control,misfitdavidl/augmented-traffic-control,venkateshdaram434/augmented-traffic-control,beni55/augmented-traffic-control,misfitdavidl/augmented-traffic-control,shinyvince/augmented-traffic-control,beni55/augmented-traffic-control
|
#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
# FIXME: add atc_thrift dependency once package is published to pip
install_requires=install_requires,
tests_require=tests_require,
)
Make atcd depends on atc_thrift package implicitely
|
#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'atc_thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
install_requires=install_requires,
tests_require=tests_require,
)
|
<commit_before>#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
# FIXME: add atc_thrift dependency once package is published to pip
install_requires=install_requires,
tests_require=tests_require,
)
<commit_msg>Make atcd depends on atc_thrift package implicitely<commit_after>
|
#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'atc_thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
install_requires=install_requires,
tests_require=tests_require,
)
|
#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
# FIXME: add atc_thrift dependency once package is published to pip
install_requires=install_requires,
tests_require=tests_require,
)
Make atcd depends on atc_thrift package implicitely#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'atc_thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
install_requires=install_requires,
tests_require=tests_require,
)
|
<commit_before>#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
# FIXME: add atc_thrift dependency once package is published to pip
install_requires=install_requires,
tests_require=tests_require,
)
<commit_msg>Make atcd depends on atc_thrift package implicitely<commit_after>#!/usr/bin/env python
#
# Copyright (c) 2014, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
#
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'atc_thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup(
name='atcd',
version='0.0.1',
description='ATC Daemon',
author='Emmanuel Bretelle',
author_email='chantra@fb.com',
url='https://github.com/facebook/augmented-traffic-control',
packages=['atcd',
'atcd.backends',
'atcd.scripts',
'atcd.tools'],
classifiers=['Programming Language :: Python', ],
long_description=readme.read(),
scripts=scripts,
install_requires=install_requires,
tests_require=tests_require,
)
|
c87be7a48d496cffe24f31ca46db0a7629a0b2a8
|
utilkit/stringutil.py
|
utilkit/stringutil.py
|
"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args)
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text)
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape')
|
"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args) # pylint:disable=undefined-variable
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text) # pylint:disable=undefined-variable
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape') # pylint:disable=undefined-variable
|
Disable error-checking that assumes Python 3 for these Python 2 helpers
|
Disable error-checking that assumes Python 3 for these Python 2 helpers
|
Python
|
mit
|
aquatix/python-utilkit
|
"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args)
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text)
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape')
Disable error-checking that assumes Python 3 for these Python 2 helpers
|
"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args) # pylint:disable=undefined-variable
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text) # pylint:disable=undefined-variable
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape') # pylint:disable=undefined-variable
|
<commit_before>"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args)
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text)
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape')
<commit_msg>Disable error-checking that assumes Python 3 for these Python 2 helpers<commit_after>
|
"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args) # pylint:disable=undefined-variable
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text) # pylint:disable=undefined-variable
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape') # pylint:disable=undefined-variable
|
"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args)
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text)
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape')
Disable error-checking that assumes Python 3 for these Python 2 helpers"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args) # pylint:disable=undefined-variable
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text) # pylint:disable=undefined-variable
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape') # pylint:disable=undefined-variable
|
<commit_before>"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args)
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text)
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape')
<commit_msg>Disable error-checking that assumes Python 3 for these Python 2 helpers<commit_after>"""
String/unicode helper functions
"""
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args) # pylint:disable=undefined-variable
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text) # pylint:disable=undefined-variable
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape') # pylint:disable=undefined-variable
|
66289d6620758de0da80e91c6a492e39626c9029
|
tests/integration.py
|
tests/integration.py
|
#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
|
Remove index file created in test
|
Remove index file created in test
|
Python
|
mit
|
alneberg/sillymap
|
#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
Remove index file created in test
|
#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
|
<commit_before>#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
<commit_msg>Remove index file created in test<commit_after>
|
#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
Remove index file created in test#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
|
<commit_before>#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
<commit_msg>Remove index file created in test<commit_after>#!/usr/bin/env python
import unittest
import subprocess
class TestSimpleMapping(unittest.TestCase):
def test_map_1_read(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_1.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\n')
def test_map_5_reads(self):
subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa'])
result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa', 'tests/test_data/reads_2.fq'], stdout=subprocess.PIPE)
subprocess.run(['rm', 'tests/test_data/reference.fa.silly'])
self.assertEqual(result.stdout, b'read1,5\nread2,0\nread3,10\nread4,15\nread5,5\n')
if __name__ == '__main__':
unittest.main()
|
21d940192fa390b1a2de3183e099194bceaeeafe
|
tests/test_arrays.py
|
tests/test_arrays.py
|
from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
|
from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
def test_array_initialization_over_function_calls():
assert run("""
thing Program
does start
array numbers = self.build_array()
Output.write(numbers)
does get_10
return 10
does get_7
return 7
does add with a, b
return a + b
does build_array
return [self.get_7(), self.get_10(), self.add(9, self.get_7() + self.get_10())]
""").output == """[7, 10, 26]"""
|
Add test for more complex array initization case
|
Add test for more complex array initization case
|
Python
|
mit
|
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
|
from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
Add test for more complex array initization case
|
from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
def test_array_initialization_over_function_calls():
assert run("""
thing Program
does start
array numbers = self.build_array()
Output.write(numbers)
does get_10
return 10
does get_7
return 7
does add with a, b
return a + b
does build_array
return [self.get_7(), self.get_10(), self.add(9, self.get_7() + self.get_10())]
""").output == """[7, 10, 26]"""
|
<commit_before>from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
<commit_msg>Add test for more complex array initization case<commit_after>
|
from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
def test_array_initialization_over_function_calls():
assert run("""
thing Program
does start
array numbers = self.build_array()
Output.write(numbers)
does get_10
return 10
does get_7
return 7
does add with a, b
return a + b
does build_array
return [self.get_7(), self.get_10(), self.add(9, self.get_7() + self.get_10())]
""").output == """[7, 10, 26]"""
|
from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
Add test for more complex array initization casefrom thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
def test_array_initialization_over_function_calls():
assert run("""
thing Program
does start
array numbers = self.build_array()
Output.write(numbers)
does get_10
return 10
does get_7
return 7
does add with a, b
return a + b
does build_array
return [self.get_7(), self.get_10(), self.add(9, self.get_7() + self.get_10())]
""").output == """[7, 10, 26]"""
|
<commit_before>from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
<commit_msg>Add test for more complex array initization case<commit_after>from thinglang.thinglang import run
def test_simple_arrays():
assert run("""
thing Program
does start
array names = ["yotam", "andrew", "john"]
Output.write(names)
""").output == """['yotam', 'andrew', 'john']"""
def test_array_initialization_over_function_calls():
assert run("""
thing Program
does start
array numbers = self.build_array()
Output.write(numbers)
does get_10
return 10
does get_7
return 7
does add with a, b
return a + b
does build_array
return [self.get_7(), self.get_10(), self.add(9, self.get_7() + self.get_10())]
""").output == """[7, 10, 26]"""
|
25fc6df856aa77dca6660eab7c1ce9d9e01fc2c4
|
eultheme/__init__.py
|
eultheme/__init__.py
|
__version_info__ = (1, 3, 0, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
|
__version_info__ = (1, 4, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
|
Set develop version to 1.4-dev after tagging 1.3
|
Set develop version to 1.4-dev after tagging 1.3
|
Python
|
apache-2.0
|
emory-libraries/django-eultheme,emory-libraries/django-eultheme,emory-libraries/django-eultheme
|
__version_info__ = (1, 3, 0, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
Set develop version to 1.4-dev after tagging 1.3
|
__version_info__ = (1, 4, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
|
<commit_before>__version_info__ = (1, 3, 0, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
<commit_msg>Set develop version to 1.4-dev after tagging 1.3<commit_after>
|
__version_info__ = (1, 4, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
|
__version_info__ = (1, 3, 0, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
Set develop version to 1.4-dev after tagging 1.3__version_info__ = (1, 4, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
|
<commit_before>__version_info__ = (1, 3, 0, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
<commit_msg>Set develop version to 1.4-dev after tagging 1.3<commit_after>__version_info__ = (1, 4, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
|
497be50549e9c7b3a886a1d0753386d8f93cea2b
|
tests/test_blocks.py
|
tests/test_blocks.py
|
from .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for _in=seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b, _in=seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
|
from .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for item in seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b in seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
|
Update tags for new syntax
|
Update tags for new syntax
|
Python
|
mit
|
funkybob/knights-templater,funkybob/knights-templater
|
from .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for _in=seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b, _in=seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
Update tags for new syntax
|
from .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for item in seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b in seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
|
<commit_before>from .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for _in=seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b, _in=seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
<commit_msg>Update tags for new syntax<commit_after>
|
from .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for item in seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b in seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
|
from .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for _in=seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b, _in=seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
Update tags for new syntaxfrom .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for item in seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b in seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
|
<commit_before>from .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for _in=seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b, _in=seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
<commit_msg>Update tags for new syntax<commit_after>from .utils import TemplateTestCase, Mock
class BlockTagTest(TemplateTestCase):
def test_block_parse(self):
self.assertRendered('{% block name %}%{% endblock %}', '%')
class ForTagTest(TemplateTestCase):
def test_simple_for(self):
self.assertRendered(
'{% for item in seq %}{{ item }} {% endfor %}',
'a b c d e ',
{'seq': 'abcde'},
)
def test_unpack_for(self):
self.assertRendered(
'{% for a, b in seq %}{{ a }} == {{ b }},{% endfor %}',
'a == 1,b == 2,',
{'seq': (('a', 1), ('b', 2))}
)
class IfTagTest(TemplateTestCase):
def test_simple_if(self):
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'Yes!',
{'a': 1}
)
self.assertRendered(
'{% if a == 1 %}Yes!{% endif %}',
'',
{'a': 2}
)
def test_if_else(self):
tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}'
self.assertRendered(tmpl, 'Yes!', {'a': 1})
self.assertRendered(tmpl, 'No!', {'a': 2})
|
f682e0bc4b8506a45846a74fe537917ba0ffd5bb
|
tests/test_format.py
|
tests/test_format.py
|
from unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff)
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
|
from unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff, auto_allow_exceptions_=(UnicodeEncodeError,))
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
|
Fix test case to be more explicit
|
Fix test case to be more explicit
|
Python
|
mit
|
PyCQA/isort,PyCQA/isort
|
from unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff)
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
Fix test case to be more explicit
|
from unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff, auto_allow_exceptions_=(UnicodeEncodeError,))
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
|
<commit_before>from unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff)
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
<commit_msg>Fix test case to be more explicit<commit_after>
|
from unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff, auto_allow_exceptions_=(UnicodeEncodeError,))
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
|
from unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff)
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
Fix test case to be more explicitfrom unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff, auto_allow_exceptions_=(UnicodeEncodeError,))
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
|
<commit_before>from unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff)
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
<commit_msg>Fix test case to be more explicit<commit_after>from unittest.mock import MagicMock, patch
import pytest
from hypothesis_auto import auto_pytest_magic
import isort.format
auto_pytest_magic(isort.format.show_unified_diff, auto_allow_exceptions_=(UnicodeEncodeError,))
def test_ask_whether_to_apply_changes_to_file():
with patch("isort.format.input", MagicMock(return_value="y")):
assert isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="n")):
assert not isort.format.ask_whether_to_apply_changes_to_file("")
with patch("isort.format.input", MagicMock(return_value="q")):
with pytest.raises(SystemExit):
assert isort.format.ask_whether_to_apply_changes_to_file("")
|
1e3109f154ab86273996e4b598cea706c766cb8b
|
spec/settings_spec.py
|
spec/settings_spec.py
|
# -*- coding: utf-8 -*-
from mamba import describe, context, before
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe('Settings') as _:
@before.each
def create_settings():
_.settings = Settings()
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.settings.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
|
# -*- coding: utf-8 -*-
from mamba import describe, context
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe(Settings) as _:
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.subject.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
|
Use subject for test settings
|
Use subject for test settings
|
Python
|
mit
|
jaimegildesagredo/mamba,nestorsalceda/mamba,alejandrodob/mamba,angelsanz/mamba,eferro/mamba,markng/mamba,dex4er/mamba
|
# -*- coding: utf-8 -*-
from mamba import describe, context, before
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe('Settings') as _:
@before.each
def create_settings():
_.settings = Settings()
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.settings.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
Use subject for test settings
|
# -*- coding: utf-8 -*-
from mamba import describe, context
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe(Settings) as _:
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.subject.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
|
<commit_before># -*- coding: utf-8 -*-
from mamba import describe, context, before
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe('Settings') as _:
@before.each
def create_settings():
_.settings = Settings()
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.settings.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
<commit_msg>Use subject for test settings<commit_after>
|
# -*- coding: utf-8 -*-
from mamba import describe, context
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe(Settings) as _:
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.subject.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
|
# -*- coding: utf-8 -*-
from mamba import describe, context, before
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe('Settings') as _:
@before.each
def create_settings():
_.settings = Settings()
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.settings.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
Use subject for test settings# -*- coding: utf-8 -*-
from mamba import describe, context
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe(Settings) as _:
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.subject.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
|
<commit_before># -*- coding: utf-8 -*-
from mamba import describe, context, before
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe('Settings') as _:
@before.each
def create_settings():
_.settings = Settings()
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.settings.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
<commit_msg>Use subject for test settings<commit_after># -*- coding: utf-8 -*-
from mamba import describe, context
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe(Settings) as _:
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.subject.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
|
6e04a5c4953ef3fde5f2f5b3ef4f7fd8b7e8437e
|
tests/test_server.py
|
tests/test_server.py
|
def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
|
from rocketchat_API.rocketchat import RocketChat
def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
def test_login_token(logged_rocket):
user_id = logged_rocket.headers["X-User-Id"]
auth_token = logged_rocket.headers["X-Auth-Token"]
another_rocket = RocketChat(user_id=user_id, auth_token=auth_token)
logged_user = another_rocket.me().json()
assert logged_user.get("_id") == user_id
|
Add a test to check that authentication using the token directly works
|
Add a test to check that authentication using the token directly works
|
Python
|
mit
|
jadolg/rocketchat_API
|
def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
Add a test to check that authentication using the token directly works
|
from rocketchat_API.rocketchat import RocketChat
def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
def test_login_token(logged_rocket):
user_id = logged_rocket.headers["X-User-Id"]
auth_token = logged_rocket.headers["X-Auth-Token"]
another_rocket = RocketChat(user_id=user_id, auth_token=auth_token)
logged_user = another_rocket.me().json()
assert logged_user.get("_id") == user_id
|
<commit_before>def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
<commit_msg>Add a test to check that authentication using the token directly works<commit_after>
|
from rocketchat_API.rocketchat import RocketChat
def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
def test_login_token(logged_rocket):
user_id = logged_rocket.headers["X-User-Id"]
auth_token = logged_rocket.headers["X-Auth-Token"]
another_rocket = RocketChat(user_id=user_id, auth_token=auth_token)
logged_user = another_rocket.me().json()
assert logged_user.get("_id") == user_id
|
def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
Add a test to check that authentication using the token directly worksfrom rocketchat_API.rocketchat import RocketChat
def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
def test_login_token(logged_rocket):
user_id = logged_rocket.headers["X-User-Id"]
auth_token = logged_rocket.headers["X-Auth-Token"]
another_rocket = RocketChat(user_id=user_id, auth_token=auth_token)
logged_user = another_rocket.me().json()
assert logged_user.get("_id") == user_id
|
<commit_before>def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
<commit_msg>Add a test to check that authentication using the token directly works<commit_after>from rocketchat_API.rocketchat import RocketChat
def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
def test_login_token(logged_rocket):
user_id = logged_rocket.headers["X-User-Id"]
auth_token = logged_rocket.headers["X-Auth-Token"]
another_rocket = RocketChat(user_id=user_id, auth_token=auth_token)
logged_user = another_rocket.me().json()
assert logged_user.get("_id") == user_id
|
0f08eb828091204c6131ee868a43f2a8f3ed73f4
|
tests/test_widget.py
|
tests/test_widget.py
|
from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
|
import re
from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
@staticmethod
def test_render():
"""Tests whether the :see:LocalizedFieldWidget correctly
render."""
widget = LocalizedFieldWidget()
output = widget.render(name='title', value=None)
assert bool(re.search('<label (.|\n|\t)*>\w+<\/label>', output))
|
Add test on render method
|
Add test on render method
|
Python
|
mit
|
SectorLabs/django-localized-fields,SectorLabs/django-localized-fields,SectorLabs/django-localized-fields
|
from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
Add test on render method
|
import re
from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
@staticmethod
def test_render():
"""Tests whether the :see:LocalizedFieldWidget correctly
render."""
widget = LocalizedFieldWidget()
output = widget.render(name='title', value=None)
assert bool(re.search('<label (.|\n|\t)*>\w+<\/label>', output))
|
<commit_before>from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
<commit_msg>Add test on render method<commit_after>
|
import re
from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
@staticmethod
def test_render():
"""Tests whether the :see:LocalizedFieldWidget correctly
render."""
widget = LocalizedFieldWidget()
output = widget.render(name='title', value=None)
assert bool(re.search('<label (.|\n|\t)*>\w+<\/label>', output))
|
from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
Add test on render methodimport re
from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
@staticmethod
def test_render():
"""Tests whether the :see:LocalizedFieldWidget correctly
render."""
widget = LocalizedFieldWidget()
output = widget.render(name='title', value=None)
assert bool(re.search('<label (.|\n|\t)*>\w+<\/label>', output))
|
<commit_before>from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
<commit_msg>Add test on render method<commit_after>import re
from django.conf import settings
from django.test import TestCase
from localized_fields.value import LocalizedValue
from localized_fields.widgets import LocalizedFieldWidget
class LocalizedFieldWidgetTestCase(TestCase):
"""Tests the workings of the :see:LocalizedFieldWidget class."""
@staticmethod
def test_widget_creation():
"""Tests whether a widget is created for every
language correctly."""
widget = LocalizedFieldWidget()
assert len(widget.widgets) == len(settings.LANGUAGES)
@staticmethod
def test_decompress():
"""Tests whether a :see:LocalizedValue instance
can correctly be "decompressed" over the available
widgets."""
localized_value = LocalizedValue()
for lang_code, lang_name in settings.LANGUAGES:
localized_value.set(lang_code, lang_name)
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(localized_value)
for (lang_code, _), value in zip(settings.LANGUAGES, decompressed_values):
assert localized_value.get(lang_code) == value
@staticmethod
def test_decompress_none():
"""Tests whether the :see:LocalizedFieldWidget correctly
handles :see:None."""
widget = LocalizedFieldWidget()
decompressed_values = widget.decompress(None)
for _, value in zip(settings.LANGUAGES, decompressed_values):
assert not value
@staticmethod
def test_render():
"""Tests whether the :see:LocalizedFieldWidget correctly
render."""
widget = LocalizedFieldWidget()
output = widget.render(name='title', value=None)
assert bool(re.search('<label (.|\n|\t)*>\w+<\/label>', output))
|
96513ab379341d6db0aa7ce16aa20b8d1a93dc69
|
runtests.py
|
runtests.py
|
#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"forums",
"forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
|
#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"pinax.forums",
"pinax.forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="pinax.forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
|
Fix two left over renames
|
Fix two left over renames
|
Python
|
mit
|
pinax/pinax-forums
|
#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"forums",
"forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
Fix two left over renames
|
#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"pinax.forums",
"pinax.forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="pinax.forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
|
<commit_before>#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"forums",
"forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
<commit_msg>Fix two left over renames<commit_after>
|
#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"pinax.forums",
"pinax.forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="pinax.forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
|
#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"forums",
"forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
Fix two left over renames#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"pinax.forums",
"pinax.forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="pinax.forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
|
<commit_before>#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"forums",
"forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
<commit_msg>Fix two left over renames<commit_after>#!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"account",
"pinax.forums",
"pinax.forums.tests"
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="pinax.forums.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
if not test_args:
test_args = ["pinax.forums.tests"]
except ImportError:
from django.test.simple import DjangoTestSuiteRunner
runner_class = DjangoTestSuiteRunner
test_args = ["tests"]
failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == "__main__":
runtests(*sys.argv[1:])
|
0398c7539c1bebcaa6622576f4acef970394d6a7
|
runtests.py
|
runtests.py
|
#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
SOUTH_MIGRATION_MODULES={
'email_log': 'email_log.south_migrations',
},
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
|
#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
try:
from django.test.runner import DiscoverRunner
except:
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
else:
failures = DiscoverRunner(failfast=False).run_tests(
['email_log.tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
|
Fix test runner for trunk
|
Fix test runner for trunk
|
Python
|
mit
|
treyhunner/django-email-log,treyhunner/django-email-log
|
#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
SOUTH_MIGRATION_MODULES={
'email_log': 'email_log.south_migrations',
},
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
Fix test runner for trunk
|
#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
try:
from django.test.runner import DiscoverRunner
except:
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
else:
failures = DiscoverRunner(failfast=False).run_tests(
['email_log.tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
|
<commit_before>#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
SOUTH_MIGRATION_MODULES={
'email_log': 'email_log.south_migrations',
},
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
<commit_msg>Fix test runner for trunk<commit_after>
|
#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
try:
from django.test.runner import DiscoverRunner
except:
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
else:
failures = DiscoverRunner(failfast=False).run_tests(
['email_log.tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
|
#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
SOUTH_MIGRATION_MODULES={
'email_log': 'email_log.south_migrations',
},
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
Fix test runner for trunk#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
try:
from django.test.runner import DiscoverRunner
except:
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
else:
failures = DiscoverRunner(failfast=False).run_tests(
['email_log.tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
|
<commit_before>#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
SOUTH_MIGRATION_MODULES={
'email_log': 'email_log.south_migrations',
},
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
<commit_msg>Fix test runner for trunk<commit_after>#!/usr/bin/env python
import sys
from os.path import abspath, dirname
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
settings.configure(
INSTALLED_APPS=(
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.admin',
'email_log',
'email_log.tests',
),
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
EMAIL_LOG_BACKEND = 'django.core.mail.backends.locmem.EmailBackend',
ROOT_URLCONF='email_log.tests.urls',
)
def runtests():
if hasattr(django, 'setup'):
django.setup()
try:
from django.test.runner import DiscoverRunner
except:
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(failfast=False).run_tests(['tests'])
else:
failures = DiscoverRunner(failfast=False).run_tests(
['email_log.tests'])
sys.exit(failures)
if __name__ == "__main__":
runtests()
|
ae8b0d5eab43a349f33d3eb907565cb2931e15cd
|
jedi/api/replstartup.py
|
jedi/api/replstartup.py
|
"""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
|
"""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
from jedi import __version__ as __jedi_version__
print('REPL completion using Jedi %s' % __jedi_version__)
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
|
Print the Jedi version when REPL completion is used
|
Print the Jedi version when REPL completion is used
This also makes debugging easier, because people see which completion
they're actually using.
|
Python
|
mit
|
tjwei/jedi,mfussenegger/jedi,WoLpH/jedi,mfussenegger/jedi,jonashaag/jedi,flurischt/jedi,WoLpH/jedi,flurischt/jedi,jonashaag/jedi,dwillmer/jedi,dwillmer/jedi,tjwei/jedi
|
"""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
Print the Jedi version when REPL completion is used
This also makes debugging easier, because people see which completion
they're actually using.
|
"""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
from jedi import __version__ as __jedi_version__
print('REPL completion using Jedi %s' % __jedi_version__)
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
|
<commit_before>"""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
<commit_msg>Print the Jedi version when REPL completion is used
This also makes debugging easier, because people see which completion
they're actually using.<commit_after>
|
"""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
from jedi import __version__ as __jedi_version__
print('REPL completion using Jedi %s' % __jedi_version__)
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
|
"""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
Print the Jedi version when REPL completion is used
This also makes debugging easier, because people see which completion
they're actually using."""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
from jedi import __version__ as __jedi_version__
print('REPL completion using Jedi %s' % __jedi_version__)
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
|
<commit_before>"""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
<commit_msg>Print the Jedi version when REPL completion is used
This also makes debugging easier, because people see which completion
they're actually using.<commit_after>"""
To use Jedi completion in Python interpreter, add the following in your shell
setup (e.g., ``.bashrc``)::
export PYTHONSTARTUP="$(python -m jedi repl)"
Then you will be able to use Jedi completer in your Python interpreter::
$ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.join().split().in<TAB> # doctest: +SKIP
os.path.join().split().index os.path.join().split().insert
"""
import jedi.utils
from jedi import __version__ as __jedi_version__
print('REPL completion using Jedi %s' % __jedi_version__)
jedi.utils.setup_readline()
del jedi
# Note: try not to do many things here, as it will contaminate global
# namespace of the interpreter.
|
e50333baa8390ae3bedb77f1442c9d90cf6ea4b0
|
mint/userlisting.py
|
mint/userlisting.py
|
#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
|
#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users WHERE active=1
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
|
Hide yet-to-be-activated usernames from listings
|
Hide yet-to-be-activated usernames from listings
|
Python
|
apache-2.0
|
sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint
|
#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
Hide yet-to-be-activated usernames from listings
|
#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users WHERE active=1
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
|
<commit_before>#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
<commit_msg>Hide yet-to-be-activated usernames from listings<commit_after>
|
#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users WHERE active=1
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
|
#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
Hide yet-to-be-activated usernames from listings#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users WHERE active=1
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
|
<commit_before>#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
<commit_msg>Hide yet-to-be-activated usernames from listings<commit_after>#
# Copyright (c) 2005 rpath, Inc.
#
# All Rights Reserved
#
(
USERNAME_ASC,
USERNAME_DES,
FULLNAME_ASC,
FULLNAME_DES,
CREATED_ASC,
CREATED_DES,
ACCESSED_ASC,
ACCESSED_DES
) = range(0, 8)
blurbindex = 5
blurbtrunclength = 300
sqlbase = """SELECT userid, username, fullname, timeCreated, timeAccessed,
blurb FROM users WHERE active=1
ORDER BY %s
LIMIT %d
OFFSET %d"""
ordersql = {
USERNAME_ASC: "username ASC",
USERNAME_DES: "username DESC",
FULLNAME_ASC: "fullname ASC",
FULLNAME_DES: "fullname DESC",
CREATED_ASC: "timeCreated ASC",
CREATED_DES: "timeCreated DESC",
ACCESSED_ASC: "timeAccessed ASC",
ACCESSED_DES: "timeAccessed DESC"
}
orderhtml = {
USERNAME_ASC: "Username in ascending order",
USERNAME_DES: "Username in descending order",
FULLNAME_ASC: "Full name in ascending order",
FULLNAME_DES: "Full name in descending order",
CREATED_ASC: "Oldest users",
CREATED_DES: "Newest users",
ACCESSED_ASC: "Least recently accessed",
ACCESSED_DES: "Most recently accessed"
}
|
d45df810c6ae9482f935ccfddef6c96438d893a3
|
OpenPNM/Geometry/models/pore_centroid.py
|
OpenPNM/Geometry/models/pore_centroid.py
|
r"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
value[geom_pore] = _sp.mean(verts, axis=0)
return value
|
r"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
value.fill(0.0)
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
if len(verts) > 0:
value[geom_pore] = _sp.mean(verts, axis=0)
return value
|
Fix bug in pore centroid
|
Fix bug in pore centroid
|
Python
|
mit
|
amdouglas/OpenPNM,PMEAL/OpenPNM,TomTranter/OpenPNM,stadelmanma/OpenPNM,amdouglas/OpenPNM
|
r"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
value[geom_pore] = _sp.mean(verts, axis=0)
return value
Fix bug in pore centroid
|
r"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
value.fill(0.0)
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
if len(verts) > 0:
value[geom_pore] = _sp.mean(verts, axis=0)
return value
|
<commit_before>r"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
value[geom_pore] = _sp.mean(verts, axis=0)
return value
<commit_msg>Fix bug in pore centroid<commit_after>
|
r"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
value.fill(0.0)
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
if len(verts) > 0:
value[geom_pore] = _sp.mean(verts, axis=0)
return value
|
r"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
value[geom_pore] = _sp.mean(verts, axis=0)
return value
Fix bug in pore centroidr"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
value.fill(0.0)
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
if len(verts) > 0:
value[geom_pore] = _sp.mean(verts, axis=0)
return value
|
<commit_before>r"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
value[geom_pore] = _sp.mean(verts, axis=0)
return value
<commit_msg>Fix bug in pore centroid<commit_after>r"""
===============================================================================
pore_centroid
===============================================================================
"""
import scipy as _sp
def voronoi(network, geometry, vertices='throat.centroid', **kwargs):
r"""
Calculate the centroid from the mean of the throat centroids
"""
value = _sp.ndarray([geometry.num_pores(), 3])
value.fill(0.0)
pore_map = geometry.map_pores(target=network,
pores=geometry.pores(),
return_mapping=True)
for i, net_pore in enumerate(pore_map['target']):
geom_pore = pore_map['source'][i]
net_throats = network.find_neighbor_throats(net_pore)
geom_throats = network.map_throats(target=geometry,
throats=net_throats,
return_mapping=False)
verts = geometry[vertices][geom_throats]
" Ignore all zero centroids "
verts = verts[~_sp.all(verts == 0, axis=1)]
if len(verts) > 0:
value[geom_pore] = _sp.mean(verts, axis=0)
return value
|
4d4279cf97d6b925e687423a0681793c9ab3ef56
|
runtests.py
|
runtests.py
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.
|
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.
|
Python
|
mit
|
eugena/django-localeurl
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
<commit_before>#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
<commit_msg>Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.<commit_after>
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
<commit_before>#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
<commit_msg>Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.<commit_after>#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'localeurl.tests',
'django.contrib.sites', # for sitemap test
),
ROOT_URLCONF='localeurl.tests.test_urls',
SITE_ID=1,
)
if VERSION >= (1, 2):
settings_dict["DATABASES"] = {
"default": {
"ENGINE": "django.db.backends.sqlite3"
}}
else:
settings_dict["DATABASE_ENGINE"] = "sqlite3"
settings.configure(**settings_dict)
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.simple import DjangoTestSuiteRunner
def run_tests(test_args, verbosity, interactive):
runner = DjangoTestSuiteRunner(
verbosity=verbosity, interactive=interactive, failfast=False)
return runner.run_tests(test_args)
except ImportError:
# for Django versions that don't have DjangoTestSuiteRunner
from django.test.simple import run_tests
failures = run_tests(
test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
60ed71891d628989fa813f2f750e8cb9d1f19f9d
|
runtests.py
|
runtests.py
|
#!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
#!/usr/bin/env python
import sys
import django
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
if django.VERSION >= (1,7,0):
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
Call django.setup() for Django >= 1.7.0
|
Call django.setup() for Django >= 1.7.0
|
Python
|
bsd-3-clause
|
rochapps/django-secure-input,rochapps/django-secure-input,rochapps/django-secure-input
|
#!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
Call django.setup() for Django >= 1.7.0
|
#!/usr/bin/env python
import sys
import django
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
if django.VERSION >= (1,7,0):
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
<commit_before>#!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
<commit_msg>Call django.setup() for Django >= 1.7.0<commit_after>
|
#!/usr/bin/env python
import sys
import django
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
if django.VERSION >= (1,7,0):
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
#!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
Call django.setup() for Django >= 1.7.0#!/usr/bin/env python
import sys
import django
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
if django.VERSION >= (1,7,0):
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
<commit_before>#!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
<commit_msg>Call django.setup() for Django >= 1.7.0<commit_after>#!/usr/bin/env python
import sys
import django
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
'secure_input',
),
SITE_ID=1,
SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
)
from django.test.utils import get_runner
def runtests():
if django.VERSION >= (1,7,0):
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['secure_input', ])
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
1cccb432d0f7abc468a36a22ee5c9d3845fbd636
|
runtests.py
|
runtests.py
|
#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit()
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.failures))
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Return exit code indicating failure
|
Return exit code indicating failure
|
Python
|
mit
|
giserh/peewee,coleifer/peewee,Dipsomaniac/peewee,coreos/peewee,d1hotpep/peewee,jarrahwu/peewee,mackjoner/peewee,d1hotpep/peewee,bopo/peewee,bopo/peewee,coleifer/peewee,jarrahwu/peewee,jnovinger/peewee,wenxer/peewee,coleifer/peewee,fuzeman/peewee,fuzeman/peewee,new-xiaji/peewee,wenxer/peewee,zhang625272514/peewee,Sunzhifeng/peewee,teserak/peewee,zhang625272514/peewee,Sunzhifeng/peewee,new-xiaji/peewee,new-xiaji/peewee,Dipsomaniac/peewee,Sunzhifeng/peewee,jarrahwu/peewee,ghukill/peewee,ronyb29/peewee,giserh/peewee,bopo/peewee,coreos/peewee,stas/peewee,Dipsomaniac/peewee,zhang625272514/peewee,coreos/peewee,softside/peewee,py4a/peewee,jnovinger/peewee,lez/peewee
|
#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit()
if __name__ == '__main__':
runtests(*sys.argv[1:])
Return exit code indicating failure
|
#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.failures))
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
<commit_before>#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit()
if __name__ == '__main__':
runtests(*sys.argv[1:])
<commit_msg>Return exit code indicating failure<commit_after>
|
#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.failures))
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit()
if __name__ == '__main__':
runtests(*sys.argv[1:])
Return exit code indicating failure#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.failures))
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
<commit_before>#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit()
if __name__ == '__main__':
runtests(*sys.argv[1:])
<commit_msg>Return exit code indicating failure<commit_after>#!/usr/bin/env python
import sys
import unittest
from os.path import dirname, abspath
import tests
def runtests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(bool(result.failures))
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
7648ac7ae01ee6cde8871128e162e8a4d5322b87
|
s3upload.py
|
s3upload.py
|
#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
object = s3.Bucket('ictrp-data').upload_file(sys.argv[1], sys.argv[1])
object.Acl().put(ACL='public-read')
|
#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
with open(sys.argv[1], 'rb') as f:
object = s3.Bucket('ictrp-data').put_object(Key=sys.argv[1], Body=f)
object.Acl().put(ACL='public-read')
|
Fix failing attempt to set ACL
|
Fix failing attempt to set ACL
|
Python
|
mit
|
gertvv/ictrp-retrieval,gertvv/ictrp-retrieval
|
#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
object = s3.Bucket('ictrp-data').upload_file(sys.argv[1], sys.argv[1])
object.Acl().put(ACL='public-read')
Fix failing attempt to set ACL
|
#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
with open(sys.argv[1], 'rb') as f:
object = s3.Bucket('ictrp-data').put_object(Key=sys.argv[1], Body=f)
object.Acl().put(ACL='public-read')
|
<commit_before>#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
object = s3.Bucket('ictrp-data').upload_file(sys.argv[1], sys.argv[1])
object.Acl().put(ACL='public-read')
<commit_msg>Fix failing attempt to set ACL<commit_after>
|
#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
with open(sys.argv[1], 'rb') as f:
object = s3.Bucket('ictrp-data').put_object(Key=sys.argv[1], Body=f)
object.Acl().put(ACL='public-read')
|
#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
object = s3.Bucket('ictrp-data').upload_file(sys.argv[1], sys.argv[1])
object.Acl().put(ACL='public-read')
Fix failing attempt to set ACL#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
with open(sys.argv[1], 'rb') as f:
object = s3.Bucket('ictrp-data').put_object(Key=sys.argv[1], Body=f)
object.Acl().put(ACL='public-read')
|
<commit_before>#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
object = s3.Bucket('ictrp-data').upload_file(sys.argv[1], sys.argv[1])
object.Acl().put(ACL='public-read')
<commit_msg>Fix failing attempt to set ACL<commit_after>#!/usr/bin/python
import sys
import boto3
s3 = boto3.resource('s3')
with open(sys.argv[1], 'rb') as f:
object = s3.Bucket('ictrp-data').put_object(Key=sys.argv[1], Body=f)
object.Acl().put(ACL='public-read')
|
5cbc6b6f6191d69879d9ab077b57bf2b4da04586
|
sessions/__about__.py
|
sessions/__about__.py
|
# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "Sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__
|
# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__
|
Rename the library sessions instead of Sessions
|
Rename the library sessions instead of Sessions
|
Python
|
apache-2.0
|
dstufft/sessions
|
# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "Sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__Rename the library sessions instead of Sessions
|
# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__
|
<commit_before># Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "Sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__<commit_msg>Rename the library sessions instead of Sessions<commit_after>
|
# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__
|
# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "Sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__Rename the library sessions instead of Sessions# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__
|
<commit_before># Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "Sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__<commit_msg>Rename the library sessions instead of Sessions<commit_after># Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "sessions"
__summary__ = "Web framework agnostic management of sessions"
__uri__ = "https://github.com/dstufft/sessions"
__version__ = "0.1.0"
__author__ = "Donald Stufft"
__email__ = "donald@stufft.io"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__
|
80aa4574da8754db544d66167b61823de1cbf281
|
source/globals/fieldtests.py
|
source/globals/fieldtests.py
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \param field_list
# \b \e tuple|list : List of wx control to be checked
# \param enabled
# \b \e bool : Status to check for (True=enabled, False=disabled)
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list, enabled=True):
if not isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list, enabled)
for F in field_list:
if not FieldEnabled(F, enabled):
return False
return True
|
Fix FieldsEnabled function & add 'enabled' argument
|
Fix FieldsEnabled function & add 'enabled' argument
|
Python
|
mit
|
AntumDeluge/desktop_recorder,AntumDeluge/desktop_recorder
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
Fix FieldsEnabled function & add 'enabled' argument
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \param field_list
# \b \e tuple|list : List of wx control to be checked
# \param enabled
# \b \e bool : Status to check for (True=enabled, False=disabled)
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list, enabled=True):
if not isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list, enabled)
for F in field_list:
if not FieldEnabled(F, enabled):
return False
return True
|
<commit_before># -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
<commit_msg>Fix FieldsEnabled function & add 'enabled' argument<commit_after>
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \param field_list
# \b \e tuple|list : List of wx control to be checked
# \param enabled
# \b \e bool : Status to check for (True=enabled, False=disabled)
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list, enabled=True):
if not isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list, enabled)
for F in field_list:
if not FieldEnabled(F, enabled):
return False
return True
|
# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
Fix FieldsEnabled function & add 'enabled' argument# -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \param field_list
# \b \e tuple|list : List of wx control to be checked
# \param enabled
# \b \e bool : Status to check for (True=enabled, False=disabled)
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list, enabled=True):
if not isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list, enabled)
for F in field_list:
if not FieldEnabled(F, enabled):
return False
return True
|
<commit_before># -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list):
if isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list)
for F in field_list:
if not FieldEnabled(F):
return False
return True
<commit_msg>Fix FieldsEnabled function & add 'enabled' argument<commit_after># -*- coding: utf-8 -*-
## \package globals.fieldtests
# MIT licensing
# See: LICENSE.txt
import wx
## Tests if a wx control/instance is enabled/disabled
#
# Function for compatibility between wx versions
# \param field
# \b \e wx.Window : the wx control to check
# \param enabled
# \b \e bool : Check if enabled or disabled
# \return
# \b \e bool : True if field's enabled status is same as 'enabled'
def FieldEnabled(field, enabled=True):
if wx.MAJOR_VERSION > 2:
return field.IsThisEnabled() == enabled
else:
return field.IsEnabled() == enabled
## Tests if a wx control/instance is disabled
#
# \param field
# \b \e wx.Window : The wx field to check
# \return
# \b \e : True if field is disabled
def FieldDisabled(field):
return FieldEnabled(field, False)
## Tests multiple fields
#
# \param field_list
# \b \e tuple|list : List of wx control to be checked
# \param enabled
# \b \e bool : Status to check for (True=enabled, False=disabled)
# \return
# \b \e bool : True if all fields are enabled
def FieldsEnabled(field_list, enabled=True):
if not isinstance(field_list, (tuple, list)):
return FieldEnabled(field_list, enabled)
for F in field_list:
if not FieldEnabled(F, enabled):
return False
return True
|
7060e3f1b1e8bda4c96cdc4b0c84ae344ac81c76
|
Sketches/MPS/test/test_Selector.py
|
Sketches/MPS/test/test_Selector.py
|
#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
if __name__=="__main__":
unittest.main()
|
#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
class SmokeTests_Selector(unittest.TestCase):
def test_SmokeTest(self):
"""__init__ - Called with no arguments succeeds"""
S = Selector()
self.assert_(isinstance(S, Axon.Component.component))
if __name__=="__main__":
unittest.main()
|
Add the most basic smoke test. We make a check that the resulting object is a minimal component at least.
|
Add the most basic smoke test. We make a check that the resulting object is a minimal component at least.
|
Python
|
apache-2.0
|
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
|
#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
if __name__=="__main__":
unittest.main()
Add the most basic smoke test. We make a check that the resulting object is a minimal component at least.
|
#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
class SmokeTests_Selector(unittest.TestCase):
def test_SmokeTest(self):
"""__init__ - Called with no arguments succeeds"""
S = Selector()
self.assert_(isinstance(S, Axon.Component.component))
if __name__=="__main__":
unittest.main()
|
<commit_before>#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
if __name__=="__main__":
unittest.main()
<commit_msg>Add the most basic smoke test. We make a check that the resulting object is a minimal component at least.<commit_after>
|
#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
class SmokeTests_Selector(unittest.TestCase):
def test_SmokeTest(self):
"""__init__ - Called with no arguments succeeds"""
S = Selector()
self.assert_(isinstance(S, Axon.Component.component))
if __name__=="__main__":
unittest.main()
|
#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
if __name__=="__main__":
unittest.main()
Add the most basic smoke test. We make a check that the resulting object is a minimal component at least.#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
class SmokeTests_Selector(unittest.TestCase):
def test_SmokeTest(self):
"""__init__ - Called with no arguments succeeds"""
S = Selector()
self.assert_(isinstance(S, Axon.Component.component))
if __name__=="__main__":
unittest.main()
|
<commit_before>#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
if __name__=="__main__":
unittest.main()
<commit_msg>Add the most basic smoke test. We make a check that the resulting object is a minimal component at least.<commit_after>#!/usr/bin/python
import unittest
import sys; sys.path.append("../")
from Selector import Selector
class SmokeTests_Selector(unittest.TestCase):
def test_SmokeTest(self):
"""__init__ - Called with no arguments succeeds"""
S = Selector()
self.assert_(isinstance(S, Axon.Component.component))
if __name__=="__main__":
unittest.main()
|
2b5e33bf178cd1fdd8e320051d0c99a45d7613a1
|
models/product_bundle.py
|
models/product_bundle.py
|
# -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one('product.template', string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Use of product.template instead of product.product in bundle line
|
Use of product.template instead of product.product in bundle line
|
Python
|
agpl-3.0
|
akretion/sale-workflow,richard-willowit/sale-workflow,ddico/sale-workflow,Eficent/sale-workflow,anas-taji/sale-workflow,BT-cserra/sale-workflow,BT-fgarbely/sale-workflow,fevxie/sale-workflow,diagramsoftware/sale-workflow,adhoc-dev/sale-workflow,thomaspaulb/sale-workflow,kittiu/sale-workflow,factorlibre/sale-workflow,numerigraphe/sale-workflow,xpansa/sale-workflow,brain-tec/sale-workflow,acsone/sale-workflow,brain-tec/sale-workflow,Endika/sale-workflow,open-synergy/sale-workflow,anybox/sale-workflow,BT-ojossen/sale-workflow,BT-jmichaud/sale-workflow,acsone/sale-workflow,luistorresm/sale-workflow,jjscarafia/sale-workflow,alexsandrohaag/sale-workflow,Antiun/sale-workflow,Rona111/sale-workflow,jabibi/sale-workflow,akretion/sale-workflow,numerigraphe/sale-workflow,kittiu/sale-workflow
|
# -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one('product.template', string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Use of product.template instead of product.product in bundle line
|
# -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
<commit_before># -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one('product.template', string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>Use of product.template instead of product.product in bundle line<commit_after>
|
# -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one('product.template', string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Use of product.template instead of product.product in bundle line# -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
<commit_before># -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one('product.template', string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>Use of product.template instead of product.product in bundle line<commit_after># -*- encoding: utf-8 -*-
from openerp import fields, models, _
import openerp.addons.decimal_precision as dp
class product_bundle(models.Model):
_name = 'product.bundle'
_description = 'Product bundle'
name = fields.Char(_('Name'), help=_('Product bundle name'), required=True)
bundle_line_ids = fields.Many2many(
'product.bundle.line', 'product_bundle_product_bundle_line',
'product_bundle_id', 'product_bundle_line_id', string=_('Bundle lines'))
class product_bundle_line(models.Model):
_name = 'product.bundle.line'
_description = 'Product bundle line'
product_id = fields.Many2one(
'product.product', domain=[('sale_ok', '=', True)], string=_('Product'), required=True)
quantity = fields.Float(
string=_('Quantity'), digits=dp.get_precision('Product Unit of Measure'),
required=True, default=1)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.