commit stringlengths 40 40 | old_file stringlengths 4 106 | new_file stringlengths 4 106 | old_contents stringlengths 10 2.94k | new_contents stringlengths 21 2.95k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 7 43k | ndiff stringlengths 52 3.31k | instruction stringlengths 16 444 | content stringlengths 133 4.32k | diff stringlengths 49 3.61k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7dcd2c2aa1e2fd8f17e0b564f9b77375675ccd9a | metakernel/pexpect.py | metakernel/pexpect.py | from __future__ import absolute_import
from pexpect import spawn, which, EOF, TIMEOUT
| from __future__ import absolute_import
from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
import os
try:
from pexpect import spawn
import pty
except ImportError:
pty = None
def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if 'PATH' not in os.environ or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if pty:
if is_executable_file(ff):
return ff
else:
pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
pathext = pathext.split(os.pathsep) + ['']
for ext in pathext:
if os.access(ff + ext, os.X_OK):
return ff + ext
return None
| Add handling of which on Windows | Add handling of which on Windows
| Python | bsd-3-clause | Calysto/metakernel | from __future__ import absolute_import
- from pexpect import spawn, which, EOF, TIMEOUT
+ from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
+ import os
+ try:
+ from pexpect import spawn
+ import pty
+ except ImportError:
+ pty = None
+
+
+ def which(filename):
+ '''This takes a given filename; tries to find it in the environment path;
+ then checks if it is executable. This returns the full path to the filename
+ if found and executable. Otherwise this returns None.'''
+
+ # Special case where filename contains an explicit path.
+ if os.path.dirname(filename) != '' and is_executable_file(filename):
+ return filename
+ if 'PATH' not in os.environ or os.environ['PATH'] == '':
+ p = os.defpath
+ else:
+ p = os.environ['PATH']
+ pathlist = p.split(os.pathsep)
+ for path in pathlist:
+ ff = os.path.join(path, filename)
+ if pty:
+ if is_executable_file(ff):
+ return ff
+ else:
+ pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
+ pathext = pathext.split(os.pathsep) + ['']
+ for ext in pathext:
+ if os.access(ff + ext, os.X_OK):
+ return ff + ext
+ return None
+ | Add handling of which on Windows | ## Code Before:
from __future__ import absolute_import
from pexpect import spawn, which, EOF, TIMEOUT
## Instruction:
Add handling of which on Windows
## Code After:
from __future__ import absolute_import
from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
import os
try:
from pexpect import spawn
import pty
except ImportError:
pty = None
def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then checks if it is executable. This returns the full path to the filename
if found and executable. Otherwise this returns None.'''
# Special case where filename contains an explicit path.
if os.path.dirname(filename) != '' and is_executable_file(filename):
return filename
if 'PATH' not in os.environ or os.environ['PATH'] == '':
p = os.defpath
else:
p = os.environ['PATH']
pathlist = p.split(os.pathsep)
for path in pathlist:
ff = os.path.join(path, filename)
if pty:
if is_executable_file(ff):
return ff
else:
pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
pathext = pathext.split(os.pathsep) + ['']
for ext in pathext:
if os.access(ff + ext, os.X_OK):
return ff + ext
return None
| from __future__ import absolute_import
- from pexpect import spawn, which, EOF, TIMEOUT
+ from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
+ import os
+
+ try:
+ from pexpect import spawn
+ import pty
+ except ImportError:
+ pty = None
+
+
+ def which(filename):
+ '''This takes a given filename; tries to find it in the environment path;
+ then checks if it is executable. This returns the full path to the filename
+ if found and executable. Otherwise this returns None.'''
+
+ # Special case where filename contains an explicit path.
+ if os.path.dirname(filename) != '' and is_executable_file(filename):
+ return filename
+ if 'PATH' not in os.environ or os.environ['PATH'] == '':
+ p = os.defpath
+ else:
+ p = os.environ['PATH']
+ pathlist = p.split(os.pathsep)
+ for path in pathlist:
+ ff = os.path.join(path, filename)
+ if pty:
+ if is_executable_file(ff):
+ return ff
+ else:
+ pathext = os.environ.get('Pathext', '.exe;.com;.bat;.cmd')
+ pathext = pathext.split(os.pathsep) + ['']
+ for ext in pathext:
+ if os.access(ff + ext, os.X_OK):
+ return ff + ext
+ return None |
3ed02baa8ad7fcd1f6ca5cccc4f67799ec79e272 | kimi.py | kimi.py |
import sys
def tokenize(program):
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x (* x x)))")
['(', 'define', 'square', '(', 'lambda', 'x', '(', '*', 'x', 'x', ')', ')', ')']
'''
program = program.replace("(", " ( ")
program = program.replace(")", " ) ")
tokens = program.split()
return tokens
def parse(tokens):
pass
def evaluate(tree):
pass
if __name__ == "__main__":
program = sys.argv[1]
print(tokenize(program))
|
import sys
def tokenize(string):
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x (* x x)))")
['(', 'define', 'square', '(', 'lambda', 'x', '(', '*', 'x', 'x', ')', ')', ')']
'''
string = string.replace("(", " ( ")
string = string.replace(")", " ) ")
tokens = string.split()
return tokens
def parse(tokens):
pass
def evaluate(tree):
pass
if __name__ == "__main__":
program = sys.argv[1]
print(tokenize(program))
| Rename program to string in tokenize | Rename program to string in tokenize
| Python | mit | vakila/kimi |
import sys
- def tokenize(program):
+ def tokenize(string):
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x (* x x)))")
['(', 'define', 'square', '(', 'lambda', 'x', '(', '*', 'x', 'x', ')', ')', ')']
'''
- program = program.replace("(", " ( ")
- program = program.replace(")", " ) ")
+ string = string.replace("(", " ( ")
+ string = string.replace(")", " ) ")
- tokens = program.split()
+ tokens = string.split()
return tokens
def parse(tokens):
pass
def evaluate(tree):
pass
if __name__ == "__main__":
program = sys.argv[1]
print(tokenize(program))
| Rename program to string in tokenize | ## Code Before:
import sys
def tokenize(program):
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x (* x x)))")
['(', 'define', 'square', '(', 'lambda', 'x', '(', '*', 'x', 'x', ')', ')', ')']
'''
program = program.replace("(", " ( ")
program = program.replace(")", " ) ")
tokens = program.split()
return tokens
def parse(tokens):
pass
def evaluate(tree):
pass
if __name__ == "__main__":
program = sys.argv[1]
print(tokenize(program))
## Instruction:
Rename program to string in tokenize
## Code After:
import sys
def tokenize(string):
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x (* x x)))")
['(', 'define', 'square', '(', 'lambda', 'x', '(', '*', 'x', 'x', ')', ')', ')']
'''
string = string.replace("(", " ( ")
string = string.replace(")", " ) ")
tokens = string.split()
return tokens
def parse(tokens):
pass
def evaluate(tree):
pass
if __name__ == "__main__":
program = sys.argv[1]
print(tokenize(program))
|
import sys
- def tokenize(program):
? ^ ^ ---
+ def tokenize(string):
? ^^ ^^
'''Take a Kimi program as a string, return the tokenized program as a list of strings.
>>> tokenize("(+ 1 2)")
['(', '+', '1', '2', ')']
>>> tokenize("(define square (lambda x (* x x)))")
['(', 'define', 'square', '(', 'lambda', 'x', '(', '*', 'x', 'x', ')', ')', ')']
'''
- program = program.replace("(", " ( ")
? ^ ^ --- ^ ^ ---
+ string = string.replace("(", " ( ")
? ^^ ^^ ^^ ^^
- program = program.replace(")", " ) ")
? ^ ^ --- ^ ^ ---
+ string = string.replace(")", " ) ")
? ^^ ^^ ^^ ^^
- tokens = program.split()
? ^ ^ ---
+ tokens = string.split()
? ^^ ^^
return tokens
def parse(tokens):
pass
def evaluate(tree):
pass
if __name__ == "__main__":
program = sys.argv[1]
print(tokenize(program)) |
01e4b6c3cbd11058e3d60a635048998c24138ddb | instana/__init__.py | instana/__init__.py | from __future__ import absolute_import
import opentracing
from .sensor import Sensor
from .tracer import InstanaTracer
from .options import Options
# Import & initialize instrumentation
from .instrumentation import urllib3
"""
The Instana package has two core components: the sensor and the tracer.
The sensor is individual to each python process and handles process metric
collection and reporting.
The tracer upholds the OpenTracing API and is responsible for reporting
span data to Instana.
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2017 Instana Inc.'
__credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo']
__license__ = 'MIT'
__version__ = '0.7.0'
__maintainer__ = 'Peter Giacomo Lombardo'
__email__ = 'peter.lombardo@instana.com'
# For any given Python process, we only want one sensor as multiple would
# collect/report metrics in duplicate, triplicate etc..
#
# Usage example:
#
# import instana
# instana.global_sensor
#
global_sensor = Sensor(Options())
# The global OpenTracing compatible tracer used internally by
# this package.
#
# Usage example:
#
# import instana
# instana.internal_tracer.start_span(...)
#
internal_tracer = InstanaTracer()
# Set ourselves as the tracer.
opentracing.tracer = internal_tracer
| from __future__ import absolute_import
import os
import opentracing
from .sensor import Sensor
from .tracer import InstanaTracer
from .options import Options
if "INSTANA_DISABLE_AUTO_INSTR" not in os.environ:
# Import & initialize instrumentation
from .instrumentation import urllib3
"""
The Instana package has two core components: the sensor and the tracer.
The sensor is individual to each python process and handles process metric
collection and reporting.
The tracer upholds the OpenTracing API and is responsible for reporting
span data to Instana.
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2017 Instana Inc.'
__credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo']
__license__ = 'MIT'
__version__ = '0.7.0'
__maintainer__ = 'Peter Giacomo Lombardo'
__email__ = 'peter.lombardo@instana.com'
# For any given Python process, we only want one sensor as multiple would
# collect/report metrics in duplicate, triplicate etc..
#
# Usage example:
#
# import instana
# instana.global_sensor
#
global_sensor = Sensor(Options())
# The global OpenTracing compatible tracer used internally by
# this package.
#
# Usage example:
#
# import instana
# instana.internal_tracer.start_span(...)
#
internal_tracer = InstanaTracer()
# Set ourselves as the tracer.
opentracing.tracer = internal_tracer
| Add environment variable to disable automatic instrumentation | Add environment variable to disable automatic instrumentation
| Python | mit | instana/python-sensor,instana/python-sensor | from __future__ import absolute_import
+ import os
import opentracing
from .sensor import Sensor
from .tracer import InstanaTracer
from .options import Options
+ if "INSTANA_DISABLE_AUTO_INSTR" not in os.environ:
- # Import & initialize instrumentation
+ # Import & initialize instrumentation
- from .instrumentation import urllib3
+ from .instrumentation import urllib3
"""
The Instana package has two core components: the sensor and the tracer.
The sensor is individual to each python process and handles process metric
collection and reporting.
The tracer upholds the OpenTracing API and is responsible for reporting
span data to Instana.
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2017 Instana Inc.'
__credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo']
__license__ = 'MIT'
__version__ = '0.7.0'
__maintainer__ = 'Peter Giacomo Lombardo'
__email__ = 'peter.lombardo@instana.com'
# For any given Python process, we only want one sensor as multiple would
# collect/report metrics in duplicate, triplicate etc..
#
# Usage example:
#
# import instana
# instana.global_sensor
#
global_sensor = Sensor(Options())
# The global OpenTracing compatible tracer used internally by
# this package.
#
# Usage example:
#
# import instana
# instana.internal_tracer.start_span(...)
#
internal_tracer = InstanaTracer()
# Set ourselves as the tracer.
opentracing.tracer = internal_tracer
| Add environment variable to disable automatic instrumentation | ## Code Before:
from __future__ import absolute_import
import opentracing
from .sensor import Sensor
from .tracer import InstanaTracer
from .options import Options
# Import & initialize instrumentation
from .instrumentation import urllib3
"""
The Instana package has two core components: the sensor and the tracer.
The sensor is individual to each python process and handles process metric
collection and reporting.
The tracer upholds the OpenTracing API and is responsible for reporting
span data to Instana.
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2017 Instana Inc.'
__credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo']
__license__ = 'MIT'
__version__ = '0.7.0'
__maintainer__ = 'Peter Giacomo Lombardo'
__email__ = 'peter.lombardo@instana.com'
# For any given Python process, we only want one sensor as multiple would
# collect/report metrics in duplicate, triplicate etc..
#
# Usage example:
#
# import instana
# instana.global_sensor
#
global_sensor = Sensor(Options())
# The global OpenTracing compatible tracer used internally by
# this package.
#
# Usage example:
#
# import instana
# instana.internal_tracer.start_span(...)
#
internal_tracer = InstanaTracer()
# Set ourselves as the tracer.
opentracing.tracer = internal_tracer
## Instruction:
Add environment variable to disable automatic instrumentation
## Code After:
from __future__ import absolute_import
import os
import opentracing
from .sensor import Sensor
from .tracer import InstanaTracer
from .options import Options
if "INSTANA_DISABLE_AUTO_INSTR" not in os.environ:
# Import & initialize instrumentation
from .instrumentation import urllib3
"""
The Instana package has two core components: the sensor and the tracer.
The sensor is individual to each python process and handles process metric
collection and reporting.
The tracer upholds the OpenTracing API and is responsible for reporting
span data to Instana.
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2017 Instana Inc.'
__credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo']
__license__ = 'MIT'
__version__ = '0.7.0'
__maintainer__ = 'Peter Giacomo Lombardo'
__email__ = 'peter.lombardo@instana.com'
# For any given Python process, we only want one sensor as multiple would
# collect/report metrics in duplicate, triplicate etc..
#
# Usage example:
#
# import instana
# instana.global_sensor
#
global_sensor = Sensor(Options())
# The global OpenTracing compatible tracer used internally by
# this package.
#
# Usage example:
#
# import instana
# instana.internal_tracer.start_span(...)
#
internal_tracer = InstanaTracer()
# Set ourselves as the tracer.
opentracing.tracer = internal_tracer
| from __future__ import absolute_import
+ import os
import opentracing
from .sensor import Sensor
from .tracer import InstanaTracer
from .options import Options
+ if "INSTANA_DISABLE_AUTO_INSTR" not in os.environ:
- # Import & initialize instrumentation
+ # Import & initialize instrumentation
? ++++
- from .instrumentation import urllib3
+ from .instrumentation import urllib3
? ++++
"""
The Instana package has two core components: the sensor and the tracer.
The sensor is individual to each python process and handles process metric
collection and reporting.
The tracer upholds the OpenTracing API and is responsible for reporting
span data to Instana.
"""
__author__ = 'Instana Inc.'
__copyright__ = 'Copyright 2017 Instana Inc.'
__credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo']
__license__ = 'MIT'
__version__ = '0.7.0'
__maintainer__ = 'Peter Giacomo Lombardo'
__email__ = 'peter.lombardo@instana.com'
# For any given Python process, we only want one sensor as multiple would
# collect/report metrics in duplicate, triplicate etc..
#
# Usage example:
#
# import instana
# instana.global_sensor
#
global_sensor = Sensor(Options())
# The global OpenTracing compatible tracer used internally by
# this package.
#
# Usage example:
#
# import instana
# instana.internal_tracer.start_span(...)
#
internal_tracer = InstanaTracer()
# Set ourselves as the tracer.
opentracing.tracer = internal_tracer |
fa01bae61830e501e62997f456f9533b654eb425 | utils.py | utils.py | import numpy as np
def overwrite_labels(y):
classes = np.unique(y)
y[y==classes[0]] = -1
y[y==classes[1]] = 1
return y
| import numpy as np
from sklearn import cross_validation
def overwrite_labels(y):
classes = np.unique(y)
y[y==classes[0]] = -1
y[y==classes[1]] = 1
return y
def train_test_split(X, y, test_size=0.2):
data = cross_validation.train_test_split(X, y, test_size=test_size)
training = data[0], data[2]
test = data[1], data[3]
return training, test
| Add data splitter for cross validation | Add data splitter for cross validation
| Python | mit | IshitaTakeshi/SCW | import numpy as np
+ from sklearn import cross_validation
def overwrite_labels(y):
classes = np.unique(y)
y[y==classes[0]] = -1
y[y==classes[1]] = 1
return y
+
+ def train_test_split(X, y, test_size=0.2):
+ data = cross_validation.train_test_split(X, y, test_size=test_size)
+ training = data[0], data[2]
+ test = data[1], data[3]
+ return training, test
+ | Add data splitter for cross validation | ## Code Before:
import numpy as np
def overwrite_labels(y):
classes = np.unique(y)
y[y==classes[0]] = -1
y[y==classes[1]] = 1
return y
## Instruction:
Add data splitter for cross validation
## Code After:
import numpy as np
from sklearn import cross_validation
def overwrite_labels(y):
classes = np.unique(y)
y[y==classes[0]] = -1
y[y==classes[1]] = 1
return y
def train_test_split(X, y, test_size=0.2):
data = cross_validation.train_test_split(X, y, test_size=test_size)
training = data[0], data[2]
test = data[1], data[3]
return training, test
| import numpy as np
+ from sklearn import cross_validation
def overwrite_labels(y):
classes = np.unique(y)
y[y==classes[0]] = -1
y[y==classes[1]] = 1
return y
+
+
+ def train_test_split(X, y, test_size=0.2):
+ data = cross_validation.train_test_split(X, y, test_size=test_size)
+ training = data[0], data[2]
+ test = data[1], data[3]
+ return training, test |
f97b5ec83601430ae63ac6c0a6e651cc7a0cf90d | project/encode.py | project/encode.py | from msgpack import packb, Unpacker
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
'data': obj.to_json()}
elif isinstance(obj, LazyNode):
return obj.offset
return obj
def encode(data):
return packb(data, default=encode_btree)
def decode(data, tree):
def decode_btree(obj):
if b'__class__' in obj:
cls_name = obj[b'__class__'].decode()
data = obj[b'data']
if cls_name == 'Leaf':
obj = Leaf(tree, bucket=bucket_to_lazynodes(data, tree))
elif cls_name == 'Node':
bucket = bucket_to_lazynodes(data[b'bucket'], tree)
obj = Node(tree, bucket=bucket,
rest=LazyNode(offset=data[b'rest'], tree=tree))
else:
tree.max_size = data[b'max_size']
tree.root = LazyNode(offset=data[b'root'], tree=tree)
return tree
return obj
unpacker = Unpacker(data, object_hook=decode_btree)
return(next(unpacker))
def bucket_to_lazynodes(bucket, tree):
return {k: LazyNode(offset=v, tree=tree) for k, v in bucket.items()}
| from msgpack import packb, unpackb, Unpacker
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
from checksum import add_integrity, check_integrity
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
'data': obj.to_json()}
elif isinstance(obj, LazyNode):
return obj.offset
return obj
def encode(data):
return packb(compress(add_integrity(packb(data, default=encode_btree))))
def decode(data, tree):
def decode_btree(obj):
if b'__class__' in obj:
cls_name = obj[b'__class__'].decode()
data = obj[b'data']
if cls_name == 'Leaf':
obj = Leaf(tree, bucket=bucket_to_lazynodes(data, tree))
elif cls_name == 'Node':
bucket = bucket_to_lazynodes(data[b'bucket'], tree)
obj = Node(tree, bucket=bucket,
rest=LazyNode(offset=data[b'rest'], tree=tree))
else:
tree.max_size = data[b'max_size']
tree.root = LazyNode(offset=data[b'root'], tree=tree)
return tree
return obj
data = decompress(next(Unpacker(data)))
return unpackb(check_integrity(data), object_hook=decode_btree)
def bucket_to_lazynodes(bucket, tree):
return {k: LazyNode(offset=v, tree=tree) for k, v in bucket.items()}
| Add compression and integrity checks | Add compression and integrity checks
| Python | mit | Snuggert/moda | - from msgpack import packb, Unpacker
+ from msgpack import packb, unpackb, Unpacker
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
+ from checksum import add_integrity, check_integrity
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
'data': obj.to_json()}
elif isinstance(obj, LazyNode):
return obj.offset
return obj
def encode(data):
- return packb(data, default=encode_btree)
+ return packb(compress(add_integrity(packb(data, default=encode_btree))))
def decode(data, tree):
def decode_btree(obj):
if b'__class__' in obj:
cls_name = obj[b'__class__'].decode()
data = obj[b'data']
if cls_name == 'Leaf':
obj = Leaf(tree, bucket=bucket_to_lazynodes(data, tree))
elif cls_name == 'Node':
bucket = bucket_to_lazynodes(data[b'bucket'], tree)
obj = Node(tree, bucket=bucket,
rest=LazyNode(offset=data[b'rest'], tree=tree))
else:
tree.max_size = data[b'max_size']
tree.root = LazyNode(offset=data[b'root'], tree=tree)
return tree
return obj
+ data = decompress(next(Unpacker(data)))
+
- unpacker = Unpacker(data, object_hook=decode_btree)
+ return unpackb(check_integrity(data), object_hook=decode_btree)
- return(next(unpacker))
def bucket_to_lazynodes(bucket, tree):
return {k: LazyNode(offset=v, tree=tree) for k, v in bucket.items()}
| Add compression and integrity checks | ## Code Before:
from msgpack import packb, Unpacker
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
'data': obj.to_json()}
elif isinstance(obj, LazyNode):
return obj.offset
return obj
def encode(data):
return packb(data, default=encode_btree)
def decode(data, tree):
def decode_btree(obj):
if b'__class__' in obj:
cls_name = obj[b'__class__'].decode()
data = obj[b'data']
if cls_name == 'Leaf':
obj = Leaf(tree, bucket=bucket_to_lazynodes(data, tree))
elif cls_name == 'Node':
bucket = bucket_to_lazynodes(data[b'bucket'], tree)
obj = Node(tree, bucket=bucket,
rest=LazyNode(offset=data[b'rest'], tree=tree))
else:
tree.max_size = data[b'max_size']
tree.root = LazyNode(offset=data[b'root'], tree=tree)
return tree
return obj
unpacker = Unpacker(data, object_hook=decode_btree)
return(next(unpacker))
def bucket_to_lazynodes(bucket, tree):
return {k: LazyNode(offset=v, tree=tree) for k, v in bucket.items()}
## Instruction:
Add compression and integrity checks
## Code After:
from msgpack import packb, unpackb, Unpacker
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
from checksum import add_integrity, check_integrity
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
'data': obj.to_json()}
elif isinstance(obj, LazyNode):
return obj.offset
return obj
def encode(data):
return packb(compress(add_integrity(packb(data, default=encode_btree))))
def decode(data, tree):
def decode_btree(obj):
if b'__class__' in obj:
cls_name = obj[b'__class__'].decode()
data = obj[b'data']
if cls_name == 'Leaf':
obj = Leaf(tree, bucket=bucket_to_lazynodes(data, tree))
elif cls_name == 'Node':
bucket = bucket_to_lazynodes(data[b'bucket'], tree)
obj = Node(tree, bucket=bucket,
rest=LazyNode(offset=data[b'rest'], tree=tree))
else:
tree.max_size = data[b'max_size']
tree.root = LazyNode(offset=data[b'root'], tree=tree)
return tree
return obj
data = decompress(next(Unpacker(data)))
return unpackb(check_integrity(data), object_hook=decode_btree)
def bucket_to_lazynodes(bucket, tree):
return {k: LazyNode(offset=v, tree=tree) for k, v in bucket.items()}
| - from msgpack import packb, Unpacker
+ from msgpack import packb, unpackb, Unpacker
? +++++++++
from snappy import compress, decompress # noqa
from btree import Tree, Node, Leaf, LazyNode
+ from checksum import add_integrity, check_integrity
def encode_btree(obj):
if isinstance(obj, (Tree, Node, Leaf)):
return {'__class__': obj.__class__.__name__,
'data': obj.to_json()}
elif isinstance(obj, LazyNode):
return obj.offset
return obj
def encode(data):
- return packb(data, default=encode_btree)
+ return packb(compress(add_integrity(packb(data, default=encode_btree))))
def decode(data, tree):
def decode_btree(obj):
if b'__class__' in obj:
cls_name = obj[b'__class__'].decode()
data = obj[b'data']
if cls_name == 'Leaf':
obj = Leaf(tree, bucket=bucket_to_lazynodes(data, tree))
elif cls_name == 'Node':
bucket = bucket_to_lazynodes(data[b'bucket'], tree)
obj = Node(tree, bucket=bucket,
rest=LazyNode(offset=data[b'rest'], tree=tree))
else:
tree.max_size = data[b'max_size']
tree.root = LazyNode(offset=data[b'root'], tree=tree)
return tree
return obj
+ data = decompress(next(Unpacker(data)))
+
- unpacker = Unpacker(data, object_hook=decode_btree)
? --------
+ return unpackb(check_integrity(data), object_hook=decode_btree)
? +++++++ ++++ ++++ + +++ +
- return(next(unpacker))
def bucket_to_lazynodes(bucket, tree):
return {k: LazyNode(offset=v, tree=tree) for k, v in bucket.items()} |
f559001d2c46fade2d9b62f9cb7a3f8053e8b80f | OMDB_api_scrape.py | OMDB_api_scrape.py |
import json, requests, sys, os
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
theJSON = json.loads(response.text)
# Save the JSON file
with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile:
json.dump(theJSON, outfile)
|
import requests, sys, os
import lxml.etree
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
# Save the XML file
with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile:
outfile.write(response.text)
| Convert OMDB scrapper to grab xml | Convert OMDB scrapper to grab xml
| Python | mit | samcheck/PyMedia,samcheck/PyMedia,samcheck/PyMedia |
- import json, requests, sys, os
+ import requests, sys, os
+ import lxml.etree
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
- url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
+ url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
- theJSON = json.loads(response.text)
+ # Save the XML file
+ with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile:
+ outfile.write(response.text)
- # Save the JSON file
- with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile:
- json.dump(theJSON, outfile)
- | Convert OMDB scrapper to grab xml | ## Code Before:
import json, requests, sys, os
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
theJSON = json.loads(response.text)
# Save the JSON file
with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile:
json.dump(theJSON, outfile)
## Instruction:
Convert OMDB scrapper to grab xml
## Code After:
import requests, sys, os
import lxml.etree
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml'
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
# Save the XML file
with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile:
outfile.write(response.text)
|
- import json, requests, sys, os
? ------
+ import requests, sys, os
+ import lxml.etree
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the URL
- url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json'
? ^^^^
+ url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=xml'
? ^^^
# Try to get the url
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as err:
print(err)
sys.exit(1)
- theJSON = json.loads(response.text)
-
- # Save the JSON file
? ^^^^
+ # Save the XML file
? ^^^
- with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.json'))), 'w') as outfile:
? ^^^^
+ with open((os.path.join(os.getcwd(), (mTitle + '_' + mYear + '.xml'))), 'wb') as outfile:
? ^^^ +
- json.dump(theJSON, outfile)
+ outfile.write(response.text) |
2bcc941b015c443c64f08a13012e8caf70028754 | ideascube/search/migrations/0001_initial.py | ideascube/search/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
import ideascube.search.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Search',
fields=[
('rowid', models.IntegerField(serialize=False, primary_key=True)),
('model', models.CharField(max_length=64)),
('model_id', models.IntegerField()),
('public', models.BooleanField(default=True)),
('text', ideascube.search.models.SearchField()),
],
options={
'db_table': 'idx',
'managed': False,
},
),
]
| from __future__ import unicode_literals
from django.db import migrations
from ideascube.search.utils import create_index_table
class CreateSearchModel(migrations.CreateModel):
def database_forwards(self, *_):
# Don't run the parent method, we create the table our own way
create_index_table()
class Migration(migrations.Migration):
dependencies = [
]
operations = [
CreateSearchModel(
name='Search',
fields=[],
options={
'db_table': 'idx',
'managed': False,
},
),
]
| Fix the initial search migration | Fix the initial search migration
There is no point in creating the model in this way, that's just not how
it's used: instead we want to use the FTS4 extension from SQLite.
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | from __future__ import unicode_literals
- from django.db import migrations, models
+ from django.db import migrations
- import ideascube.search.models
+ from ideascube.search.utils import create_index_table
+
+
+ class CreateSearchModel(migrations.CreateModel):
+ def database_forwards(self, *_):
+ # Don't run the parent method, we create the table our own way
+ create_index_table()
class Migration(migrations.Migration):
dependencies = [
]
operations = [
- migrations.CreateModel(
+ CreateSearchModel(
name='Search',
- fields=[
+ fields=[],
- ('rowid', models.IntegerField(serialize=False, primary_key=True)),
- ('model', models.CharField(max_length=64)),
- ('model_id', models.IntegerField()),
- ('public', models.BooleanField(default=True)),
- ('text', ideascube.search.models.SearchField()),
- ],
options={
'db_table': 'idx',
'managed': False,
},
),
]
| Fix the initial search migration | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
import ideascube.search.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Search',
fields=[
('rowid', models.IntegerField(serialize=False, primary_key=True)),
('model', models.CharField(max_length=64)),
('model_id', models.IntegerField()),
('public', models.BooleanField(default=True)),
('text', ideascube.search.models.SearchField()),
],
options={
'db_table': 'idx',
'managed': False,
},
),
]
## Instruction:
Fix the initial search migration
## Code After:
from __future__ import unicode_literals
from django.db import migrations
from ideascube.search.utils import create_index_table
class CreateSearchModel(migrations.CreateModel):
def database_forwards(self, *_):
# Don't run the parent method, we create the table our own way
create_index_table()
class Migration(migrations.Migration):
dependencies = [
]
operations = [
CreateSearchModel(
name='Search',
fields=[],
options={
'db_table': 'idx',
'managed': False,
},
),
]
| from __future__ import unicode_literals
- from django.db import migrations, models
? --------
+ from django.db import migrations
- import ideascube.search.models
+ from ideascube.search.utils import create_index_table
+
+
+ class CreateSearchModel(migrations.CreateModel):
+ def database_forwards(self, *_):
+ # Don't run the parent method, we create the table our own way
+ create_index_table()
class Migration(migrations.Migration):
dependencies = [
]
operations = [
- migrations.CreateModel(
+ CreateSearchModel(
name='Search',
- fields=[
+ fields=[],
? ++
- ('rowid', models.IntegerField(serialize=False, primary_key=True)),
- ('model', models.CharField(max_length=64)),
- ('model_id', models.IntegerField()),
- ('public', models.BooleanField(default=True)),
- ('text', ideascube.search.models.SearchField()),
- ],
options={
'db_table': 'idx',
'managed': False,
},
),
] |
49a7968e51ce850428936fb2fc66c905ce8b8998 | head1stpython/Chapter3/sketch.py | head1stpython/Chapter3/sketch.py | import os
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Change path for the current directory
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end = '')
print(' said: ', end = '')
print(line_spoken, end = '')
except:
pass
data.close()
| import os
#Change path for the current directory
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Check if file exists
if os.path.exists('sketch.txt'):
#Load the text file into 'data' variable
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
#We use try/except to handle errors that can occur with bad input
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end = '')
print(' said: ', end = '')
print(line_spoken, end = '')
except:
pass
#After all the iteration and printing, we close the file
data.close()
#If file does exists, we simply quit and display an error for the user/dev
else:
print('The data file is missing!')
| Validate if the file exists (if/else) | Validate if the file exists (if/else)
| Python | unlicense | israelzuniga/python-octo-wookie | import os
+ #Change path for the current directory
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
- #Change path for the current directory
+ #Check if file exists
+ if os.path.exists('sketch.txt'):
+
+ #Load the text file into 'data' variable
- data = open('sketch.txt')
+ data = open('sketch.txt')
+ #Start iteration over the text file
+ for each_line in data:
+ #We use try/except to handle errors that can occur with bad input
+ try:
+ (role, line_spoken) = each_line.split(':', 1)
+ print(role, end = '')
+ print(' said: ', end = '')
+ print(line_spoken, end = '')
+ except:
+ pass
+ #After all the iteration and printing, we close the file
+ data.close()
- #Start iteration over the text file
- for each_line in data:
- try:
- (role, line_spoken) = each_line.split(':', 1)
- print(role, end = '')
- print(' said: ', end = '')
- print(line_spoken, end = '')
- except:
- pass
- data.close()
+ #If file does exists, we simply quit and display an error for the user/dev
+ else:
+ print('The data file is missing!')
| Validate if the file exists (if/else) | ## Code Before:
import os
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Change path for the current directory
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end = '')
print(' said: ', end = '')
print(line_spoken, end = '')
except:
pass
data.close()
## Instruction:
Validate if the file exists (if/else)
## Code After:
import os
#Change path for the current directory
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
#Check if file exists
if os.path.exists('sketch.txt'):
#Load the text file into 'data' variable
data = open('sketch.txt')
#Start iteration over the text file
for each_line in data:
#We use try/except to handle errors that can occur with bad input
try:
(role, line_spoken) = each_line.split(':', 1)
print(role, end = '')
print(' said: ', end = '')
print(line_spoken, end = '')
except:
pass
#After all the iteration and printing, we close the file
data.close()
#If file does exists, we simply quit and display an error for the user/dev
else:
print('The data file is missing!')
| import os
+ #Change path for the current directory
os.chdir('/home/israel/Development/Python_Exercises/python-octo-wookie/head1stpython/Chapter3')
- #Change path for the current directory
+ #Check if file exists
+ if os.path.exists('sketch.txt'):
+
+ #Load the text file into 'data' variable
- data = open('sketch.txt')
+ data = open('sketch.txt')
? ++++
+ #Start iteration over the text file
+ for each_line in data:
+ #We use try/except to handle errors that can occur with bad input
+ try:
+ (role, line_spoken) = each_line.split(':', 1)
+ print(role, end = '')
+ print(' said: ', end = '')
+ print(line_spoken, end = '')
+ except:
+ pass
+ #After all the iteration and printing, we close the file
+ data.close()
- #Start iteration over the text file
- for each_line in data:
- try:
- (role, line_spoken) = each_line.split(':', 1)
- print(role, end = '')
- print(' said: ', end = '')
- print(line_spoken, end = '')
- except:
- pass
- data.close()
+ #If file does exists, we simply quit and display an error for the user/dev
+ else:
+ print('The data file is missing!')
|
22e16ba6e2bf7135933895162744424e89ca514d | article/tests/article_admin_tests.py | article/tests/article_admin_tests.py | from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', 'pari@test.com', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
def test_article_cannot_be_stored_without_content(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', content='')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
| from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', 'pari@test.com', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
def test_article_can_be_stored_without_content(self):
article = ArticleFactory(title='Test', content='')
self.assertEqual(article.title, 'Test')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
| Fix test for storing article without any content | Fix test for storing article without any content
| Python | bsd-3-clause | PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari | from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', 'pari@test.com', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
- def test_article_cannot_be_stored_without_content(self):
+ def test_article_can_be_stored_without_content(self):
- with self.assertRaisesRegexp(ValidationError,
- "This field cannot be blank"):
- ArticleFactory(title='Test', content='')
+ article = ArticleFactory(title='Test', content='')
+ self.assertEqual(article.title, 'Test')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
| Fix test for storing article without any content | ## Code Before:
from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', 'pari@test.com', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
def test_article_cannot_be_stored_without_content(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', content='')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
## Instruction:
Fix test for storing article without any content
## Code After:
from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', 'pari@test.com', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
def test_article_can_be_stored_without_content(self):
article = ArticleFactory(title='Test', content='')
self.assertEqual(article.title, 'Test')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='')
| from django.contrib.auth.models import User
from django.test import TestCase, override_settings, Client
from django.test import RequestFactory
from mock import MagicMock
from wagtail.wagtailsearch.backends.elasticsearch import Elasticsearch
from django.db import DataError, IntegrityError
from django.core.exceptions import ValidationError
from article.models import Article
from functional_tests.factory import ArticleFactory, AuthorFactory
class ArticleAdminFormTest(TestCase):
def setUp(self):
self.client = Client()
self.test_author = AuthorFactory(name='xyz', slug="xyz")
self.article = ArticleFactory(title="english_article", authors=(self.test_author,), language='en')
def login_admin(self):
User.objects.create_superuser('pari', 'pari@test.com', "pari")
self.client.login(username="pari", password="pari")
def test_no_article_can_be_stored_without_a_title(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"): # Slug and title fields cannot be null.
ArticleFactory(title="")
- def test_article_cannot_be_stored_without_content(self):
? ---
+ def test_article_can_be_stored_without_content(self):
- with self.assertRaisesRegexp(ValidationError,
- "This field cannot be blank"):
- ArticleFactory(title='Test', content='')
? ^^
+ article = ArticleFactory(title='Test', content='')
? +++++++ ^
+ self.assertEqual(article.title, 'Test')
def test_article_cannot_be_stored_without_language(self):
with self.assertRaisesRegexp(ValidationError,
"This field cannot be blank"):
ArticleFactory(title='Test', language='') |
e9a5bbd1eba1cdad15626a712bfc7994008c7381 | byceps/blueprints/snippet/init.py | byceps/blueprints/snippet/init.py |
from flask import current_app
from ...services.snippet import mountpoint_service
from .views import blueprint as snippet_blueprint, view_current_version_by_name
def add_routes_for_snippets(site_id):
"""Register routes for snippets with the application."""
mountpoints = mountpoint_service.get_mountpoints_for_site(site_id)
for mountpoint in mountpoints:
add_route_for_snippet(mountpoint)
def add_route_for_snippet(mountpoint):
"""Register a route for the snippet."""
endpoint = '{}.{}'.format(snippet_blueprint.name,
mountpoint.endpoint_suffix)
defaults = {'name': mountpoint.snippet.name}
current_app.add_url_rule(
mountpoint.url_path,
endpoint,
view_func=view_current_version_by_name,
defaults=defaults)
|
from flask import current_app
from ...services.snippet import mountpoint_service
from .views import blueprint as snippet_blueprint, view_current_version_by_name
def add_routes_for_snippets(site_id):
"""Register routes for snippets with the application."""
mountpoints = mountpoint_service.get_mountpoints_for_site(site_id)
for mountpoint in mountpoints:
add_route_for_snippet(mountpoint)
def add_route_for_snippet(mountpoint):
"""Register a route for the snippet."""
endpoint = '{}.{}'.format(snippet_blueprint.name,
mountpoint.endpoint_suffix)
defaults = {'name': mountpoint.endpoint_suffix}
current_app.add_url_rule(
mountpoint.url_path,
endpoint,
view_func=view_current_version_by_name,
defaults=defaults)
| Fix snippet URL rules to use mountpoints' endpoint suffix | Fix snippet URL rules to use mountpoints' endpoint suffix
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps |
from flask import current_app
from ...services.snippet import mountpoint_service
from .views import blueprint as snippet_blueprint, view_current_version_by_name
def add_routes_for_snippets(site_id):
"""Register routes for snippets with the application."""
mountpoints = mountpoint_service.get_mountpoints_for_site(site_id)
for mountpoint in mountpoints:
add_route_for_snippet(mountpoint)
def add_route_for_snippet(mountpoint):
"""Register a route for the snippet."""
endpoint = '{}.{}'.format(snippet_blueprint.name,
mountpoint.endpoint_suffix)
- defaults = {'name': mountpoint.snippet.name}
+ defaults = {'name': mountpoint.endpoint_suffix}
current_app.add_url_rule(
mountpoint.url_path,
endpoint,
view_func=view_current_version_by_name,
defaults=defaults)
| Fix snippet URL rules to use mountpoints' endpoint suffix | ## Code Before:
from flask import current_app
from ...services.snippet import mountpoint_service
from .views import blueprint as snippet_blueprint, view_current_version_by_name
def add_routes_for_snippets(site_id):
"""Register routes for snippets with the application."""
mountpoints = mountpoint_service.get_mountpoints_for_site(site_id)
for mountpoint in mountpoints:
add_route_for_snippet(mountpoint)
def add_route_for_snippet(mountpoint):
"""Register a route for the snippet."""
endpoint = '{}.{}'.format(snippet_blueprint.name,
mountpoint.endpoint_suffix)
defaults = {'name': mountpoint.snippet.name}
current_app.add_url_rule(
mountpoint.url_path,
endpoint,
view_func=view_current_version_by_name,
defaults=defaults)
## Instruction:
Fix snippet URL rules to use mountpoints' endpoint suffix
## Code After:
from flask import current_app
from ...services.snippet import mountpoint_service
from .views import blueprint as snippet_blueprint, view_current_version_by_name
def add_routes_for_snippets(site_id):
"""Register routes for snippets with the application."""
mountpoints = mountpoint_service.get_mountpoints_for_site(site_id)
for mountpoint in mountpoints:
add_route_for_snippet(mountpoint)
def add_route_for_snippet(mountpoint):
"""Register a route for the snippet."""
endpoint = '{}.{}'.format(snippet_blueprint.name,
mountpoint.endpoint_suffix)
defaults = {'name': mountpoint.endpoint_suffix}
current_app.add_url_rule(
mountpoint.url_path,
endpoint,
view_func=view_current_version_by_name,
defaults=defaults)
|
from flask import current_app
from ...services.snippet import mountpoint_service
from .views import blueprint as snippet_blueprint, view_current_version_by_name
def add_routes_for_snippets(site_id):
"""Register routes for snippets with the application."""
mountpoints = mountpoint_service.get_mountpoints_for_site(site_id)
for mountpoint in mountpoints:
add_route_for_snippet(mountpoint)
def add_route_for_snippet(mountpoint):
"""Register a route for the snippet."""
endpoint = '{}.{}'.format(snippet_blueprint.name,
mountpoint.endpoint_suffix)
- defaults = {'name': mountpoint.snippet.name}
? ^ ^^^^^^^^^
+ defaults = {'name': mountpoint.endpoint_suffix}
? +++++++++ ^^^ ^
current_app.add_url_rule(
mountpoint.url_path,
endpoint,
view_func=view_current_version_by_name,
defaults=defaults) |
fa991297168f216c208d53b880124a4f23250034 | setup.py | setup.py | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
| import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"gzip",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
| Add gzip to cx-freeze packages | Add gzip to cx-freeze packages
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
+ "gzip",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
| Add gzip to cx-freeze packages | ## Code Before:
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
## Instruction:
Add gzip to cx-freeze packages
## Code After:
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
"gzip",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
| import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("client/dist", "client"),
"LICENSE",
"templates",
"readme.md",
(backend_path, "lib/.libs_cffi_backend")
],
"includes": [
"cffi",
"numpy",
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format",
"raven.processors"
],
"packages": [
"_cffi_backend",
"appdirs",
"asyncio",
"bcrypt",
"cffi",
+ "gzip",
"idna",
"motor",
"packaging",
"ssl",
"uvloop"
]
}
options = {
"build_exe": build_exe_options
}
executables = [
Executable('run.py', base="Console")
]
classifiers=[
"Programming Language :: Python :: 3.7"
]
importlib.import_module("virtool")
setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
|
8095c37e0ab99e9827acbe4621f2fcb9334e1426 | games/management/commands/autocreate_steamdb_installers.py | games/management/commands/autocreate_steamdb_installers.py | import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = models.Runner.objects.get(slug='steam')
user = User.objects.get(username='strider')
for steamapp in steamdb:
if steamapp['linux_status'] == 'Game Works':
appid = steamapp['appid']
name = steamapp['name']
try:
game = models.Game.objects.get(steamid=int(appid))
except models.Game.DoesNotExist:
continue
current_installer = game.installer_set.all()
if current_installer:
continue
self.stdout.write("Creating installer for %s" % name)
installer = models.Installer()
installer.runner = steam_runner
installer.user = user
installer.game = game
installer.set_default_installer()
installer.published = True
installer.save()
| import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = models.Runner.objects.get(slug='steam')
user = User.objects.get(username='strider')
for steamapp in steamdb:
if steamapp['linux_status'].startswith('Game Works'):
appid = steamapp['appid']
name = steamapp['name']
try:
game = models.Game.objects.get(steamid=int(appid))
except models.Game.DoesNotExist:
continue
current_installer = game.installer_set.all()
if current_installer:
continue
self.stdout.write("Creating installer for %s" % name)
installer = models.Installer()
installer.runner = steam_runner
installer.user = user
installer.game = game
installer.set_default_installer()
installer.published = True
installer.save()
| Update installer autocreate for games with no icon | Update installer autocreate for games with no icon
| Python | agpl-3.0 | Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website,lutris/website,lutris/website,Turupawn/website | import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = models.Runner.objects.get(slug='steam')
user = User.objects.get(username='strider')
for steamapp in steamdb:
- if steamapp['linux_status'] == 'Game Works':
+ if steamapp['linux_status'].startswith('Game Works'):
appid = steamapp['appid']
name = steamapp['name']
try:
game = models.Game.objects.get(steamid=int(appid))
except models.Game.DoesNotExist:
continue
current_installer = game.installer_set.all()
if current_installer:
continue
self.stdout.write("Creating installer for %s" % name)
installer = models.Installer()
installer.runner = steam_runner
installer.user = user
installer.game = game
installer.set_default_installer()
installer.published = True
installer.save()
| Update installer autocreate for games with no icon | ## Code Before:
import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = models.Runner.objects.get(slug='steam')
user = User.objects.get(username='strider')
for steamapp in steamdb:
if steamapp['linux_status'] == 'Game Works':
appid = steamapp['appid']
name = steamapp['name']
try:
game = models.Game.objects.get(steamid=int(appid))
except models.Game.DoesNotExist:
continue
current_installer = game.installer_set.all()
if current_installer:
continue
self.stdout.write("Creating installer for %s" % name)
installer = models.Installer()
installer.runner = steam_runner
installer.user = user
installer.game = game
installer.set_default_installer()
installer.published = True
installer.save()
## Instruction:
Update installer autocreate for games with no icon
## Code After:
import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = models.Runner.objects.get(slug='steam')
user = User.objects.get(username='strider')
for steamapp in steamdb:
if steamapp['linux_status'].startswith('Game Works'):
appid = steamapp['appid']
name = steamapp['name']
try:
game = models.Game.objects.get(steamid=int(appid))
except models.Game.DoesNotExist:
continue
current_installer = game.installer_set.all()
if current_installer:
continue
self.stdout.write("Creating installer for %s" % name)
installer = models.Installer()
installer.runner = steam_runner
installer.user = user
installer.game = game
installer.set_default_installer()
installer.published = True
installer.save()
| import json
from django.core.management.base import BaseCommand
from games import models
from accounts.models import User
class Command(BaseCommand):
def handle(self, *args, **options):
with open("steamdb.json") as steamdb_file:
steamdb = json.loads(steamdb_file.read())
steam_runner = models.Runner.objects.get(slug='steam')
user = User.objects.get(username='strider')
for steamapp in steamdb:
- if steamapp['linux_status'] == 'Game Works':
? ^^^^
+ if steamapp['linux_status'].startswith('Game Works'):
? ^^^^^^^^^^^^ +
appid = steamapp['appid']
name = steamapp['name']
try:
game = models.Game.objects.get(steamid=int(appid))
except models.Game.DoesNotExist:
continue
current_installer = game.installer_set.all()
if current_installer:
continue
self.stdout.write("Creating installer for %s" % name)
installer = models.Installer()
installer.runner = steam_runner
installer.user = user
installer.game = game
installer.set_default_installer()
installer.published = True
installer.save() |
1843e34bba0343cd3600f3c8934ae29b4b365554 | chstrings/chstrings_test.py | chstrings/chstrings_test.py | import chstrings
import config
import unittest
class CHStringsTest(unittest.TestCase):
@classmethod
def add_smoke_test(cls, cfg):
def test(self):
# We just want to see if this will blow up
chstrings.get_localized_strings(cfg, cfg.lang_code)
name = 'test_' + cfg.lang_code + '_smoke_test'
setattr(cls, name, test)
if __name__ == '__main__':
for lc in config.LANG_CODES_TO_LANG_NAMES:
cfg = config.get_localized_config(lc)
CHStringsTest.add_smoke_test(cfg)
unittest.main()
| import chstrings
import config
import unittest
class CHStringsTest(unittest.TestCase):
@classmethod
def add_smoke_test(cls, cfg):
def test(self):
# We just want to see if this will blow up. Use the fallback
# lang_tag across all tests.
lang_tag = cfg.lang_code
if cfg.accept_language:
lang_tag = cfg.accept_language[-1]
self.assertNotEqual({},
chstrings.get_localized_strings(cfg, lang_tag))
name = 'test_' + cfg.lang_code + '_smoke_test'
setattr(cls, name, test)
if __name__ == '__main__':
for lc in config.LANG_CODES_TO_LANG_NAMES:
cfg = config.get_localized_config(lc)
CHStringsTest.add_smoke_test(cfg)
unittest.main()
| Extend chstrings smoke test a little more. | Extend chstrings smoke test a little more.
| Python | mit | eggpi/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt | import chstrings
import config
import unittest
class CHStringsTest(unittest.TestCase):
@classmethod
def add_smoke_test(cls, cfg):
def test(self):
- # We just want to see if this will blow up
+ # We just want to see if this will blow up. Use the fallback
+ # lang_tag across all tests.
+ lang_tag = cfg.lang_code
+ if cfg.accept_language:
+ lang_tag = cfg.accept_language[-1]
+ self.assertNotEqual({},
- chstrings.get_localized_strings(cfg, cfg.lang_code)
+ chstrings.get_localized_strings(cfg, lang_tag))
name = 'test_' + cfg.lang_code + '_smoke_test'
setattr(cls, name, test)
if __name__ == '__main__':
for lc in config.LANG_CODES_TO_LANG_NAMES:
cfg = config.get_localized_config(lc)
CHStringsTest.add_smoke_test(cfg)
unittest.main()
| Extend chstrings smoke test a little more. | ## Code Before:
import chstrings
import config
import unittest
class CHStringsTest(unittest.TestCase):
@classmethod
def add_smoke_test(cls, cfg):
def test(self):
# We just want to see if this will blow up
chstrings.get_localized_strings(cfg, cfg.lang_code)
name = 'test_' + cfg.lang_code + '_smoke_test'
setattr(cls, name, test)
if __name__ == '__main__':
for lc in config.LANG_CODES_TO_LANG_NAMES:
cfg = config.get_localized_config(lc)
CHStringsTest.add_smoke_test(cfg)
unittest.main()
## Instruction:
Extend chstrings smoke test a little more.
## Code After:
import chstrings
import config
import unittest
class CHStringsTest(unittest.TestCase):
@classmethod
def add_smoke_test(cls, cfg):
def test(self):
# We just want to see if this will blow up. Use the fallback
# lang_tag across all tests.
lang_tag = cfg.lang_code
if cfg.accept_language:
lang_tag = cfg.accept_language[-1]
self.assertNotEqual({},
chstrings.get_localized_strings(cfg, lang_tag))
name = 'test_' + cfg.lang_code + '_smoke_test'
setattr(cls, name, test)
if __name__ == '__main__':
for lc in config.LANG_CODES_TO_LANG_NAMES:
cfg = config.get_localized_config(lc)
CHStringsTest.add_smoke_test(cfg)
unittest.main()
| import chstrings
import config
import unittest
class CHStringsTest(unittest.TestCase):
@classmethod
def add_smoke_test(cls, cfg):
def test(self):
- # We just want to see if this will blow up
+ # We just want to see if this will blow up. Use the fallback
? ++++++++++++++++++
+ # lang_tag across all tests.
+ lang_tag = cfg.lang_code
+ if cfg.accept_language:
+ lang_tag = cfg.accept_language[-1]
+ self.assertNotEqual({},
- chstrings.get_localized_strings(cfg, cfg.lang_code)
? ---- ^^^^
+ chstrings.get_localized_strings(cfg, lang_tag))
? ++++ ^^^ +
name = 'test_' + cfg.lang_code + '_smoke_test'
setattr(cls, name, test)
if __name__ == '__main__':
for lc in config.LANG_CODES_TO_LANG_NAMES:
cfg = config.get_localized_config(lc)
CHStringsTest.add_smoke_test(cfg)
unittest.main() |
620bf504292583b2547cf7489eeeaaa582ddad77 | indra/tests/test_ctd.py | indra/tests/test_ctd.py | import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 4, cp.statements
| import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 3, cp.statements
assert isinstance(cp.statements[0], Dephosphorylation)
assert cp.statements[0].enz.name == 'wortmannin'
assert isinstance(cp.statements[1], Dephosphorylation)
assert cp.statements[1].enz.name == 'YM-254890'
assert isinstance(cp.statements[2], Phosphorylation)
assert cp.statements[2].enz.name == 'zinc atom'
| Fix and extend test conditions | Fix and extend test conditions
| Python | bsd-2-clause | sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra,bgyori/indra,sorgerlab/belpy | import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
- assert len(cp.statements) == 4, cp.statements
+ assert len(cp.statements) == 3, cp.statements
+ assert isinstance(cp.statements[0], Dephosphorylation)
+ assert cp.statements[0].enz.name == 'wortmannin'
+ assert isinstance(cp.statements[1], Dephosphorylation)
+ assert cp.statements[1].enz.name == 'YM-254890'
+ assert isinstance(cp.statements[2], Phosphorylation)
+ assert cp.statements[2].enz.name == 'zinc atom'
| Fix and extend test conditions | ## Code Before:
import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 4, cp.statements
## Instruction:
Fix and extend test conditions
## Code After:
import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 3, cp.statements
assert isinstance(cp.statements[0], Dephosphorylation)
assert cp.statements[0].enz.name == 'wortmannin'
assert isinstance(cp.statements[1], Dephosphorylation)
assert cp.statements[1].enz.name == 'YM-254890'
assert isinstance(cp.statements[2], Phosphorylation)
assert cp.statements[2].enz.name == 'zinc atom'
| import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
- assert len(cp.statements) == 4, cp.statements
? ^
+ assert len(cp.statements) == 3, cp.statements
? ^
+ assert isinstance(cp.statements[0], Dephosphorylation)
+ assert cp.statements[0].enz.name == 'wortmannin'
+ assert isinstance(cp.statements[1], Dephosphorylation)
+ assert cp.statements[1].enz.name == 'YM-254890'
+ assert isinstance(cp.statements[2], Phosphorylation)
+ assert cp.statements[2].enz.name == 'zinc atom' |
c87b5f8392dc58d6fa1d5398245b4ffe9edb19c8 | praw/models/mod_action.py | praw/models/mod_action.py | """Provide the ModAction class."""
from typing import TYPE_CHECKING
from .base import PRAWBase
if TYPE_CHECKING: # pragma: no cover
from ... import praw
class ModAction(PRAWBase):
"""Represent a moderator action."""
@property
def mod(self) -> "praw.models.Redditor":
"""Return the :class:`.Redditor` who the action was issued by."""
return self._reddit.redditor(self._mod) # pylint: disable=no-member
@mod.setter
def mod(self, value: "praw.models.Redditor"):
self._mod = value # pylint: disable=attribute-defined-outside-init
| """Provide the ModAction class."""
from typing import TYPE_CHECKING, Union
from .base import PRAWBase
if TYPE_CHECKING: # pragma: no cover
from ... import praw
class ModAction(PRAWBase):
"""Represent a moderator action."""
@property
def mod(self) -> "praw.models.Redditor":
"""Return the :class:`.Redditor` who the action was issued by."""
return self._reddit.redditor(self._mod) # pylint: disable=no-member
@mod.setter
def mod(self, value: Union[str, "praw.models.Redditor"]):
self._mod = value # pylint: disable=attribute-defined-outside-init
| Add str as a type for mod setter | Add str as a type for mod setter
| Python | bsd-2-clause | praw-dev/praw,praw-dev/praw | """Provide the ModAction class."""
- from typing import TYPE_CHECKING
+ from typing import TYPE_CHECKING, Union
from .base import PRAWBase
if TYPE_CHECKING: # pragma: no cover
from ... import praw
class ModAction(PRAWBase):
"""Represent a moderator action."""
@property
def mod(self) -> "praw.models.Redditor":
"""Return the :class:`.Redditor` who the action was issued by."""
return self._reddit.redditor(self._mod) # pylint: disable=no-member
@mod.setter
- def mod(self, value: "praw.models.Redditor"):
+ def mod(self, value: Union[str, "praw.models.Redditor"]):
self._mod = value # pylint: disable=attribute-defined-outside-init
| Add str as a type for mod setter | ## Code Before:
"""Provide the ModAction class."""
from typing import TYPE_CHECKING
from .base import PRAWBase
if TYPE_CHECKING: # pragma: no cover
from ... import praw
class ModAction(PRAWBase):
"""Represent a moderator action."""
@property
def mod(self) -> "praw.models.Redditor":
"""Return the :class:`.Redditor` who the action was issued by."""
return self._reddit.redditor(self._mod) # pylint: disable=no-member
@mod.setter
def mod(self, value: "praw.models.Redditor"):
self._mod = value # pylint: disable=attribute-defined-outside-init
## Instruction:
Add str as a type for mod setter
## Code After:
"""Provide the ModAction class."""
from typing import TYPE_CHECKING, Union
from .base import PRAWBase
if TYPE_CHECKING: # pragma: no cover
from ... import praw
class ModAction(PRAWBase):
"""Represent a moderator action."""
@property
def mod(self) -> "praw.models.Redditor":
"""Return the :class:`.Redditor` who the action was issued by."""
return self._reddit.redditor(self._mod) # pylint: disable=no-member
@mod.setter
def mod(self, value: Union[str, "praw.models.Redditor"]):
self._mod = value # pylint: disable=attribute-defined-outside-init
| """Provide the ModAction class."""
- from typing import TYPE_CHECKING
+ from typing import TYPE_CHECKING, Union
? +++++++
from .base import PRAWBase
if TYPE_CHECKING: # pragma: no cover
from ... import praw
class ModAction(PRAWBase):
"""Represent a moderator action."""
@property
def mod(self) -> "praw.models.Redditor":
"""Return the :class:`.Redditor` who the action was issued by."""
return self._reddit.redditor(self._mod) # pylint: disable=no-member
@mod.setter
- def mod(self, value: "praw.models.Redditor"):
+ def mod(self, value: Union[str, "praw.models.Redditor"]):
? +++++++++++ +
self._mod = value # pylint: disable=attribute-defined-outside-init |
c28ae7e4b0637a2c4db120d9add13d5589ddca40 | runtests.py | runtests.py | import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
try:
django.setup()
except AttributeError: # 1.6 or lower
pass
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
| import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
| Remove compat shim as it doesn't apply | Remove compat shim as it doesn't apply
| Python | mit | sergei-maertens/django-systemjs,sergei-maertens/django-systemjs,sergei-maertens/django-systemjs,sergei-maertens/django-systemjs | import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
- try:
- django.setup()
+ django.setup()
- except AttributeError: # 1.6 or lower
- pass
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
| Remove compat shim as it doesn't apply | ## Code Before:
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
try:
django.setup()
except AttributeError: # 1.6 or lower
pass
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
## Instruction:
Remove compat shim as it doesn't apply
## Code After:
import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests()
| import os
import sys
def runtests():
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
from django.test.utils import get_runner
from django.conf import settings
- try:
- django.setup()
? ----
+ django.setup()
- except AttributeError: # 1.6 or lower
- pass
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['.'])
sys.exit(failures)
if __name__ == '__main__':
runtests() |
fc25a6c4796ad008570974a682037bc575f15018 | astroquery/lamda/tests/test_lamda.py | astroquery/lamda/tests/test_lamda.py | from ... import lamda
def test_query():
Q = lamda.core.LAMDAQuery()
Q.lamda_query(mol='co', query_type='erg_levels')
Q.lamda_query(mol='co', query_type='rad_trans')
Q.lamda_query(mol='co', query_type='coll_rates')
| from ... import lamda
def test_query():
lamda.print_mols()
lamda.query(mol='co', query_type='erg_levels')
lamda.query(mol='co', query_type='rad_trans')
lamda.query(mol='co', query_type='coll_rates', coll_partner_index=1)
| Update tests for new style | Update tests for new style
Also added test for printing molecule list and made the collisional rate
test more complicated.
| Python | bsd-3-clause | imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery | from ... import lamda
def test_query():
- Q = lamda.core.LAMDAQuery()
+ lamda.print_mols()
- Q.lamda_query(mol='co', query_type='erg_levels')
+ lamda.query(mol='co', query_type='erg_levels')
- Q.lamda_query(mol='co', query_type='rad_trans')
+ lamda.query(mol='co', query_type='rad_trans')
- Q.lamda_query(mol='co', query_type='coll_rates')
+ lamda.query(mol='co', query_type='coll_rates', coll_partner_index=1)
| Update tests for new style | ## Code Before:
from ... import lamda
def test_query():
Q = lamda.core.LAMDAQuery()
Q.lamda_query(mol='co', query_type='erg_levels')
Q.lamda_query(mol='co', query_type='rad_trans')
Q.lamda_query(mol='co', query_type='coll_rates')
## Instruction:
Update tests for new style
## Code After:
from ... import lamda
def test_query():
lamda.print_mols()
lamda.query(mol='co', query_type='erg_levels')
lamda.query(mol='co', query_type='rad_trans')
lamda.query(mol='co', query_type='coll_rates', coll_partner_index=1)
| from ... import lamda
def test_query():
- Q = lamda.core.LAMDAQuery()
+ lamda.print_mols()
- Q.lamda_query(mol='co', query_type='erg_levels')
? -- ^
+ lamda.query(mol='co', query_type='erg_levels')
? ^
- Q.lamda_query(mol='co', query_type='rad_trans')
? -- ^
+ lamda.query(mol='co', query_type='rad_trans')
? ^
- Q.lamda_query(mol='co', query_type='coll_rates')
? -- ^
+ lamda.query(mol='co', query_type='coll_rates', coll_partner_index=1)
? ^ ++++++++++++++++++++++
|
ffe9bba2e4045236a3f3731e39876b6220f8f9a1 | jarviscli/plugins/joke_of_day.py | jarviscli/plugins/joke_of_day.py | from plugin import plugin, require
import requests
from colorama import Fore
from plugins.animations import SpinnerThread
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
spinner = SpinnerThread('Fetching ', 0.15)
while True:
url = "https://api.jokes.one/jod"
spinner.start()
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
spinner.stop()
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW)
| from plugin import plugin, require
import requests
from colorama import Fore
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
while True:
url = "https://api.jokes.one/jod"
jarvis.spinner_start('Fetching')
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
jarvis.spinner_stop()
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW)
| Update joke of day: Fix for moved SpinnerThread | Update joke of day: Fix for moved SpinnerThread
| Python | mit | sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis | from plugin import plugin, require
import requests
from colorama import Fore
- from plugins.animations import SpinnerThread
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
- spinner = SpinnerThread('Fetching ', 0.15)
while True:
url = "https://api.jokes.one/jod"
- spinner.start()
+ jarvis.spinner_start('Fetching')
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
- spinner.stop()
+ jarvis.spinner_stop()
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW)
| Update joke of day: Fix for moved SpinnerThread | ## Code Before:
from plugin import plugin, require
import requests
from colorama import Fore
from plugins.animations import SpinnerThread
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
spinner = SpinnerThread('Fetching ', 0.15)
while True:
url = "https://api.jokes.one/jod"
spinner.start()
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
spinner.stop()
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW)
## Instruction:
Update joke of day: Fix for moved SpinnerThread
## Code After:
from plugin import plugin, require
import requests
from colorama import Fore
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
while True:
url = "https://api.jokes.one/jod"
jarvis.spinner_start('Fetching')
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
jarvis.spinner_stop()
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW)
| from plugin import plugin, require
import requests
from colorama import Fore
- from plugins.animations import SpinnerThread
@require(network=True)
@plugin('joke daily')
class joke_of_day:
"""
Provides you with a joke of day to help you laugh amidst the
daily boring schedule
Enter 'joke daily' to use
"""
def __call__(self, jarvis, s):
jarvis.say("Welcome To The Plugin Joke Of Day!", Fore.CYAN)
jarvis.say("Jokes provided by jokes.one API", Fore.CYAN, False)
print()
joke_fetch = self.get_joke(jarvis)
if joke_fetch is not None:
self.joke(jarvis, joke_fetch)
def get_joke(self, jarvis):
- spinner = SpinnerThread('Fetching ', 0.15)
while True:
url = "https://api.jokes.one/jod"
- spinner.start()
+ jarvis.spinner_start('Fetching')
r = requests.get(url)
if r is None:
spinner.stop()
jarvis.say(
"Error in fetching joke - try again! later", Fore.RED)
- spinner.stop()
? ^
+ jarvis.spinner_stop()
? +++++++ ^
return r.json()
def joke(self, jarvis, joke_fetch):
title = joke_fetch["contents"]["jokes"][0]["joke"]["title"]
joke = joke_fetch["contents"]["jokes"][0]["joke"]["text"]
print()
jarvis.say("Title: " + title, Fore.BLUE)
print()
jarvis.say(joke, Fore.YELLOW) |
7eb580d11dc8506cf656021d12884562d1a1b823 | dumper/site.py | dumper/site.py | from six import string_types
from django.db.models import signals
from .invalidation import invalidate_paths
def register(model):
register_instance_function_at_save(model, invalidate_model_paths)
def register_instance_function_at_save(model, function):
def save_function(sender, instance, **kwargs):
function(instance)
signals.post_save.connect(save_function, model, weak=False)
signals.pre_delete.connect(save_function, model, weak=False)
def get_paths_from_model(model):
paths = model.dependent_paths()
if isinstance(paths, string_types):
model_name = model.__class__.__name__
raise TypeError(
('dependent_paths on {} should return a list of paths, not a'
'string'.format(model_name))
)
return paths
def invalidate_model_paths(model):
paths = get_paths_from_model(model)
invalidate_paths(paths)
| from six import string_types
from django.db.models import signals
from .invalidation import invalidate_paths
def register(model):
register_instance_function_at_save(model, invalidate_model_paths)
def register_instance_function_at_save(model, function):
def save_function(sender, instance, **kwargs):
function(instance)
signals.post_save.connect(save_function, model, weak=False)
signals.pre_delete.connect(save_function, model, weak=False)
def get_paths_from_model(model):
paths = model.dependent_paths()
if isinstance(paths, string_types):
model_name = model.__class__.__name__
raise TypeError(
('dependent_paths on {model_name} should return a list of paths, '
' not a string'.format(model_name=model_name))
)
return paths
def invalidate_model_paths(model):
paths = get_paths_from_model(model)
invalidate_paths(paths)
| Use keyword based `format` to maintain 2.6 compatibility | Use keyword based `format` to maintain 2.6 compatibility
| Python | mit | saulshanabrook/django-dumper | from six import string_types
from django.db.models import signals
from .invalidation import invalidate_paths
def register(model):
register_instance_function_at_save(model, invalidate_model_paths)
def register_instance_function_at_save(model, function):
def save_function(sender, instance, **kwargs):
function(instance)
signals.post_save.connect(save_function, model, weak=False)
signals.pre_delete.connect(save_function, model, weak=False)
def get_paths_from_model(model):
paths = model.dependent_paths()
if isinstance(paths, string_types):
model_name = model.__class__.__name__
raise TypeError(
- ('dependent_paths on {} should return a list of paths, not a'
+ ('dependent_paths on {model_name} should return a list of paths, '
- 'string'.format(model_name))
+ ' not a string'.format(model_name=model_name))
)
return paths
def invalidate_model_paths(model):
paths = get_paths_from_model(model)
invalidate_paths(paths)
| Use keyword based `format` to maintain 2.6 compatibility | ## Code Before:
from six import string_types
from django.db.models import signals
from .invalidation import invalidate_paths
def register(model):
register_instance_function_at_save(model, invalidate_model_paths)
def register_instance_function_at_save(model, function):
def save_function(sender, instance, **kwargs):
function(instance)
signals.post_save.connect(save_function, model, weak=False)
signals.pre_delete.connect(save_function, model, weak=False)
def get_paths_from_model(model):
paths = model.dependent_paths()
if isinstance(paths, string_types):
model_name = model.__class__.__name__
raise TypeError(
('dependent_paths on {} should return a list of paths, not a'
'string'.format(model_name))
)
return paths
def invalidate_model_paths(model):
paths = get_paths_from_model(model)
invalidate_paths(paths)
## Instruction:
Use keyword based `format` to maintain 2.6 compatibility
## Code After:
from six import string_types
from django.db.models import signals
from .invalidation import invalidate_paths
def register(model):
register_instance_function_at_save(model, invalidate_model_paths)
def register_instance_function_at_save(model, function):
def save_function(sender, instance, **kwargs):
function(instance)
signals.post_save.connect(save_function, model, weak=False)
signals.pre_delete.connect(save_function, model, weak=False)
def get_paths_from_model(model):
paths = model.dependent_paths()
if isinstance(paths, string_types):
model_name = model.__class__.__name__
raise TypeError(
('dependent_paths on {model_name} should return a list of paths, '
' not a string'.format(model_name=model_name))
)
return paths
def invalidate_model_paths(model):
paths = get_paths_from_model(model)
invalidate_paths(paths)
| from six import string_types
from django.db.models import signals
from .invalidation import invalidate_paths
def register(model):
register_instance_function_at_save(model, invalidate_model_paths)
def register_instance_function_at_save(model, function):
def save_function(sender, instance, **kwargs):
function(instance)
signals.post_save.connect(save_function, model, weak=False)
signals.pre_delete.connect(save_function, model, weak=False)
def get_paths_from_model(model):
paths = model.dependent_paths()
if isinstance(paths, string_types):
model_name = model.__class__.__name__
raise TypeError(
- ('dependent_paths on {} should return a list of paths, not a'
? -----
+ ('dependent_paths on {model_name} should return a list of paths, '
? ++++++++++
- 'string'.format(model_name))
+ ' not a string'.format(model_name=model_name))
? +++++++ +++++++++++
)
return paths
def invalidate_model_paths(model):
paths = get_paths_from_model(model)
invalidate_paths(paths) |
c01cef9340a3d55884fe38b60b209dbad5f97ea6 | nova/db/sqlalchemy/migrate_repo/versions/080_add_hypervisor_hostname_to_compute_nodes.py | nova/db/sqlalchemy/migrate_repo/versions/080_add_hypervisor_hostname_to_compute_nodes.py |
from sqlalchemy import *
meta = MetaData()
compute_nodes = Table("compute_nodes", meta, Column("id", Integer(),
primary_key=True, nullable=False))
hypervisor_hostname = Column("hypervisor_hostname", String(255))
def upgrade(migrate_engine):
meta.bind = migrate_engine
compute_nodes.create_column(hypervisor_hostname)
def downgrade(migrate_engine):
meta.bind = migrate_engine
compute_nodes.drop_column(hypervisor_hostname)
|
from sqlalchemy import Column, MetaData, String, Table
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
compute_nodes = Table("compute_nodes", meta, autoload=True)
hypervisor_hostname = Column("hypervisor_hostname", String(255))
compute_nodes.create_column(hypervisor_hostname)
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
compute_nodes = Table("compute_nodes", meta, autoload=True)
compute_nodes.drop_column('hypervisor_hostname')
| Use sqlalchemy reflection in migration 080 | Use sqlalchemy reflection in migration 080
Change-Id: If2a0e59461d108d59c6e9907d3db053ba2b44f57
| Python | apache-2.0 | petrutlucian94/nova,adelina-t/nova,DirectXMan12/nova-hacking,sridevikoushik31/nova,gooddata/openstack-nova,alvarolopez/nova,whitepages/nova,thomasem/nova,affo/nova,berrange/nova,eayunstack/nova,mahak/nova,cernops/nova,felixma/nova,apporc/nova,cyx1231st/nova,openstack/nova,klmitch/nova,JianyuWang/nova,CiscoSystems/nova,devoid/nova,DirectXMan12/nova-hacking,badock/nova,saleemjaveds/https-github.com-openstack-nova,Tehsmash/nova,gspilio/nova,yosshy/nova,mandeepdhami/nova,saleemjaveds/https-github.com-openstack-nova,maoy/zknova,akash1808/nova,Francis-Liu/animated-broccoli,houshengbo/nova_vmware_compute_driver,leilihh/nova,usc-isi/extra-specs,shail2810/nova,spring-week-topos/nova-week,thomasem/nova,mikalstill/nova,blueboxgroup/nova,dstroppa/openstack-smartos-nova-grizzly,Brocade-OpenSource/OpenStack-DNRM-Nova,barnsnake351/nova,spring-week-topos/nova-week,imsplitbit/nova,Stavitsky/nova,petrutlucian94/nova,fnordahl/nova,sridevikoushik31/nova,Triv90/Nova,rahulunair/nova,hanlind/nova,paulmathews/nova,sebrandon1/nova,alexandrucoman/vbox-nova-driver,raildo/nova,qwefi/nova,rajalokan/nova,eharney/nova,gooddata/openstack-nova,Yuriy-Leonov/nova,akash1808/nova,ntt-sic/nova,NoBodyCam/TftpPxeBootBareMetal,TwinkleChawla/nova,rickerc/nova_audit,noironetworks/nova,dawnpower/nova,iuliat/nova,nikesh-mahalka/nova,rickerc/nova_audit,sileht/deb-openstack-nova,savi-dev/nova,JioCloud/nova_test_latest,klmitch/nova,mandeepdhami/nova,bgxavier/nova,cloudbase/nova,cloudbase/nova,houshengbo/nova_vmware_compute_driver,rahulunair/nova,cloudbase/nova-virtualbox,devendermishrajio/nova_test_latest,jeffrey4l/nova,NewpTone/stacklab-nova,Juniper/nova,fajoy/nova,takeshineshiro/nova,belmiromoreira/nova,bclau/nova,mmnelemane/nova,angdraug/nova,Juniper/nova,sridevikoushik31/nova,orbitfp7/nova,NewpTone/stacklab-nova,devendermishrajio/nova,ted-gould/nova,double12gzh/nova,Tehsmash/nova,JioCloud/nova_test_latest,BeyondTheClouds/nova,savi-dev/nova,watonyweng/nova,mgagne/nova,klmitch/nova,rrader/nova-docker-plugin,dims/nova,shootstar/novatest,devoid/nova,bigswitch/nova,dstroppa/openstack-smartos-nova-grizzly,eonpatapon/nova,cloudbau/nova,redhat-openstack/nova,leilihh/novaha,mahak/nova,NeCTAR-RC/nova,CCI-MOC/nova,Triv90/Nova,badock/nova,iuliat/nova,TwinkleChawla/nova,cyx1231st/nova,psiwczak/openstack,yrobla/nova,phenoxim/nova,tudorvio/nova,cloudbase/nova-virtualbox,shail2810/nova,joker946/nova,sridevikoushik31/openstack,yrobla/nova,zhimin711/nova,gspilio/nova,cernops/nova,aristanetworks/arista-ovs-nova,mahak/nova,LoHChina/nova,Triv90/Nova,sebrandon1/nova,edulramirez/nova,usc-isi/extra-specs,rajalokan/nova,sridevikoushik31/nova,angdraug/nova,usc-isi/nova,maheshp/novatest,varunarya10/nova_test_latest,bclau/nova,joker946/nova,psiwczak/openstack,shahar-stratoscale/nova,NoBodyCam/TftpPxeBootBareMetal,rahulunair/nova,noironetworks/nova,gooddata/openstack-nova,citrix-openstack-build/nova,nikesh-mahalka/nova,sebrandon1/nova,hanlind/nova,fajoy/nova,maoy/zknova,TieWei/nova,sacharya/nova,tealover/nova,ewindisch/nova,isyippee/nova,barnsnake351/nova,blueboxgroup/nova,sileht/deb-openstack-nova,sileht/deb-openstack-nova,eneabio/nova,raildo/nova,alaski/nova,kimjaejoong/nova,sridevikoushik31/openstack,berrange/nova,dawnpower/nova,ewindisch/nova,vmturbo/nova,OpenAcademy-OpenStack/nova-scheduler,edulramirez/nova,j-carpentier/nova,SUSE-Cloud/nova,MountainWei/nova,zzicewind/nova,vmturbo/nova,leilihh/nova,fnordahl/nova,yatinkumbhare/openstack-nova,BeyondTheClouds/nova,vladikr/nova_drafts,usc-isi/nova,orbitfp7/nova,sacharya/nova,ruslanloman/nova,Yusuke1987/openstack_template,shahar-stratoscale/nova,MountainWei/nova,gspilio/nova,scripnichenko/nova,maelnor/nova,mmnelemane/nova,CCI-MOC/nova,varunarya10/nova_test_latest,watonyweng/nova,yrobla/nova,devendermishrajio/nova_test_latest,OpenAcademy-OpenStack/nova-scheduler,psiwczak/openstack,rajalokan/nova,CloudServer/nova,openstack/nova,jianghuaw/nova,usc-isi/nova,rrader/nova-docker-plugin,cloudbase/nova,alexandrucoman/vbox-nova-driver,yosshy/nova,tealover/nova,gooddata/openstack-nova,apporc/nova,TieWei/nova,virtualopensystems/nova,hanlind/nova,jeffrey4l/nova,affo/nova,jianghuaw/nova,vmturbo/nova,devendermishrajio/nova,openstack/nova,Stavitsky/nova,jianghuaw/nova,qwefi/nova,klmitch/nova,alaski/nova,viggates/nova,Brocade-OpenSource/OpenStack-DNRM-Nova,maheshp/novatest,scripnichenko/nova,CloudServer/nova,bigswitch/nova,maelnor/nova,NeCTAR-RC/nova,redhat-openstack/nova,tianweizhang/nova,mikalstill/nova,rajalokan/nova,citrix-openstack-build/nova,mikalstill/nova,ntt-sic/nova,ruslanloman/nova,LoHChina/nova,jianghuaw/nova,shootstar/novatest,CEG-FYP-OpenStack/scheduler,kimjaejoong/nova,Francis-Liu/animated-broccoli,eayunstack/nova,bgxavier/nova,josephsuh/extra-specs,NoBodyCam/TftpPxeBootBareMetal,sridevikoushik31/openstack,savi-dev/nova,plumgrid/plumgrid-nova,felixma/nova,JianyuWang/nova,Yuriy-Leonov/nova,silenceli/nova,eharney/nova,imsplitbit/nova,aristanetworks/arista-ovs-nova,projectcalico/calico-nova,isyippee/nova,NewpTone/stacklab-nova,paulmathews/nova,petrutlucian94/nova_dev,Yusuke1987/openstack_template,plumgrid/plumgrid-nova,JioCloud/nova,Juniper/nova,petrutlucian94/nova_dev,luogangyi/bcec-nova,BeyondTheClouds/nova,Metaswitch/calico-nova,maheshp/novatest,projectcalico/calico-nova,alvarolopez/nova,vladikr/nova_drafts,fajoy/nova,dstroppa/openstack-smartos-nova-grizzly,whitepages/nova,eonpatapon/nova,leilihh/novaha,j-carpentier/nova,adelina-t/nova,vmturbo/nova,zaina/nova,double12gzh/nova,tianweizhang/nova,eneabio/nova,aristanetworks/arista-ovs-nova,tangfeixiong/nova,luogangyi/bcec-nova,paulmathews/nova,silenceli/nova,tudorvio/nova,dims/nova,phenoxim/nova,tanglei528/nova,maoy/zknova,JioCloud/nova,zzicewind/nova,ted-gould/nova,cernops/nova,cloudbau/nova,usc-isi/extra-specs,zaina/nova,mgagne/nova,Metaswitch/calico-nova,houshengbo/nova_vmware_compute_driver,tanglei528/nova,akash1808/nova_test_latest,CEG-FYP-OpenStack/scheduler,zhimin711/nova,viggates/nova,Juniper/nova,belmiromoreira/nova,yatinkumbhare/openstack-nova,akash1808/nova_test_latest,DirectXMan12/nova-hacking,eneabio/nova,josephsuh/extra-specs,SUSE-Cloud/nova,josephsuh/extra-specs,virtualopensystems/nova,takeshineshiro/nova,CiscoSystems/nova,tangfeixiong/nova |
+ from sqlalchemy import Column, MetaData, String, Table
- from sqlalchemy import *
-
-
- meta = MetaData()
-
- compute_nodes = Table("compute_nodes", meta, Column("id", Integer(),
- primary_key=True, nullable=False))
-
- hypervisor_hostname = Column("hypervisor_hostname", String(255))
def upgrade(migrate_engine):
+ meta = MetaData()
meta.bind = migrate_engine
+ compute_nodes = Table("compute_nodes", meta, autoload=True)
+ hypervisor_hostname = Column("hypervisor_hostname", String(255))
compute_nodes.create_column(hypervisor_hostname)
def downgrade(migrate_engine):
+ meta = MetaData()
meta.bind = migrate_engine
+ compute_nodes = Table("compute_nodes", meta, autoload=True)
- compute_nodes.drop_column(hypervisor_hostname)
+ compute_nodes.drop_column('hypervisor_hostname')
| Use sqlalchemy reflection in migration 080 | ## Code Before:
from sqlalchemy import *
meta = MetaData()
compute_nodes = Table("compute_nodes", meta, Column("id", Integer(),
primary_key=True, nullable=False))
hypervisor_hostname = Column("hypervisor_hostname", String(255))
def upgrade(migrate_engine):
meta.bind = migrate_engine
compute_nodes.create_column(hypervisor_hostname)
def downgrade(migrate_engine):
meta.bind = migrate_engine
compute_nodes.drop_column(hypervisor_hostname)
## Instruction:
Use sqlalchemy reflection in migration 080
## Code After:
from sqlalchemy import Column, MetaData, String, Table
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
compute_nodes = Table("compute_nodes", meta, autoload=True)
hypervisor_hostname = Column("hypervisor_hostname", String(255))
compute_nodes.create_column(hypervisor_hostname)
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
compute_nodes = Table("compute_nodes", meta, autoload=True)
compute_nodes.drop_column('hypervisor_hostname')
|
+ from sqlalchemy import Column, MetaData, String, Table
- from sqlalchemy import *
-
-
- meta = MetaData()
-
- compute_nodes = Table("compute_nodes", meta, Column("id", Integer(),
- primary_key=True, nullable=False))
-
- hypervisor_hostname = Column("hypervisor_hostname", String(255))
def upgrade(migrate_engine):
+ meta = MetaData()
meta.bind = migrate_engine
+ compute_nodes = Table("compute_nodes", meta, autoload=True)
+ hypervisor_hostname = Column("hypervisor_hostname", String(255))
compute_nodes.create_column(hypervisor_hostname)
def downgrade(migrate_engine):
+ meta = MetaData()
meta.bind = migrate_engine
+ compute_nodes = Table("compute_nodes", meta, autoload=True)
- compute_nodes.drop_column(hypervisor_hostname)
+ compute_nodes.drop_column('hypervisor_hostname')
? + +
|
55d0fa9b834e6400d48293c80e557c27f5cc4181 | yowsup/structs/protocolentity.py | yowsup/structs/protocolentity.py | from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, attributes, children = None, data = None):
return ProtocolTreeNode(self.getTag(), attributes, children, data)
def _getCurrentTimestamp(self):
return int(time.time())
def _generateId(self):
ProtocolEntity.__ID_GEN += 1
return str(int(time.time())) + "-" + str(ProtocolEntity.__ID_GEN)
def toProtocolTreeNode(self):
pass
@staticmethod
def fromProtocolTreeNode(self, protocolTreeNode):
pass
class ProtocolEntityTest(unittest.TestCase):
def setUp(self):
self.skipTest("override in child classes")
def test_generation(self):
entity = self.ProtocolEntity.fromProtocolTreeNode(self.node)
self.assertEqual(entity.toProtocolTreeNode(), self.node)
| from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, attributes, children = None, data = None):
return ProtocolTreeNode(self.getTag(), attributes, children, data)
def _getCurrentTimestamp(self):
return int(time.time())
def _generateId(self):
ProtocolEntity.__ID_GEN += 1
return str(int(time.time())) + "-" + str(ProtocolEntity.__ID_GEN)
def toProtocolTreeNode(self):
pass
@staticmethod
def fromProtocolTreeNode(self, protocolTreeNode):
pass
class ProtocolEntityTest(unittest.TestCase):
def setUp(self):
self.skipTest("override in child classes")
def test_generation(self):
entity = self.ProtocolEntity.fromProtocolTreeNode(self.node)
try:
self.assertEqual(entity.toProtocolTreeNode(), self.node)
except:
print(entity.toProtocolTreeNode())
print("\nNOTEQ\n")
print(self.node)
raise
| Print protocoltreenode on assertion failure | Print protocoltreenode on assertion failure
| Python | mit | biji/yowsup,ongair/yowsup | from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, attributes, children = None, data = None):
return ProtocolTreeNode(self.getTag(), attributes, children, data)
def _getCurrentTimestamp(self):
return int(time.time())
def _generateId(self):
ProtocolEntity.__ID_GEN += 1
return str(int(time.time())) + "-" + str(ProtocolEntity.__ID_GEN)
def toProtocolTreeNode(self):
pass
@staticmethod
def fromProtocolTreeNode(self, protocolTreeNode):
pass
class ProtocolEntityTest(unittest.TestCase):
def setUp(self):
self.skipTest("override in child classes")
def test_generation(self):
entity = self.ProtocolEntity.fromProtocolTreeNode(self.node)
+ try:
- self.assertEqual(entity.toProtocolTreeNode(), self.node)
+ self.assertEqual(entity.toProtocolTreeNode(), self.node)
+ except:
+ print(entity.toProtocolTreeNode())
+ print("\nNOTEQ\n")
+ print(self.node)
+ raise
| Print protocoltreenode on assertion failure | ## Code Before:
from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, attributes, children = None, data = None):
return ProtocolTreeNode(self.getTag(), attributes, children, data)
def _getCurrentTimestamp(self):
return int(time.time())
def _generateId(self):
ProtocolEntity.__ID_GEN += 1
return str(int(time.time())) + "-" + str(ProtocolEntity.__ID_GEN)
def toProtocolTreeNode(self):
pass
@staticmethod
def fromProtocolTreeNode(self, protocolTreeNode):
pass
class ProtocolEntityTest(unittest.TestCase):
def setUp(self):
self.skipTest("override in child classes")
def test_generation(self):
entity = self.ProtocolEntity.fromProtocolTreeNode(self.node)
self.assertEqual(entity.toProtocolTreeNode(), self.node)
## Instruction:
Print protocoltreenode on assertion failure
## Code After:
from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, attributes, children = None, data = None):
return ProtocolTreeNode(self.getTag(), attributes, children, data)
def _getCurrentTimestamp(self):
return int(time.time())
def _generateId(self):
ProtocolEntity.__ID_GEN += 1
return str(int(time.time())) + "-" + str(ProtocolEntity.__ID_GEN)
def toProtocolTreeNode(self):
pass
@staticmethod
def fromProtocolTreeNode(self, protocolTreeNode):
pass
class ProtocolEntityTest(unittest.TestCase):
def setUp(self):
self.skipTest("override in child classes")
def test_generation(self):
entity = self.ProtocolEntity.fromProtocolTreeNode(self.node)
try:
self.assertEqual(entity.toProtocolTreeNode(), self.node)
except:
print(entity.toProtocolTreeNode())
print("\nNOTEQ\n")
print(self.node)
raise
| from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, attributes, children = None, data = None):
return ProtocolTreeNode(self.getTag(), attributes, children, data)
def _getCurrentTimestamp(self):
return int(time.time())
def _generateId(self):
ProtocolEntity.__ID_GEN += 1
return str(int(time.time())) + "-" + str(ProtocolEntity.__ID_GEN)
def toProtocolTreeNode(self):
pass
@staticmethod
def fromProtocolTreeNode(self, protocolTreeNode):
pass
class ProtocolEntityTest(unittest.TestCase):
def setUp(self):
self.skipTest("override in child classes")
def test_generation(self):
entity = self.ProtocolEntity.fromProtocolTreeNode(self.node)
+ try:
- self.assertEqual(entity.toProtocolTreeNode(), self.node)
+ self.assertEqual(entity.toProtocolTreeNode(), self.node)
? ++++
+ except:
+ print(entity.toProtocolTreeNode())
+ print("\nNOTEQ\n")
+ print(self.node)
+ raise
|
f2109a486b3459a3fbf4e5e7db92780f1765a5a8 | test_app/urls.py | test_app/urls.py | from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.http import HttpResponseNotFound, HttpResponseServerError
from test_app import views
from waffle.views import wafflejs
handler404 = lambda r: HttpResponseNotFound()
handler500 = lambda r: HttpResponseServerError()
admin.autodiscover()
urlpatterns = patterns('',
url(r'^flag_in_view', views.flag_in_view, name='flag_in_view'),
url(r'^wafflejs$', wafflejs, name='wafflejs'),
url(r'^switch-on', views.switched_view),
url(r'^switch-off', views.switched_off_view),
url(r'^flag-on', views.flagged_view),
url(r'^flag-off', views.flagged_off_view),
(r'^admin/', include(admin.site.urls))
)
| from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.http import HttpResponseNotFound, HttpResponseServerError
from test_app import views
handler404 = lambda r: HttpResponseNotFound()
handler500 = lambda r: HttpResponseServerError()
admin.autodiscover()
urlpatterns = patterns('',
url(r'^flag_in_view', views.flag_in_view, name='flag_in_view'),
url(r'^switch-on', views.switched_view),
url(r'^switch-off', views.switched_off_view),
url(r'^flag-on', views.flagged_view),
url(r'^flag-off', views.flagged_off_view),
(r'^', include('waffle.urls')),
(r'^admin/', include(admin.site.urls))
)
| Use new URLs module in test_app. | Use new URLs module in test_app.
| Python | bsd-3-clause | mark-adams/django-waffle,festicket/django-waffle,hwkns/django-waffle,JeLoueMonCampingCar/django-waffle,crccheck/django-waffle,ilanbm/django-waffle,mwaaas/django-waffle-session,11craft/django-waffle,VladimirFilonov/django-waffle,willkg/django-waffle,rodgomes/django-waffle,festicket/django-waffle,crccheck/django-waffle,rlr/django-waffle,groovecoder/django-waffle,engagespark/django-waffle,rlr/django-waffle,mwaaas/django-waffle-session,safarijv/django-waffle,rsalmaso/django-waffle,safarijv/django-waffle,rodgomes/django-waffle,ilanbm/django-waffle,engagespark/django-waffle,festicket/django-waffle,styleseat/django-waffle,JeLoueMonCampingCar/django-waffle,engagespark/django-waffle,safarijv/django-waffle,styleseat/django-waffle,JeLoueMonCampingCar/django-waffle,VladimirFilonov/django-waffle,VladimirFilonov/django-waffle,ekohl/django-waffle,TwigWorld/django-waffle,TwigWorld/django-waffle,webus/django-waffle,mark-adams/django-waffle,VladimirFilonov/django-waffle,paulcwatts/django-waffle,ilanbm/django-waffle,rodgomes/django-waffle,crccheck/django-waffle,styleseat/django-waffle,paulcwatts/django-waffle,willkg/django-waffle,mark-adams/django-waffle,rlr/django-waffle,hwkns/django-waffle,isotoma/django-waffle,11craft/django-waffle,groovecoder/django-waffle,rsalmaso/django-waffle,rodgomes/django-waffle,mwaaas/django-waffle-session,rlr/django-waffle,paulcwatts/django-waffle,hwkns/django-waffle,festicket/django-waffle,paulcwatts/django-waffle,mark-adams/django-waffle,groovecoder/django-waffle,styleseat/django-waffle,isotoma/django-waffle,mwaaas/django-waffle-session,hwkns/django-waffle,JeLoueMonCampingCar/django-waffle,crccheck/django-waffle,isotoma/django-waffle,TwigWorld/django-waffle,rsalmaso/django-waffle,webus/django-waffle,safarijv/django-waffle,engagespark/django-waffle,ilanbm/django-waffle,isotoma/django-waffle,groovecoder/django-waffle,webus/django-waffle,webus/django-waffle,ekohl/django-waffle,rsalmaso/django-waffle | from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.http import HttpResponseNotFound, HttpResponseServerError
from test_app import views
- from waffle.views import wafflejs
handler404 = lambda r: HttpResponseNotFound()
handler500 = lambda r: HttpResponseServerError()
admin.autodiscover()
urlpatterns = patterns('',
url(r'^flag_in_view', views.flag_in_view, name='flag_in_view'),
- url(r'^wafflejs$', wafflejs, name='wafflejs'),
url(r'^switch-on', views.switched_view),
url(r'^switch-off', views.switched_off_view),
url(r'^flag-on', views.flagged_view),
url(r'^flag-off', views.flagged_off_view),
+ (r'^', include('waffle.urls')),
(r'^admin/', include(admin.site.urls))
)
| Use new URLs module in test_app. | ## Code Before:
from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.http import HttpResponseNotFound, HttpResponseServerError
from test_app import views
from waffle.views import wafflejs
handler404 = lambda r: HttpResponseNotFound()
handler500 = lambda r: HttpResponseServerError()
admin.autodiscover()
urlpatterns = patterns('',
url(r'^flag_in_view', views.flag_in_view, name='flag_in_view'),
url(r'^wafflejs$', wafflejs, name='wafflejs'),
url(r'^switch-on', views.switched_view),
url(r'^switch-off', views.switched_off_view),
url(r'^flag-on', views.flagged_view),
url(r'^flag-off', views.flagged_off_view),
(r'^admin/', include(admin.site.urls))
)
## Instruction:
Use new URLs module in test_app.
## Code After:
from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.http import HttpResponseNotFound, HttpResponseServerError
from test_app import views
handler404 = lambda r: HttpResponseNotFound()
handler500 = lambda r: HttpResponseServerError()
admin.autodiscover()
urlpatterns = patterns('',
url(r'^flag_in_view', views.flag_in_view, name='flag_in_view'),
url(r'^switch-on', views.switched_view),
url(r'^switch-off', views.switched_off_view),
url(r'^flag-on', views.flagged_view),
url(r'^flag-off', views.flagged_off_view),
(r'^', include('waffle.urls')),
(r'^admin/', include(admin.site.urls))
)
| from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.http import HttpResponseNotFound, HttpResponseServerError
from test_app import views
- from waffle.views import wafflejs
handler404 = lambda r: HttpResponseNotFound()
handler500 = lambda r: HttpResponseServerError()
admin.autodiscover()
urlpatterns = patterns('',
url(r'^flag_in_view', views.flag_in_view, name='flag_in_view'),
- url(r'^wafflejs$', wafflejs, name='wafflejs'),
url(r'^switch-on', views.switched_view),
url(r'^switch-off', views.switched_off_view),
url(r'^flag-on', views.flagged_view),
url(r'^flag-off', views.flagged_off_view),
+ (r'^', include('waffle.urls')),
(r'^admin/', include(admin.site.urls))
) |
b26bf17154e478ee02e0e2936d7623d71698e1f2 | subprocrunner/_which.py | subprocrunner/_which.py |
import errno
import shutil
from typing import Optional
from .error import CommandError
class Which:
@property
def command(self):
return self.__command
def __init__(self, command: str) -> None:
if not command:
raise CommandError(
"invalid command {}: ".format(command), cmd=command, errno=errno.EINVAL
)
self.__command = command
self.__abspath = None # type: Optional[str]
def __repr__(self) -> str:
item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())]
if self.is_exist():
item_list.append("abspath={}".format(self.abspath()))
return ", ".join(item_list)
def is_exist(self) -> bool:
return self.abspath() is not None
def verify(self) -> None:
if not self.is_exist():
raise CommandError(
"command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT
)
def abspath(self) -> Optional[str]:
if self.__abspath:
return self.__abspath
self.__abspath = shutil.which(self.command)
return self.__abspath
|
import errno
import shutil
from typing import Optional
from .error import CommandError
class Which:
@property
def command(self):
return self.__command
def __init__(self, command: str) -> None:
if not command:
raise ValueError("require a command")
self.__command = command
self.__abspath = None # type: Optional[str]
def __repr__(self) -> str:
item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())]
if self.is_exist():
item_list.append("abspath={}".format(self.abspath()))
return ", ".join(item_list)
def is_exist(self) -> bool:
return self.abspath() is not None
def verify(self) -> None:
if not self.is_exist():
raise CommandError(
"command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT
)
def abspath(self) -> Optional[str]:
if self.__abspath:
return self.__abspath
self.__abspath = shutil.which(self.command)
return self.__abspath
| Modify an error handling when a command not specified for Which | Modify an error handling when a command not specified for Which
| Python | mit | thombashi/subprocrunner,thombashi/subprocrunner |
import errno
import shutil
from typing import Optional
from .error import CommandError
class Which:
@property
def command(self):
return self.__command
def __init__(self, command: str) -> None:
if not command:
+ raise ValueError("require a command")
- raise CommandError(
- "invalid command {}: ".format(command), cmd=command, errno=errno.EINVAL
- )
self.__command = command
self.__abspath = None # type: Optional[str]
def __repr__(self) -> str:
item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())]
if self.is_exist():
item_list.append("abspath={}".format(self.abspath()))
return ", ".join(item_list)
def is_exist(self) -> bool:
return self.abspath() is not None
def verify(self) -> None:
if not self.is_exist():
raise CommandError(
"command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT
)
def abspath(self) -> Optional[str]:
if self.__abspath:
return self.__abspath
self.__abspath = shutil.which(self.command)
return self.__abspath
| Modify an error handling when a command not specified for Which | ## Code Before:
import errno
import shutil
from typing import Optional
from .error import CommandError
class Which:
@property
def command(self):
return self.__command
def __init__(self, command: str) -> None:
if not command:
raise CommandError(
"invalid command {}: ".format(command), cmd=command, errno=errno.EINVAL
)
self.__command = command
self.__abspath = None # type: Optional[str]
def __repr__(self) -> str:
item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())]
if self.is_exist():
item_list.append("abspath={}".format(self.abspath()))
return ", ".join(item_list)
def is_exist(self) -> bool:
return self.abspath() is not None
def verify(self) -> None:
if not self.is_exist():
raise CommandError(
"command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT
)
def abspath(self) -> Optional[str]:
if self.__abspath:
return self.__abspath
self.__abspath = shutil.which(self.command)
return self.__abspath
## Instruction:
Modify an error handling when a command not specified for Which
## Code After:
import errno
import shutil
from typing import Optional
from .error import CommandError
class Which:
@property
def command(self):
return self.__command
def __init__(self, command: str) -> None:
if not command:
raise ValueError("require a command")
self.__command = command
self.__abspath = None # type: Optional[str]
def __repr__(self) -> str:
item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())]
if self.is_exist():
item_list.append("abspath={}".format(self.abspath()))
return ", ".join(item_list)
def is_exist(self) -> bool:
return self.abspath() is not None
def verify(self) -> None:
if not self.is_exist():
raise CommandError(
"command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT
)
def abspath(self) -> Optional[str]:
if self.__abspath:
return self.__abspath
self.__abspath = shutil.which(self.command)
return self.__abspath
|
import errno
import shutil
from typing import Optional
from .error import CommandError
class Which:
@property
def command(self):
return self.__command
def __init__(self, command: str) -> None:
if not command:
+ raise ValueError("require a command")
- raise CommandError(
- "invalid command {}: ".format(command), cmd=command, errno=errno.EINVAL
- )
self.__command = command
self.__abspath = None # type: Optional[str]
def __repr__(self) -> str:
item_list = ["command={}".format(self.command), "is_exist={}".format(self.is_exist())]
if self.is_exist():
item_list.append("abspath={}".format(self.abspath()))
return ", ".join(item_list)
def is_exist(self) -> bool:
return self.abspath() is not None
def verify(self) -> None:
if not self.is_exist():
raise CommandError(
"command not found: '{}'".format(self.command), cmd=self.command, errno=errno.ENOENT
)
def abspath(self) -> Optional[str]:
if self.__abspath:
return self.__abspath
self.__abspath = shutil.which(self.command)
return self.__abspath |
b4e3461277669bf42225d278d491b7c714968491 | vm_server/test/execute_macro/code/execute.py | vm_server/test/execute_macro/code/execute.py | import os
import shutil
import win32com.client
import pythoncom
import repackage
repackage.up()
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
path_to_file = current_path + "\\action\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
shutil.move(path_to_file, current_path +
"\\action\\output\\excelsheet.xlsm")
shutil.move(current_path + "\\action\\data\\output.txt", current_path +
"\\action\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
| import os
import shutil
import win32com.client
import pythoncom
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
path_to_file = ".\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
shutil.move(path_to_file, ".\\output\\excelsheet.xlsm")
shutil.move(".\\data\\output.txt", ".\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
| Modify excel screenshot test so that it works with the new directory structure | Modify excel screenshot test so that it works with the new directory structure
| Python | apache-2.0 | googleinterns/automated-windows-vms,googleinterns/automated-windows-vms | import os
import shutil
import win32com.client
import pythoncom
- import repackage
- repackage.up()
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
- path_to_file = current_path + "\\action\\data\\excelsheet.xlsm"
+ path_to_file = ".\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
+ shutil.move(path_to_file, ".\\output\\excelsheet.xlsm")
+ shutil.move(".\\data\\output.txt", ".\\output\\output.txt")
- shutil.move(path_to_file, current_path +
- "\\action\\output\\excelsheet.xlsm")
- shutil.move(current_path + "\\action\\data\\output.txt", current_path +
- "\\action\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
| Modify excel screenshot test so that it works with the new directory structure | ## Code Before:
import os
import shutil
import win32com.client
import pythoncom
import repackage
repackage.up()
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
path_to_file = current_path + "\\action\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
shutil.move(path_to_file, current_path +
"\\action\\output\\excelsheet.xlsm")
shutil.move(current_path + "\\action\\data\\output.txt", current_path +
"\\action\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
## Instruction:
Modify excel screenshot test so that it works with the new directory structure
## Code After:
import os
import shutil
import win32com.client
import pythoncom
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
path_to_file = ".\\data\\excelsheet.xlsm"
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
shutil.move(path_to_file, ".\\output\\excelsheet.xlsm")
shutil.move(".\\data\\output.txt", ".\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro()
| import os
import shutil
import win32com.client
import pythoncom
- import repackage
- repackage.up()
def execute_macro():
"""Execute VBA macro in MS Excel
"""
pythoncom.CoInitialize()
current_path = os.path.dirname(os.getcwd())
- path_to_file = current_path + "\\action\\data\\excelsheet.xlsm"
? --------------- ^^^^^^^^
+ path_to_file = ".\\data\\excelsheet.xlsm"
? ^
if os.path.exists(path_to_file):
xl_file = win32com.client.Dispatch("Excel.Application")
xl_run = xl_file.Workbooks.Open(os.path.abspath(path_to_file),
ReadOnly=1)
xl_run.Application.Run("excelsheet.xlsm!Module1.add_numbers_in_column") #execute macro
xl_run.Save()
xl_run.Close()
xl_file.Quit()
del xl_file
+ shutil.move(path_to_file, ".\\output\\excelsheet.xlsm")
+ shutil.move(".\\data\\output.txt", ".\\output\\output.txt")
- shutil.move(path_to_file, current_path +
- "\\action\\output\\excelsheet.xlsm")
- shutil.move(current_path + "\\action\\data\\output.txt", current_path +
- "\\action\\output\\output.txt")
print("Action successfully executed")
if __name__ == "__main__":
execute_macro() |
be1b1de45b93b5c72d6d76667430a6be4c56fb75 | vsmomi/_service_instance.py | vsmomi/_service_instance.py |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
import base64
import atexit
import requests
# disable warnings
try:
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
class ServiceInstance(object):
def __init__(self, vcenter, username, password):
self.si = None
self.vcenter = vcenter
self.username = username
self.password = password
self.__connect()
def __connect(self):
connect = True
if self.si:
# check connection
try:
self.si.CurrentTime()
connect = False
except vim.fault.NotAuthenticated:
# timeout
pass
if connect:
si = None
try:
pwd = base64.b64decode(self.password).decode("utf-8")
si = SmartConnect(
host=self.vcenter,
user=self.username,
pwd=pwd,
port=443)
except IOError:
raise
if self.si is None:
atexit.register(Disconnect, self.si)
else:
Disconnect(self.si)
self.si = si
def __getattr__(self, name):
self.__connect()
return getattr(self.si, name)
|
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
import base64
import atexit
import requests
# disable warnings
try:
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass
# disable SSL verification
__get = requests.get
def getNoSLL(*args, **kwargs):
kwargs["verify"] = False
return __get(*args, **kwargs)
requests.get = getNoSLL
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
class ServiceInstance(object):
def __init__(self, vcenter, username, password):
self.si = None
self.vcenter = vcenter
self.username = username
self.password = password
self.__connect()
def __connect(self):
connect = True
if self.si:
# check connection
try:
self.si.CurrentTime()
connect = False
except vim.fault.NotAuthenticated:
# timeout
pass
if connect:
si = None
try:
pwd = base64.b64decode(self.password).decode("utf-8")
si = SmartConnect(
host=self.vcenter,
user=self.username,
pwd=pwd,
port=443)
except IOError:
raise
if self.si is None:
atexit.register(Disconnect, self.si)
else:
Disconnect(self.si)
self.si = si
def __getattr__(self, name):
self.__connect()
return getattr(self.si, name)
| Disable SSL verification in requests.get | Disable SSL verification in requests.get
| Python | apache-2.0 | dahuebi/vsmomi,dahuebi/vsmomi |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
import base64
import atexit
import requests
# disable warnings
try:
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass
+
+ # disable SSL verification
+ __get = requests.get
+ def getNoSLL(*args, **kwargs):
+ kwargs["verify"] = False
+ return __get(*args, **kwargs)
+ requests.get = getNoSLL
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
class ServiceInstance(object):
def __init__(self, vcenter, username, password):
self.si = None
self.vcenter = vcenter
self.username = username
self.password = password
self.__connect()
def __connect(self):
connect = True
if self.si:
# check connection
try:
self.si.CurrentTime()
connect = False
except vim.fault.NotAuthenticated:
# timeout
pass
if connect:
si = None
try:
pwd = base64.b64decode(self.password).decode("utf-8")
si = SmartConnect(
host=self.vcenter,
user=self.username,
pwd=pwd,
port=443)
except IOError:
raise
if self.si is None:
atexit.register(Disconnect, self.si)
else:
Disconnect(self.si)
self.si = si
def __getattr__(self, name):
self.__connect()
return getattr(self.si, name)
| Disable SSL verification in requests.get | ## Code Before:
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
import base64
import atexit
import requests
# disable warnings
try:
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
class ServiceInstance(object):
def __init__(self, vcenter, username, password):
self.si = None
self.vcenter = vcenter
self.username = username
self.password = password
self.__connect()
def __connect(self):
connect = True
if self.si:
# check connection
try:
self.si.CurrentTime()
connect = False
except vim.fault.NotAuthenticated:
# timeout
pass
if connect:
si = None
try:
pwd = base64.b64decode(self.password).decode("utf-8")
si = SmartConnect(
host=self.vcenter,
user=self.username,
pwd=pwd,
port=443)
except IOError:
raise
if self.si is None:
atexit.register(Disconnect, self.si)
else:
Disconnect(self.si)
self.si = si
def __getattr__(self, name):
self.__connect()
return getattr(self.si, name)
## Instruction:
Disable SSL verification in requests.get
## Code After:
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
import base64
import atexit
import requests
# disable warnings
try:
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass
# disable SSL verification
__get = requests.get
def getNoSLL(*args, **kwargs):
kwargs["verify"] = False
return __get(*args, **kwargs)
requests.get = getNoSLL
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
class ServiceInstance(object):
def __init__(self, vcenter, username, password):
self.si = None
self.vcenter = vcenter
self.username = username
self.password = password
self.__connect()
def __connect(self):
connect = True
if self.si:
# check connection
try:
self.si.CurrentTime()
connect = False
except vim.fault.NotAuthenticated:
# timeout
pass
if connect:
si = None
try:
pwd = base64.b64decode(self.password).decode("utf-8")
si = SmartConnect(
host=self.vcenter,
user=self.username,
pwd=pwd,
port=443)
except IOError:
raise
if self.si is None:
atexit.register(Disconnect, self.si)
else:
Disconnect(self.si)
self.si = si
def __getattr__(self, name):
self.__connect()
return getattr(self.si, name)
|
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
import base64
import atexit
import requests
# disable warnings
try:
requests.packages.urllib3.disable_warnings()
except AttributeError:
pass
+
+ # disable SSL verification
+ __get = requests.get
+ def getNoSLL(*args, **kwargs):
+ kwargs["verify"] = False
+ return __get(*args, **kwargs)
+ requests.get = getNoSLL
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
class ServiceInstance(object):
def __init__(self, vcenter, username, password):
self.si = None
self.vcenter = vcenter
self.username = username
self.password = password
self.__connect()
def __connect(self):
connect = True
if self.si:
# check connection
try:
self.si.CurrentTime()
connect = False
except vim.fault.NotAuthenticated:
# timeout
pass
if connect:
si = None
try:
pwd = base64.b64decode(self.password).decode("utf-8")
si = SmartConnect(
host=self.vcenter,
user=self.username,
pwd=pwd,
port=443)
except IOError:
raise
if self.si is None:
atexit.register(Disconnect, self.si)
else:
Disconnect(self.si)
self.si = si
def __getattr__(self, name):
self.__connect()
return getattr(self.si, name)
|
906d60089dbe6b263ae55d91ba73d6b6e41ebbb5 | api/admin.py | api/admin.py | from django.contrib import admin
from .models import MaintenanceRecord, UserPreferences
@admin.register(UserPreferences)
class UserPreferencesAdmin(admin.ModelAdmin):
list_display = ["user", "show_beta_interface", "airport_ui", "created_date", "modified_date"]
list_filter = [
"show_beta_interface", "airport_ui",
]
# Register your models here.
admin.site.register(MaintenanceRecord)
| from django.contrib import admin
from .models import MaintenanceRecord, UserPreferences, HelpLink
@admin.register(UserPreferences)
class UserPreferencesAdmin(admin.ModelAdmin):
list_display = ["user", "show_beta_interface", "airport_ui", "created_date", "modified_date"]
list_filter = [
"show_beta_interface", "airport_ui",
]
@admin.register(HelpLink)
class HelpLinkAdmin(admin.ModelAdmin):
actions = None # disable the `delete selected` action
list_display = ["link_key", "topic", "context", "href"]
def get_readonly_fields(self, request, obj=None):
if obj: # editing an existing object
return self.readonly_fields + ("link_key", )
return self.readonly_fields
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
# Register your models here.
admin.site.register(MaintenanceRecord)
| Add entire in Admin for managing HelpLink | Add entire in Admin for managing HelpLink
An admin can _only_ modify the hyperlink associated with a HelpLink.
As a consequence, you cannot add new instances of the model nor delete
them. Only the existing HelpLinks can be modified because their
inclusion (or existence) is dependent upon the usage within the UI.
If one *must* do something to add or delete or override what is allowed
via Django Admin, they will _need_ database/SQL level access given this
current implementation.
See ATMO-1230 & ATMO-1270 for more context.
| Python | apache-2.0 | CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend | from django.contrib import admin
- from .models import MaintenanceRecord, UserPreferences
+ from .models import MaintenanceRecord, UserPreferences, HelpLink
@admin.register(UserPreferences)
class UserPreferencesAdmin(admin.ModelAdmin):
list_display = ["user", "show_beta_interface", "airport_ui", "created_date", "modified_date"]
list_filter = [
"show_beta_interface", "airport_ui",
]
+ @admin.register(HelpLink)
+ class HelpLinkAdmin(admin.ModelAdmin):
+ actions = None # disable the `delete selected` action
+
+ list_display = ["link_key", "topic", "context", "href"]
+
+ def get_readonly_fields(self, request, obj=None):
+ if obj: # editing an existing object
+ return self.readonly_fields + ("link_key", )
+ return self.readonly_fields
+
+ def has_add_permission(self, request):
+ return False
+
+ def has_delete_permission(self, request, obj=None):
+ return False
+
+
# Register your models here.
admin.site.register(MaintenanceRecord)
| Add entire in Admin for managing HelpLink | ## Code Before:
from django.contrib import admin
from .models import MaintenanceRecord, UserPreferences
@admin.register(UserPreferences)
class UserPreferencesAdmin(admin.ModelAdmin):
list_display = ["user", "show_beta_interface", "airport_ui", "created_date", "modified_date"]
list_filter = [
"show_beta_interface", "airport_ui",
]
# Register your models here.
admin.site.register(MaintenanceRecord)
## Instruction:
Add entire in Admin for managing HelpLink
## Code After:
from django.contrib import admin
from .models import MaintenanceRecord, UserPreferences, HelpLink
@admin.register(UserPreferences)
class UserPreferencesAdmin(admin.ModelAdmin):
list_display = ["user", "show_beta_interface", "airport_ui", "created_date", "modified_date"]
list_filter = [
"show_beta_interface", "airport_ui",
]
@admin.register(HelpLink)
class HelpLinkAdmin(admin.ModelAdmin):
actions = None # disable the `delete selected` action
list_display = ["link_key", "topic", "context", "href"]
def get_readonly_fields(self, request, obj=None):
if obj: # editing an existing object
return self.readonly_fields + ("link_key", )
return self.readonly_fields
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
# Register your models here.
admin.site.register(MaintenanceRecord)
| from django.contrib import admin
- from .models import MaintenanceRecord, UserPreferences
+ from .models import MaintenanceRecord, UserPreferences, HelpLink
? ++++++++++
@admin.register(UserPreferences)
class UserPreferencesAdmin(admin.ModelAdmin):
list_display = ["user", "show_beta_interface", "airport_ui", "created_date", "modified_date"]
list_filter = [
"show_beta_interface", "airport_ui",
]
+ @admin.register(HelpLink)
+ class HelpLinkAdmin(admin.ModelAdmin):
+ actions = None # disable the `delete selected` action
+
+ list_display = ["link_key", "topic", "context", "href"]
+
+ def get_readonly_fields(self, request, obj=None):
+ if obj: # editing an existing object
+ return self.readonly_fields + ("link_key", )
+ return self.readonly_fields
+
+ def has_add_permission(self, request):
+ return False
+
+ def has_delete_permission(self, request, obj=None):
+ return False
+
+
# Register your models here.
admin.site.register(MaintenanceRecord) |
d7219365197ff22aec44836e37af19f62420f996 | paystackapi/tests/test_tcontrol.py | paystackapi/tests/test_tcontrol.py | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/balance"),
content_type='text/json',
body='{"status": true, "message": "Balances retrieved"}',
status=201,
)
response = TransferControl.check_balance()
self.assertTrue(response['status'])
| import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/balance"),
content_type='text/json',
body='{"status": true, "message": "Balances retrieved"}',
status=201,
)
response = TransferControl.check_balance()
self.assertTrue(response['status'])
@httpretty.activate
def test_resend_otp(self):
"""Method defined to test resend_otp."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/transfer/resend_otp"),
content_type='text/json',
body='{"status": true, "message": "OTP has been resent"}',
status=201,
)
response = TransferControl.resend_otp(
transfer_code="TRF_vsyqdmlzble3uii",
reason="Just do it."
)
self.assertTrue(response['status'])
| Add test for transfer control resend otp | Add test for transfer control resend otp
| Python | mit | andela-sjames/paystack-python | import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/balance"),
content_type='text/json',
body='{"status": true, "message": "Balances retrieved"}',
status=201,
)
response = TransferControl.check_balance()
self.assertTrue(response['status'])
+ @httpretty.activate
+ def test_resend_otp(self):
+ """Method defined to test resend_otp."""
+ httpretty.register_uri(
+ httpretty.POST,
+ self.endpoint_url("/transfer/resend_otp"),
+ content_type='text/json',
+ body='{"status": true, "message": "OTP has been resent"}',
+ status=201,
+ )
+
+ response = TransferControl.resend_otp(
+ transfer_code="TRF_vsyqdmlzble3uii",
+ reason="Just do it."
+ )
+ self.assertTrue(response['status'])
+
+ | Add test for transfer control resend otp | ## Code Before:
import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/balance"),
content_type='text/json',
body='{"status": true, "message": "Balances retrieved"}',
status=201,
)
response = TransferControl.check_balance()
self.assertTrue(response['status'])
## Instruction:
Add test for transfer control resend otp
## Code After:
import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/balance"),
content_type='text/json',
body='{"status": true, "message": "Balances retrieved"}',
status=201,
)
response = TransferControl.check_balance()
self.assertTrue(response['status'])
@httpretty.activate
def test_resend_otp(self):
"""Method defined to test resend_otp."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/transfer/resend_otp"),
content_type='text/json',
body='{"status": true, "message": "OTP has been resent"}',
status=201,
)
response = TransferControl.resend_otp(
transfer_code="TRF_vsyqdmlzble3uii",
reason="Just do it."
)
self.assertTrue(response['status'])
| import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.tcontrol import TransferControl
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/balance"),
content_type='text/json',
body='{"status": true, "message": "Balances retrieved"}',
status=201,
)
response = TransferControl.check_balance()
self.assertTrue(response['status'])
+
+ @httpretty.activate
+ def test_resend_otp(self):
+ """Method defined to test resend_otp."""
+ httpretty.register_uri(
+ httpretty.POST,
+ self.endpoint_url("/transfer/resend_otp"),
+ content_type='text/json',
+ body='{"status": true, "message": "OTP has been resent"}',
+ status=201,
+ )
+
+ response = TransferControl.resend_otp(
+ transfer_code="TRF_vsyqdmlzble3uii",
+ reason="Just do it."
+ )
+ self.assertTrue(response['status'])
+ |
6427ef6e05e3add17533c0a86603943c85020eb6 | inonemonth/challenges/templatetags/challenges_extras.py | inonemonth/challenges/templatetags/challenges_extras.py | from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "Clencher (de.rouck.robrecht@gmail.com)"
elif role.type == "juror":
if role == user_role:
return "Juror 1 (me)"
else:
return "Juror 2"
else:
return Exception("Else Die")
elif user_role.type == "clencher":
if role.type == "clencher":
return "Clencher (me)"
elif role.type == "juror":
return "Juror 1 (andy.slacker@gmail.com)"
else:
return Exception("Else Die")
else:
return Exception("Else Die")
| from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "{0} ({1})".format(role.type.capitalize(), role.user.email)
elif role.type == "juror":
if role == user_role:
return "Juror 1 (me)"
else:
return "Juror 2"
else:
return Exception("Else Die")
elif user_role.type == "clencher":
if role.type == "clencher":
return "Clencher (me)"
elif role.type == "juror":
return "Juror 1 (andy.slacker@gmail.com)"
else:
return Exception("Else Die")
else:
return Exception("Else Die")
| Increase abstractness for one test method | Increase abstractness for one test method
| Python | mit | robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth | from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
- return "Clencher (de.rouck.robrecht@gmail.com)"
+ return "{0} ({1})".format(role.type.capitalize(), role.user.email)
elif role.type == "juror":
if role == user_role:
return "Juror 1 (me)"
else:
return "Juror 2"
else:
return Exception("Else Die")
elif user_role.type == "clencher":
if role.type == "clencher":
return "Clencher (me)"
elif role.type == "juror":
return "Juror 1 (andy.slacker@gmail.com)"
else:
return Exception("Else Die")
else:
return Exception("Else Die")
| Increase abstractness for one test method | ## Code Before:
from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "Clencher (de.rouck.robrecht@gmail.com)"
elif role.type == "juror":
if role == user_role:
return "Juror 1 (me)"
else:
return "Juror 2"
else:
return Exception("Else Die")
elif user_role.type == "clencher":
if role.type == "clencher":
return "Clencher (me)"
elif role.type == "juror":
return "Juror 1 (andy.slacker@gmail.com)"
else:
return Exception("Else Die")
else:
return Exception("Else Die")
## Instruction:
Increase abstractness for one test method
## Code After:
from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
return "{0} ({1})".format(role.type.capitalize(), role.user.email)
elif role.type == "juror":
if role == user_role:
return "Juror 1 (me)"
else:
return "Juror 2"
else:
return Exception("Else Die")
elif user_role.type == "clencher":
if role.type == "clencher":
return "Clencher (me)"
elif role.type == "juror":
return "Juror 1 (andy.slacker@gmail.com)"
else:
return Exception("Else Die")
else:
return Exception("Else Die")
| from django.template import Library
register = Library()
@register.filter
def get_representation_for_user(role, user_role):
if user_role.type == "juror":
if role.type == "clencher":
- return "Clencher (de.rouck.robrecht@gmail.com)"
+ return "{0} ({1})".format(role.type.capitalize(), role.user.email)
elif role.type == "juror":
if role == user_role:
return "Juror 1 (me)"
else:
return "Juror 2"
else:
return Exception("Else Die")
elif user_role.type == "clencher":
if role.type == "clencher":
return "Clencher (me)"
elif role.type == "juror":
return "Juror 1 (andy.slacker@gmail.com)"
else:
return Exception("Else Die")
else:
return Exception("Else Die") |
2f65eba48e5bdeac85b12cac014cb648d068da46 | tests/test_utils.py | tests/test_utils.py | import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2) | import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link")) | Add unit test for is_safe_url utility function | Add unit test for is_safe_url utility function
| Python | mit | Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary | import unittest
from app import create_app, db
- from app.utils import get_or_create
+ from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
+
+ def test_is_safe_url(self):
+ with self.app.test_request_context():
+ self.assertFalse(is_safe_url("http://externalsite.com"))
+ self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
+ self.assertTrue(is_safe_url("safe_internal_link")) | Add unit test for is_safe_url utility function | ## Code Before:
import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
## Instruction:
Add unit test for is_safe_url utility function
## Code After:
import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link")) | import unittest
from app import create_app, db
- from app.utils import get_or_create
+ from app.utils import get_or_create, is_safe_url
? +++++++++++++
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
+
+ def test_is_safe_url(self):
+ with self.app.test_request_context():
+ self.assertFalse(is_safe_url("http://externalsite.com"))
+ self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
+ self.assertTrue(is_safe_url("safe_internal_link")) |
a71b60363a39414eac712210086ce51abeed41d0 | api/feedback/admin.py | api/feedback/admin.py | from django import forms
from django.contrib import admin
from feedback.models import Feedback
class FeedbackAdminForm(forms.ModelForm):
class Meta:
model = Feedback
fields = '__all__'
widgets = {
'comments': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'user_agent': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'redux_state': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
}
class FeedbackAdmin(admin.ModelAdmin):
model = Feedback
form = FeedbackAdminForm
list_display = (
'player',
'get_type',
'created',
'comments',
)
list_filter = (
'type',
'created',
)
search_fields = (
'comments',
'user_agent',
'redux_state',
'player__username',
)
def get_type(self, obj):
return obj.get_type_display()
get_type.short_description = 'Type'
get_type.admin_order_field = 'type'
admin.site.register(Feedback, FeedbackAdmin)
| from django import forms
from django.contrib import admin
from feedback.models import Feedback
class FeedbackAdminForm(forms.ModelForm):
class Meta:
model = Feedback
fields = '__all__'
widgets = {
'comments': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'user_agent': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'redux_state': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
}
class FeedbackAdmin(admin.ModelAdmin):
model = Feedback
form = FeedbackAdminForm
list_display = (
'player',
'get_type',
'created',
'comments',
)
list_filter = (
'type',
'created',
)
search_fields = (
'comments',
'user_agent',
'redux_state',
'player__username',
)
ordering = (
'-created',
)
def get_type(self, obj):
return obj.get_type_display()
get_type.short_description = 'Type'
get_type.admin_order_field = 'type'
admin.site.register(Feedback, FeedbackAdmin)
| Order feedback by most recent | Order feedback by most recent
| Python | apache-2.0 | prattl/teamfinder,prattl/teamfinder,prattl/teamfinder,prattl/teamfinder | from django import forms
from django.contrib import admin
from feedback.models import Feedback
class FeedbackAdminForm(forms.ModelForm):
class Meta:
model = Feedback
fields = '__all__'
widgets = {
'comments': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'user_agent': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'redux_state': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
}
class FeedbackAdmin(admin.ModelAdmin):
model = Feedback
form = FeedbackAdminForm
list_display = (
'player',
'get_type',
'created',
'comments',
)
list_filter = (
'type',
'created',
)
search_fields = (
'comments',
'user_agent',
'redux_state',
'player__username',
)
+ ordering = (
+ '-created',
+ )
def get_type(self, obj):
return obj.get_type_display()
get_type.short_description = 'Type'
get_type.admin_order_field = 'type'
admin.site.register(Feedback, FeedbackAdmin)
| Order feedback by most recent | ## Code Before:
from django import forms
from django.contrib import admin
from feedback.models import Feedback
class FeedbackAdminForm(forms.ModelForm):
class Meta:
model = Feedback
fields = '__all__'
widgets = {
'comments': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'user_agent': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'redux_state': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
}
class FeedbackAdmin(admin.ModelAdmin):
model = Feedback
form = FeedbackAdminForm
list_display = (
'player',
'get_type',
'created',
'comments',
)
list_filter = (
'type',
'created',
)
search_fields = (
'comments',
'user_agent',
'redux_state',
'player__username',
)
def get_type(self, obj):
return obj.get_type_display()
get_type.short_description = 'Type'
get_type.admin_order_field = 'type'
admin.site.register(Feedback, FeedbackAdmin)
## Instruction:
Order feedback by most recent
## Code After:
from django import forms
from django.contrib import admin
from feedback.models import Feedback
class FeedbackAdminForm(forms.ModelForm):
class Meta:
model = Feedback
fields = '__all__'
widgets = {
'comments': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'user_agent': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'redux_state': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
}
class FeedbackAdmin(admin.ModelAdmin):
model = Feedback
form = FeedbackAdminForm
list_display = (
'player',
'get_type',
'created',
'comments',
)
list_filter = (
'type',
'created',
)
search_fields = (
'comments',
'user_agent',
'redux_state',
'player__username',
)
ordering = (
'-created',
)
def get_type(self, obj):
return obj.get_type_display()
get_type.short_description = 'Type'
get_type.admin_order_field = 'type'
admin.site.register(Feedback, FeedbackAdmin)
| from django import forms
from django.contrib import admin
from feedback.models import Feedback
class FeedbackAdminForm(forms.ModelForm):
class Meta:
model = Feedback
fields = '__all__'
widgets = {
'comments': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'user_agent': forms.Textarea(attrs={'cols': 80, 'rows': 5}),
'redux_state': forms.Textarea(attrs={'cols': 80, 'rows': 20}),
}
class FeedbackAdmin(admin.ModelAdmin):
model = Feedback
form = FeedbackAdminForm
list_display = (
'player',
'get_type',
'created',
'comments',
)
list_filter = (
'type',
'created',
)
search_fields = (
'comments',
'user_agent',
'redux_state',
'player__username',
)
+ ordering = (
+ '-created',
+ )
def get_type(self, obj):
return obj.get_type_display()
get_type.short_description = 'Type'
get_type.admin_order_field = 'type'
admin.site.register(Feedback, FeedbackAdmin) |
f2ab0c74986881e017199ac8a56dd09334a8b42b | magnum/tests/unit/template/test_template.py | magnum/tests/unit/template/test_template.py | import os
from glob import glob
from oslo_config import cfg
from yaml import load
from magnum.common import paths
from magnum.tests import base
cfg.CONF.register_opts([cfg.StrOpt('template_path',
default=paths.basedir_def('templates'),
help='Heat template path')])
class TestTemplate(base.TestCase):
def test_template_yaml(self):
for yml in [y for x in os.walk(cfg.CONF.template_path)
for y in glob(os.path.join(x[0], '*.yaml'))]:
with open(yml, 'r') as f:
yml_contents = f.read()
load(yml_contents)
| import os
import sys
from glob import glob
from oslo_config import cfg
from yaml import load
from magnum.common import paths
from magnum.tests import base
cfg.CONF.register_opts([cfg.StrOpt('template_path',
default=paths.basedir_def('templates'),
help='Heat template path')])
class TestTemplate(base.TestCase):
def test_template_yaml(self):
for yml in [y for x in os.walk(cfg.CONF.template_path)
for y in glob(os.path.join(x[0], '*.yaml'))]:
with open(yml, 'r') as f:
yml_contents = f.read()
try:
load(yml_contents)
except Exception:
error_msg = "file: %s: %s" % (yml, sys.exc_info()[1])
self.fail(error_msg)
| Improve yml template test case. | Improve yml template test case.
Print out yml file name when failed to loading yml.
Change-Id: Ie34282b91ec8101ffa2676e3144acf5a054578b0
| Python | apache-2.0 | ArchiFleKs/magnum,openstack/magnum,ArchiFleKs/magnum,openstack/magnum,jay-lau/magnum | import os
+ import sys
from glob import glob
from oslo_config import cfg
from yaml import load
from magnum.common import paths
from magnum.tests import base
cfg.CONF.register_opts([cfg.StrOpt('template_path',
default=paths.basedir_def('templates'),
help='Heat template path')])
class TestTemplate(base.TestCase):
def test_template_yaml(self):
for yml in [y for x in os.walk(cfg.CONF.template_path)
for y in glob(os.path.join(x[0], '*.yaml'))]:
with open(yml, 'r') as f:
yml_contents = f.read()
+ try:
- load(yml_contents)
+ load(yml_contents)
+ except Exception:
+ error_msg = "file: %s: %s" % (yml, sys.exc_info()[1])
+ self.fail(error_msg)
| Improve yml template test case. | ## Code Before:
import os
from glob import glob
from oslo_config import cfg
from yaml import load
from magnum.common import paths
from magnum.tests import base
cfg.CONF.register_opts([cfg.StrOpt('template_path',
default=paths.basedir_def('templates'),
help='Heat template path')])
class TestTemplate(base.TestCase):
def test_template_yaml(self):
for yml in [y for x in os.walk(cfg.CONF.template_path)
for y in glob(os.path.join(x[0], '*.yaml'))]:
with open(yml, 'r') as f:
yml_contents = f.read()
load(yml_contents)
## Instruction:
Improve yml template test case.
## Code After:
import os
import sys
from glob import glob
from oslo_config import cfg
from yaml import load
from magnum.common import paths
from magnum.tests import base
cfg.CONF.register_opts([cfg.StrOpt('template_path',
default=paths.basedir_def('templates'),
help='Heat template path')])
class TestTemplate(base.TestCase):
def test_template_yaml(self):
for yml in [y for x in os.walk(cfg.CONF.template_path)
for y in glob(os.path.join(x[0], '*.yaml'))]:
with open(yml, 'r') as f:
yml_contents = f.read()
try:
load(yml_contents)
except Exception:
error_msg = "file: %s: %s" % (yml, sys.exc_info()[1])
self.fail(error_msg)
| import os
+ import sys
from glob import glob
from oslo_config import cfg
from yaml import load
from magnum.common import paths
from magnum.tests import base
cfg.CONF.register_opts([cfg.StrOpt('template_path',
default=paths.basedir_def('templates'),
help='Heat template path')])
class TestTemplate(base.TestCase):
def test_template_yaml(self):
for yml in [y for x in os.walk(cfg.CONF.template_path)
for y in glob(os.path.join(x[0], '*.yaml'))]:
with open(yml, 'r') as f:
yml_contents = f.read()
+ try:
- load(yml_contents)
+ load(yml_contents)
? ++++
+ except Exception:
+ error_msg = "file: %s: %s" % (yml, sys.exc_info()[1])
+ self.fail(error_msg) |
43cd20e94c01e9364d8b0b2e50c701810d68b491 | adhocracy4/filters/views.py | adhocracy4/filters/views.py | from django.views import generic
class FilteredListView(generic.ListView):
"""List view with support for filtering and sorting via django-filter.
Usage:
Set filter_set to your django_filters.FilterSet definition.
Use view.filter.form in the template to access the filter form.
Note:
Always call super().get_queryset() when customizing get_queryset() to
include the filter functionality.
"""
filter_set = None
def filter(self):
return self.filter_set(
self.request.GET,
request=self.request
)
def get_queryset(self):
qs = self.filter().qs
return qs
| from django.views import generic
class FilteredListView(generic.ListView):
"""List view with support for filtering and sorting via django-filter.
Usage:
Set filter_set to your django_filters.FilterSet definition.
Use view.filter.form in the template to access the filter form.
Note:
Always call super().get_queryset() when customizing get_queryset() to
include the filter functionality.
"""
filter_set = None
def filter_kwargs(self):
default_kwargs = {
'data': self.request.GET,
'request': self.request,
'queryset': super().get_queryset()
}
return default_kwargs
def filter(self):
return self.filter_set(
**self.filter_kwargs()
)
def get_queryset(self):
qs = self.filter().qs
return qs
| Allow to override kwargs of filter | Allow to override kwargs of filter
| Python | agpl-3.0 | liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4 | from django.views import generic
class FilteredListView(generic.ListView):
"""List view with support for filtering and sorting via django-filter.
Usage:
Set filter_set to your django_filters.FilterSet definition.
Use view.filter.form in the template to access the filter form.
Note:
Always call super().get_queryset() when customizing get_queryset() to
include the filter functionality.
"""
filter_set = None
+ def filter_kwargs(self):
+ default_kwargs = {
+ 'data': self.request.GET,
+ 'request': self.request,
+ 'queryset': super().get_queryset()
+ }
+
+ return default_kwargs
+
def filter(self):
return self.filter_set(
+ **self.filter_kwargs()
- self.request.GET,
- request=self.request
)
def get_queryset(self):
qs = self.filter().qs
return qs
| Allow to override kwargs of filter | ## Code Before:
from django.views import generic
class FilteredListView(generic.ListView):
"""List view with support for filtering and sorting via django-filter.
Usage:
Set filter_set to your django_filters.FilterSet definition.
Use view.filter.form in the template to access the filter form.
Note:
Always call super().get_queryset() when customizing get_queryset() to
include the filter functionality.
"""
filter_set = None
def filter(self):
return self.filter_set(
self.request.GET,
request=self.request
)
def get_queryset(self):
qs = self.filter().qs
return qs
## Instruction:
Allow to override kwargs of filter
## Code After:
from django.views import generic
class FilteredListView(generic.ListView):
"""List view with support for filtering and sorting via django-filter.
Usage:
Set filter_set to your django_filters.FilterSet definition.
Use view.filter.form in the template to access the filter form.
Note:
Always call super().get_queryset() when customizing get_queryset() to
include the filter functionality.
"""
filter_set = None
def filter_kwargs(self):
default_kwargs = {
'data': self.request.GET,
'request': self.request,
'queryset': super().get_queryset()
}
return default_kwargs
def filter(self):
return self.filter_set(
**self.filter_kwargs()
)
def get_queryset(self):
qs = self.filter().qs
return qs
| from django.views import generic
class FilteredListView(generic.ListView):
"""List view with support for filtering and sorting via django-filter.
Usage:
Set filter_set to your django_filters.FilterSet definition.
Use view.filter.form in the template to access the filter form.
Note:
Always call super().get_queryset() when customizing get_queryset() to
include the filter functionality.
"""
filter_set = None
+ def filter_kwargs(self):
+ default_kwargs = {
+ 'data': self.request.GET,
+ 'request': self.request,
+ 'queryset': super().get_queryset()
+ }
+
+ return default_kwargs
+
def filter(self):
return self.filter_set(
+ **self.filter_kwargs()
- self.request.GET,
- request=self.request
)
def get_queryset(self):
qs = self.filter().qs
return qs |
bed66179633a86751a938c13b98f5b56c3c1cfc7 | fabfile.py | fabfile.py | from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty suckless-tools \
xautolock feh tmux neomutt mpd ncmpcpp vlc unp htop exa \
keepassx xdotool xclip rtorrent diffpdf xfce4 redshift-gtk')
def oh_my_zsh():
local('curl -L http://install.ohmyz.sh | sh')
local('cp ~/.zshrc.pre-oh-my-zsh ~/.zshrc')
local('chsh -s $(which shell)')
def install_vim():
local('mkdir -p ~/.vim/autoload ~/.vim/bundle')
local('curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim')
for bundle in vim_bundles:
local('git clone ' + bundle['git'] + ' ' + bundle['path'])
local('cd ~')
def update_vim():
for bundle in vim_bundles:
local('cd ' + bundle['path'] + ' && git pull')
local('cd ~')
| from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty suckless-tools \
xautolock feh tmux neomutt mpd ncmpcpp vlc unp htop exa \
keepassxc xdotool xclip rtorrent diffpdf xfce4 redshift-gtk \
graphviz')
def oh_my_zsh():
local('curl -L http://install.ohmyz.sh | sh')
local('cp ~/.zshrc.pre-oh-my-zsh ~/.zshrc')
local('chsh -s $(which shell)')
def install_vim():
local('mkdir -p ~/.vim/autoload ~/.vim/bundle')
local('curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim')
for bundle in vim_bundles:
local('git clone ' + bundle['git'] + ' ' + bundle['path'])
local('cd ~')
def update_vim():
for bundle in vim_bundles:
local('cd ' + bundle['path'] + ' && git pull')
local('cd ~')
| Add graphviz for converting dot to pdf | Add graphviz for converting dot to pdf
| Python | unlicense | spanners/dotfiles | from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty suckless-tools \
xautolock feh tmux neomutt mpd ncmpcpp vlc unp htop exa \
- keepassx xdotool xclip rtorrent diffpdf xfce4 redshift-gtk')
+ keepassxc xdotool xclip rtorrent diffpdf xfce4 redshift-gtk \
+ graphviz')
def oh_my_zsh():
local('curl -L http://install.ohmyz.sh | sh')
local('cp ~/.zshrc.pre-oh-my-zsh ~/.zshrc')
local('chsh -s $(which shell)')
def install_vim():
local('mkdir -p ~/.vim/autoload ~/.vim/bundle')
local('curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim')
for bundle in vim_bundles:
local('git clone ' + bundle['git'] + ' ' + bundle['path'])
local('cd ~')
def update_vim():
for bundle in vim_bundles:
local('cd ' + bundle['path'] + ' && git pull')
local('cd ~')
| Add graphviz for converting dot to pdf | ## Code Before:
from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty suckless-tools \
xautolock feh tmux neomutt mpd ncmpcpp vlc unp htop exa \
keepassx xdotool xclip rtorrent diffpdf xfce4 redshift-gtk')
def oh_my_zsh():
local('curl -L http://install.ohmyz.sh | sh')
local('cp ~/.zshrc.pre-oh-my-zsh ~/.zshrc')
local('chsh -s $(which shell)')
def install_vim():
local('mkdir -p ~/.vim/autoload ~/.vim/bundle')
local('curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim')
for bundle in vim_bundles:
local('git clone ' + bundle['git'] + ' ' + bundle['path'])
local('cd ~')
def update_vim():
for bundle in vim_bundles:
local('cd ' + bundle['path'] + ' && git pull')
local('cd ~')
## Instruction:
Add graphviz for converting dot to pdf
## Code After:
from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty suckless-tools \
xautolock feh tmux neomutt mpd ncmpcpp vlc unp htop exa \
keepassxc xdotool xclip rtorrent diffpdf xfce4 redshift-gtk \
graphviz')
def oh_my_zsh():
local('curl -L http://install.ohmyz.sh | sh')
local('cp ~/.zshrc.pre-oh-my-zsh ~/.zshrc')
local('chsh -s $(which shell)')
def install_vim():
local('mkdir -p ~/.vim/autoload ~/.vim/bundle')
local('curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim')
for bundle in vim_bundles:
local('git clone ' + bundle['git'] + ' ' + bundle['path'])
local('cd ~')
def update_vim():
for bundle in vim_bundles:
local('cd ' + bundle['path'] + ' && git pull')
local('cd ~')
| from fabric.api import local
vim_bundles = [
{
'git': 'git://github.com/fatih/vim-go.git',
'path': '~/.vim/bundle/vim-go'
}
]
def apt_get():
local('sudo apt-get update')
local('sudo apt-get upgrade')
# neovim instead of vim?
local('sudo apt-get install zsh vim wget curl kitty suckless-tools \
xautolock feh tmux neomutt mpd ncmpcpp vlc unp htop exa \
- keepassx xdotool xclip rtorrent diffpdf xfce4 redshift-gtk')
? ^^
+ keepassxc xdotool xclip rtorrent diffpdf xfce4 redshift-gtk \
? + ^^
+ graphviz')
def oh_my_zsh():
local('curl -L http://install.ohmyz.sh | sh')
local('cp ~/.zshrc.pre-oh-my-zsh ~/.zshrc')
local('chsh -s $(which shell)')
def install_vim():
local('mkdir -p ~/.vim/autoload ~/.vim/bundle')
local('curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim')
for bundle in vim_bundles:
local('git clone ' + bundle['git'] + ' ' + bundle['path'])
local('cd ~')
def update_vim():
for bundle in vim_bundles:
local('cd ' + bundle['path'] + ' && git pull')
local('cd ~') |
4ffb58466820cfb2569cf4d4837c8e48caed2c17 | seven23/api/permissions.py | seven23/api/permissions.py |
from itertools import chain
from rest_framework import permissions
from django.utils import timezone
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
return request.user.profile.valid_until > timezone.now() |
from itertools import chain
from rest_framework import permissions
from datetime import datetime
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
return request.user.profile.valid_until > datetime.today() | Fix issue with imezone on IsPaid Permission | Fix issue with imezone on IsPaid Permission
| Python | mit | sebastienbarbier/723e,sebastienbarbier/723e_server,sebastienbarbier/723e_server,sebastienbarbier/723e |
from itertools import chain
from rest_framework import permissions
- from django.utils import timezone
+ from datetime import datetime
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
- return request.user.profile.valid_until > timezone.now()
+ return request.user.profile.valid_until > datetime.today() | Fix issue with imezone on IsPaid Permission | ## Code Before:
from itertools import chain
from rest_framework import permissions
from django.utils import timezone
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
return request.user.profile.valid_until > timezone.now()
## Instruction:
Fix issue with imezone on IsPaid Permission
## Code After:
from itertools import chain
from rest_framework import permissions
from datetime import datetime
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
return request.user.profile.valid_until > datetime.today() |
from itertools import chain
from rest_framework import permissions
- from django.utils import timezone
+ from datetime import datetime
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
- return request.user.profile.valid_until > timezone.now()
? ^ ^^^^^^
+ return request.user.profile.valid_until > datetime.today()
? ++++ ^^ ^^^
|
3febcda544f372af01e9d2138c131f103ed45455 | app/soc/mapreduce/delete_gci_data.py | app/soc/mapreduce/delete_gci_data.py |
from google.appengine.ext import blobstore
from google.appengine.ext import db
from mapreduce import context
from mapreduce import operation
from soc.modules.gci.logic import profile as profile_logic
def process(student_info):
ctx = context.get()
params = ctx.mapreduce_spec.mapper.params
program_key_str = params['program_key']
program_key = db.Key.from_path('GCIProgram', program_key_str)
# We can skip the student info entity not belonging to the given program.
if student_info.program.key() != program_key:
return
entities, blobs = profile_logic.insertDummyData(student_info)
blobstore.delete(blobs)
for entity in entities:
yield operation.db.Put(entity)
yield operation.counters.Increment("profile dummy data inserted")
|
"""Mapreduce to insert dummy data for GCI student data for safe-harboring."""
from google.appengine.ext import blobstore
from google.appengine.ext import db
from mapreduce import context
from mapreduce import operation
from soc.modules.gci.logic import profile as profile_logic
def process(student_info):
ctx = context.get()
params = ctx.mapreduce_spec.mapper.params
program_key_str = params['program_key']
program_key = db.Key.from_path('GCIProgram', program_key_str)
# We can skip the student info entity not belonging to the given program.
if student_info.program.key() != program_key:
return
entities, blobs = profile_logic.insertDummyData(student_info)
blobstore.delete(blobs)
for entity in entities:
yield operation.db.Put(entity)
yield operation.counters.Increment("profile dummy data inserted")
| Update the docstring for the mapper to reflect what it does correctly. | Update the docstring for the mapper to reflect what it does correctly.
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | +
+ """Mapreduce to insert dummy data for GCI student data for safe-harboring."""
from google.appengine.ext import blobstore
from google.appengine.ext import db
from mapreduce import context
from mapreduce import operation
from soc.modules.gci.logic import profile as profile_logic
def process(student_info):
ctx = context.get()
params = ctx.mapreduce_spec.mapper.params
program_key_str = params['program_key']
program_key = db.Key.from_path('GCIProgram', program_key_str)
# We can skip the student info entity not belonging to the given program.
if student_info.program.key() != program_key:
return
entities, blobs = profile_logic.insertDummyData(student_info)
blobstore.delete(blobs)
for entity in entities:
yield operation.db.Put(entity)
yield operation.counters.Increment("profile dummy data inserted")
| Update the docstring for the mapper to reflect what it does correctly. | ## Code Before:
from google.appengine.ext import blobstore
from google.appengine.ext import db
from mapreduce import context
from mapreduce import operation
from soc.modules.gci.logic import profile as profile_logic
def process(student_info):
ctx = context.get()
params = ctx.mapreduce_spec.mapper.params
program_key_str = params['program_key']
program_key = db.Key.from_path('GCIProgram', program_key_str)
# We can skip the student info entity not belonging to the given program.
if student_info.program.key() != program_key:
return
entities, blobs = profile_logic.insertDummyData(student_info)
blobstore.delete(blobs)
for entity in entities:
yield operation.db.Put(entity)
yield operation.counters.Increment("profile dummy data inserted")
## Instruction:
Update the docstring for the mapper to reflect what it does correctly.
## Code After:
"""Mapreduce to insert dummy data for GCI student data for safe-harboring."""
from google.appengine.ext import blobstore
from google.appengine.ext import db
from mapreduce import context
from mapreduce import operation
from soc.modules.gci.logic import profile as profile_logic
def process(student_info):
ctx = context.get()
params = ctx.mapreduce_spec.mapper.params
program_key_str = params['program_key']
program_key = db.Key.from_path('GCIProgram', program_key_str)
# We can skip the student info entity not belonging to the given program.
if student_info.program.key() != program_key:
return
entities, blobs = profile_logic.insertDummyData(student_info)
blobstore.delete(blobs)
for entity in entities:
yield operation.db.Put(entity)
yield operation.counters.Increment("profile dummy data inserted")
| +
+ """Mapreduce to insert dummy data for GCI student data for safe-harboring."""
from google.appengine.ext import blobstore
from google.appengine.ext import db
from mapreduce import context
from mapreduce import operation
from soc.modules.gci.logic import profile as profile_logic
def process(student_info):
ctx = context.get()
params = ctx.mapreduce_spec.mapper.params
program_key_str = params['program_key']
program_key = db.Key.from_path('GCIProgram', program_key_str)
# We can skip the student info entity not belonging to the given program.
if student_info.program.key() != program_key:
return
entities, blobs = profile_logic.insertDummyData(student_info)
blobstore.delete(blobs)
for entity in entities:
yield operation.db.Put(entity)
yield operation.counters.Increment("profile dummy data inserted") |
42709afec9f2e2ed419365f61324ce0c8ff96423 | budget/forms.py | budget/forms.py | from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
| import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
| Split the start_date for better data entry (and Javascript date pickers). | Split the start_date for better data entry (and Javascript date pickers).
| Python | bsd-3-clause | jokimies/django-pj-budget,jokimies/django-pj-budget,toastdriven/django-budget,toastdriven/django-budget,jokimies/django-pj-budget | + import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
+ start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
+
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
| Split the start_date for better data entry (and Javascript date pickers). | ## Code Before:
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
## Instruction:
Split the start_date for better data entry (and Javascript date pickers).
## Code After:
import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save()
| + import datetime
from django import forms
from django.template.defaultfilters import slugify
from budget.models import Budget, BudgetEstimate
class BudgetForm(forms.ModelForm):
+ start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget)
+
class Meta:
model = Budget
fields = ('name', 'start_date')
def save(self):
if not self.instance.slug:
self.instance.slug = slugify(self.cleaned_data['name'])
super(BudgetForm, self).save()
class BudgetEstimateForm(forms.ModelForm):
class Meta:
model = BudgetEstimate
fields = ('category', 'amount')
def save(self, budget):
self.instance.budget = budget
super(BudgetEstimateForm, self).save() |
6d6709b0df05cccfd44bd68cea9fb30c4b6bd41f | asymmetric_jwt_auth/models.py | asymmetric_jwt_auth/models.py | from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
class PublicKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='public_keys')
key = models.TextField(help_text="The user's RSA public key")
comment = models.CharField(max_length=100, help_text="Comment describing this key", blank=True)
def save(self, *args, **kwargs):
key_parts = self.key.split(' ')
if len(key_parts) == 3 and not self.comment:
self.comment = key_parts.pop()
super(PublicKey, self).save(*args, **kwargs)
| from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from cryptography.hazmat.primitives.serialization import load_ssh_public_key
from cryptography.hazmat.backends import default_backend
def validate_public_key(value):
try:
load_ssh_public_key(value.encode('utf-8'), default_backend())
except Exception as e:
raise ValidationError('Public key is invalid: %s' % e)
class PublicKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='public_keys')
key = models.TextField(help_text="The user's RSA public key", validators=[validate_public_key])
comment = models.CharField(max_length=100, help_text="Comment describing this key", blank=True)
def save(self, *args, **kwargs):
key_parts = self.key.split(' ')
if len(key_parts) == 3 and not self.comment:
self.comment = key_parts.pop()
super(PublicKey, self).save(*args, **kwargs)
| Validate a public key before saving it | Validate a public key before saving it
| Python | isc | crgwbr/asymmetric_jwt_auth,crgwbr/asymmetric_jwt_auth | from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
+ from django.core.exceptions import ValidationError
+ from cryptography.hazmat.primitives.serialization import load_ssh_public_key
+ from cryptography.hazmat.backends import default_backend
+
+
+ def validate_public_key(value):
+ try:
+ load_ssh_public_key(value.encode('utf-8'), default_backend())
+ except Exception as e:
+ raise ValidationError('Public key is invalid: %s' % e)
class PublicKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='public_keys')
- key = models.TextField(help_text="The user's RSA public key")
+ key = models.TextField(help_text="The user's RSA public key", validators=[validate_public_key])
comment = models.CharField(max_length=100, help_text="Comment describing this key", blank=True)
def save(self, *args, **kwargs):
key_parts = self.key.split(' ')
if len(key_parts) == 3 and not self.comment:
self.comment = key_parts.pop()
super(PublicKey, self).save(*args, **kwargs)
| Validate a public key before saving it | ## Code Before:
from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
class PublicKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='public_keys')
key = models.TextField(help_text="The user's RSA public key")
comment = models.CharField(max_length=100, help_text="Comment describing this key", blank=True)
def save(self, *args, **kwargs):
key_parts = self.key.split(' ')
if len(key_parts) == 3 and not self.comment:
self.comment = key_parts.pop()
super(PublicKey, self).save(*args, **kwargs)
## Instruction:
Validate a public key before saving it
## Code After:
from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from cryptography.hazmat.primitives.serialization import load_ssh_public_key
from cryptography.hazmat.backends import default_backend
def validate_public_key(value):
try:
load_ssh_public_key(value.encode('utf-8'), default_backend())
except Exception as e:
raise ValidationError('Public key is invalid: %s' % e)
class PublicKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='public_keys')
key = models.TextField(help_text="The user's RSA public key", validators=[validate_public_key])
comment = models.CharField(max_length=100, help_text="Comment describing this key", blank=True)
def save(self, *args, **kwargs):
key_parts = self.key.split(' ')
if len(key_parts) == 3 and not self.comment:
self.comment = key_parts.pop()
super(PublicKey, self).save(*args, **kwargs)
| from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
+ from django.core.exceptions import ValidationError
+ from cryptography.hazmat.primitives.serialization import load_ssh_public_key
+ from cryptography.hazmat.backends import default_backend
+
+
+ def validate_public_key(value):
+ try:
+ load_ssh_public_key(value.encode('utf-8'), default_backend())
+ except Exception as e:
+ raise ValidationError('Public key is invalid: %s' % e)
class PublicKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='public_keys')
- key = models.TextField(help_text="The user's RSA public key")
+ key = models.TextField(help_text="The user's RSA public key", validators=[validate_public_key])
? ++++++++++++++++++++++++++++++++++
comment = models.CharField(max_length=100, help_text="Comment describing this key", blank=True)
def save(self, *args, **kwargs):
key_parts = self.key.split(' ')
if len(key_parts) == 3 and not self.comment:
self.comment = key_parts.pop()
super(PublicKey, self).save(*args, **kwargs) |
82973662e9cc8234e741d7595c95137df77296bb | tests/unit/utils/vt_test.py | tests/unit/utils/vt_test.py | '''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
tests.unit.utils.vt_test
~~~~~~~~~~~~~~~~~~~~~~~~
VirtualTerminal tests
'''
# Import python libs
import random
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import vt
class VTTestCase(TestCase):
def test_vt_size(self):
'''Confirm that the terminal size is being set'''
cols = random.choice(range(80, 250))
terminal = vt.Terminal(
'echo Foo!',
shell=True,
cols=cols
)
# First the assertion
self.assertEqual(
terminal.getwinsize(), (24, cols)
)
# Then wait for the terminal child to exit
terminal.wait()
if __name__ == '__main__':
from integration import run_tests
run_tests(VTTestCase, needs_daemon=False)
| '''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
tests.unit.utils.vt_test
~~~~~~~~~~~~~~~~~~~~~~~~
VirtualTerminal tests
'''
# Import python libs
import random
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import vt
class VTTestCase(TestCase):
def test_vt_size(self):
'''Confirm that the terminal size is being set'''
self.skipTest('The code is not mature enough. Test disabled.')
cols = random.choice(range(80, 250))
terminal = vt.Terminal(
'echo Foo!',
shell=True,
cols=cols
)
# First the assertion
self.assertEqual(
terminal.getwinsize(), (24, cols)
)
# Then wait for the terminal child to exit
terminal.wait()
if __name__ == '__main__':
from integration import run_tests
run_tests(VTTestCase, needs_daemon=False)
| Disable the VT test, the code ain't mature enough. | Disable the VT test, the code ain't mature enough.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
tests.unit.utils.vt_test
~~~~~~~~~~~~~~~~~~~~~~~~
VirtualTerminal tests
'''
# Import python libs
import random
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import vt
class VTTestCase(TestCase):
+
def test_vt_size(self):
'''Confirm that the terminal size is being set'''
+ self.skipTest('The code is not mature enough. Test disabled.')
cols = random.choice(range(80, 250))
terminal = vt.Terminal(
'echo Foo!',
shell=True,
cols=cols
)
# First the assertion
self.assertEqual(
terminal.getwinsize(), (24, cols)
)
# Then wait for the terminal child to exit
terminal.wait()
if __name__ == '__main__':
from integration import run_tests
run_tests(VTTestCase, needs_daemon=False)
| Disable the VT test, the code ain't mature enough. | ## Code Before:
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
tests.unit.utils.vt_test
~~~~~~~~~~~~~~~~~~~~~~~~
VirtualTerminal tests
'''
# Import python libs
import random
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import vt
class VTTestCase(TestCase):
def test_vt_size(self):
'''Confirm that the terminal size is being set'''
cols = random.choice(range(80, 250))
terminal = vt.Terminal(
'echo Foo!',
shell=True,
cols=cols
)
# First the assertion
self.assertEqual(
terminal.getwinsize(), (24, cols)
)
# Then wait for the terminal child to exit
terminal.wait()
if __name__ == '__main__':
from integration import run_tests
run_tests(VTTestCase, needs_daemon=False)
## Instruction:
Disable the VT test, the code ain't mature enough.
## Code After:
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
tests.unit.utils.vt_test
~~~~~~~~~~~~~~~~~~~~~~~~
VirtualTerminal tests
'''
# Import python libs
import random
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import vt
class VTTestCase(TestCase):
def test_vt_size(self):
'''Confirm that the terminal size is being set'''
self.skipTest('The code is not mature enough. Test disabled.')
cols = random.choice(range(80, 250))
terminal = vt.Terminal(
'echo Foo!',
shell=True,
cols=cols
)
# First the assertion
self.assertEqual(
terminal.getwinsize(), (24, cols)
)
# Then wait for the terminal child to exit
terminal.wait()
if __name__ == '__main__':
from integration import run_tests
run_tests(VTTestCase, needs_daemon=False)
| '''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
tests.unit.utils.vt_test
~~~~~~~~~~~~~~~~~~~~~~~~
VirtualTerminal tests
'''
# Import python libs
import random
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
from salt.utils import vt
class VTTestCase(TestCase):
+
def test_vt_size(self):
'''Confirm that the terminal size is being set'''
+ self.skipTest('The code is not mature enough. Test disabled.')
cols = random.choice(range(80, 250))
terminal = vt.Terminal(
'echo Foo!',
shell=True,
cols=cols
)
# First the assertion
self.assertEqual(
terminal.getwinsize(), (24, cols)
)
# Then wait for the terminal child to exit
terminal.wait()
if __name__ == '__main__':
from integration import run_tests
run_tests(VTTestCase, needs_daemon=False) |
7cf58ed386028a616c2083364d3f5c92e0c0ade3 | examples/hello_world/hello_world.py | examples/hello_world/hello_world.py |
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/foo')
def foo():
d = document.Document(data={
'foo': 'bar'
})
return d.to_json()
if __name__ == "__main__":
app.run()
|
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/hello')
def foo():
return document.Document(data={
'message': 'Hello World'
})
if __name__ == "__main__":
app.run()
| Update to hello world example | Update to hello world example
| Python | unlicense | thisissoon/Flask-HAL,thisissoon/Flask-HAL |
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
- @app.route('/foo')
+ @app.route('/hello')
def foo():
- d = document.Document(data={
+ return document.Document(data={
- 'foo': 'bar'
+ 'message': 'Hello World'
})
- return d.to_json()
if __name__ == "__main__":
app.run()
| Update to hello world example | ## Code Before:
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/foo')
def foo():
d = document.Document(data={
'foo': 'bar'
})
return d.to_json()
if __name__ == "__main__":
app.run()
## Instruction:
Update to hello world example
## Code After:
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
@app.route('/hello')
def foo():
return document.Document(data={
'message': 'Hello World'
})
if __name__ == "__main__":
app.run()
|
# Third Party Libs
from flask import Flask
from flask_hal import HAL, document
app = Flask(__name__)
HAL(app) # Initialise HAL
- @app.route('/foo')
? ^^
+ @app.route('/hello')
? ^^^^
def foo():
- d = document.Document(data={
? ^^^
+ return document.Document(data={
? ^^^^^^
- 'foo': 'bar'
+ 'message': 'Hello World'
})
- return d.to_json()
if __name__ == "__main__":
app.run() |
7b4f69971684bf2c5abfa50876583eb7c640bdac | kuulemma/views/feedback.py | kuulemma/views/feedback.py | from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
| from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
| Fix order of imports to comply with isort | Fix order of imports to comply with isort
| Python | agpl-3.0 | City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma | - from flask import Blueprint, abort, jsonify, request
+ from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
| Fix order of imports to comply with isort | ## Code Before:
from flask import Blueprint, abort, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
## Instruction:
Fix order of imports to comply with isort
## Code After:
from flask import abort, Blueprint, jsonify, request
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None
| - from flask import Blueprint, abort, jsonify, request
? -------
+ from flask import abort, Blueprint, jsonify, request
? +++++++
from flask.ext.mail import Message
from kuulemma.extensions import db, mail
from kuulemma.models import Feedback
from kuulemma.settings.base import FEEDBACK_RECIPIENTS
feedback = Blueprint(
name='feedback',
import_name=__name__,
url_prefix='/feedback'
)
@feedback.route('', methods=['POST'])
def create():
if not request.get_json():
return jsonify({'error': 'Data should be in json format'}), 400
if is_spam(request.get_json()):
abort(400)
content = request.get_json().get('content', '')
if not content:
return jsonify({'error': 'There was no content'}), 400
feedback = Feedback(content=content)
db.session.add(feedback)
db.session.commit()
message = Message(
sender='noreply@hel.fi',
recipients=FEEDBACK_RECIPIENTS,
charset='utf8',
subject='Kerrokantasi palaute',
body=feedback.content
)
mail.send(message)
return jsonify({
'feedback': {
'id': feedback.id,
'content': feedback.content
}
}), 201
def is_spam(json):
return json.get('hp') is not None |
9dd503c8d92518f9af4c599473626b98e56393e2 | typhon/tests/arts/test_arts.py | typhon/tests/arts/test_arts.py | import shutil
import pytest
from typhon import arts
class TestPlots:
"""Testing the plot functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call.
Note: This test is only run, if ARTS is found in PATH.
"""
arts_out = arts.run_arts(help=True)
assert arts_out.retcode == 0
| import shutil
import pytest
from typhon import arts
class TestARTS:
"""Testing the ARTS utility functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call.
Note: This test is only run, if ARTS is found in PATH.
"""
arts_out = arts.run_arts(help=True)
assert arts_out.retcode == 0
| Fix name and description of ARTS tests. | Fix name and description of ARTS tests. | Python | mit | atmtools/typhon,atmtools/typhon | import shutil
import pytest
from typhon import arts
- class TestPlots:
+ class TestARTS:
- """Testing the plot functions."""
+ """Testing the ARTS utility functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call.
Note: This test is only run, if ARTS is found in PATH.
"""
arts_out = arts.run_arts(help=True)
assert arts_out.retcode == 0
| Fix name and description of ARTS tests. | ## Code Before:
import shutil
import pytest
from typhon import arts
class TestPlots:
"""Testing the plot functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call.
Note: This test is only run, if ARTS is found in PATH.
"""
arts_out = arts.run_arts(help=True)
assert arts_out.retcode == 0
## Instruction:
Fix name and description of ARTS tests.
## Code After:
import shutil
import pytest
from typhon import arts
class TestARTS:
"""Testing the ARTS utility functions."""
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call.
Note: This test is only run, if ARTS is found in PATH.
"""
arts_out = arts.run_arts(help=True)
assert arts_out.retcode == 0
| import shutil
import pytest
from typhon import arts
- class TestPlots:
+ class TestARTS:
- """Testing the plot functions."""
? ^ ^
+ """Testing the ARTS utility functions."""
? ^^^^^^^^ ^ +
@pytest.mark.skipif(not shutil.which('arts'), reason='arts not in PATH')
def test_run_arts(self):
"""Test ARTS system call.
Note: This test is only run, if ARTS is found in PATH.
"""
arts_out = arts.run_arts(help=True)
assert arts_out.retcode == 0 |
34463dc84b4a277a962335a8f350267d18444401 | ovp_projects/serializers/apply.py | ovp_projects/serializers/apply.py | from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
fields = ['id', 'email', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user']
| from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
fields = ['id', 'email', 'username', 'phone', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user']
| Add username, email and phone on Apply serializer | Add username, email and phone on Apply serializer
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-projects,OpenVolunteeringPlatform/django-ovp-projects | from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
- fields = ['id', 'email', 'date', 'canceled', 'canceled_date', 'status', 'user']
+ fields = ['id', 'email', 'username', 'phone', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user']
| Add username, email and phone on Apply serializer | ## Code Before:
from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
fields = ['id', 'email', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user']
## Instruction:
Add username, email and phone on Apply serializer
## Code After:
from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
fields = ['id', 'email', 'username', 'phone', 'date', 'canceled', 'canceled_date', 'status', 'user']
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user']
| from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=False)
class Meta:
model = models.Apply
fields = ['username', 'email', 'phone', 'project', 'user']
class ApplyUpdateSerializer(serializers.ModelSerializer):
status = serializers.ChoiceField(choices=apply_status_choices)
class Meta:
model = models.Apply
fields = ['status']
class ApplyRetrieveSerializer(serializers.ModelSerializer):
user = UserApplyRetrieveSerializer()
status = serializers.SerializerMethodField()
class Meta:
model = models.Apply
- fields = ['id', 'email', 'date', 'canceled', 'canceled_date', 'status', 'user']
+ fields = ['id', 'email', 'username', 'phone', 'date', 'canceled', 'canceled_date', 'status', 'user']
? +++++++++++++++++++++
def get_status(self, object):
return object.get_status_display()
class ProjectAppliesSerializer(serializers.ModelSerializer):
user = UserPublicRetrieveSerializer()
class Meta:
model = models.Apply
fields = ['date', 'user'] |
d348c4f7c60b599e713eeeda7ed6806c5b1baae0 | tests/explorers_tests/test_additive_ou.py | tests/explorers_tests/test_additive_ou.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
import numpy as np
from chainerrl.explorers.additive_ou import AdditiveOU
class TestAdditiveOU(unittest.TestCase):
def test(self):
action_size = 3
def greedy_action_func():
return np.asarray([0] * action_size, dtype=np.float32)
explorer = AdditiveOU()
for t in range(100):
a = explorer.select_action(t, greedy_action_func)
print(t, a)
| from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
from chainer import testing
import numpy as np
from chainerrl.explorers.additive_ou import AdditiveOU
@testing.parameterize(*testing.product({
'action_size': [1, 3],
'sigma_type': ['scalar', 'ndarray'],
}))
class TestAdditiveOU(unittest.TestCase):
def test(self):
def greedy_action_func():
return np.asarray([0] * self.action_size, dtype=np.float32)
if self.sigma_type == 'scalar':
sigma = np.random.rand()
elif self.sigma_type == 'ndarray':
sigma = np.random.rand(self.action_size)
theta = np.random.rand()
explorer = AdditiveOU(theta=theta, sigma=sigma)
print('theta:', theta, 'sigma', sigma)
for t in range(100):
a = explorer.select_action(t, greedy_action_func)
print(t, a)
| Add tests of non-scalar sigma for AddtiveOU | Add tests of non-scalar sigma for AddtiveOU
| Python | mit | toslunar/chainerrl,toslunar/chainerrl | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
+ from chainer import testing
import numpy as np
from chainerrl.explorers.additive_ou import AdditiveOU
+ @testing.parameterize(*testing.product({
+ 'action_size': [1, 3],
+ 'sigma_type': ['scalar', 'ndarray'],
+ }))
class TestAdditiveOU(unittest.TestCase):
def test(self):
- action_size = 3
+ def greedy_action_func():
+ return np.asarray([0] * self.action_size, dtype=np.float32)
- def greedy_action_func():
- return np.asarray([0] * action_size, dtype=np.float32)
+ if self.sigma_type == 'scalar':
+ sigma = np.random.rand()
+ elif self.sigma_type == 'ndarray':
+ sigma = np.random.rand(self.action_size)
+ theta = np.random.rand()
- explorer = AdditiveOU()
+ explorer = AdditiveOU(theta=theta, sigma=sigma)
+ print('theta:', theta, 'sigma', sigma)
for t in range(100):
a = explorer.select_action(t, greedy_action_func)
print(t, a)
| Add tests of non-scalar sigma for AddtiveOU | ## Code Before:
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
import numpy as np
from chainerrl.explorers.additive_ou import AdditiveOU
class TestAdditiveOU(unittest.TestCase):
def test(self):
action_size = 3
def greedy_action_func():
return np.asarray([0] * action_size, dtype=np.float32)
explorer = AdditiveOU()
for t in range(100):
a = explorer.select_action(t, greedy_action_func)
print(t, a)
## Instruction:
Add tests of non-scalar sigma for AddtiveOU
## Code After:
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
from chainer import testing
import numpy as np
from chainerrl.explorers.additive_ou import AdditiveOU
@testing.parameterize(*testing.product({
'action_size': [1, 3],
'sigma_type': ['scalar', 'ndarray'],
}))
class TestAdditiveOU(unittest.TestCase):
def test(self):
def greedy_action_func():
return np.asarray([0] * self.action_size, dtype=np.float32)
if self.sigma_type == 'scalar':
sigma = np.random.rand()
elif self.sigma_type == 'ndarray':
sigma = np.random.rand(self.action_size)
theta = np.random.rand()
explorer = AdditiveOU(theta=theta, sigma=sigma)
print('theta:', theta, 'sigma', sigma)
for t in range(100):
a = explorer.select_action(t, greedy_action_func)
print(t, a)
| from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import unittest
+ from chainer import testing
import numpy as np
from chainerrl.explorers.additive_ou import AdditiveOU
+ @testing.parameterize(*testing.product({
+ 'action_size': [1, 3],
+ 'sigma_type': ['scalar', 'ndarray'],
+ }))
class TestAdditiveOU(unittest.TestCase):
def test(self):
- action_size = 3
+ def greedy_action_func():
+ return np.asarray([0] * self.action_size, dtype=np.float32)
- def greedy_action_func():
- return np.asarray([0] * action_size, dtype=np.float32)
+ if self.sigma_type == 'scalar':
+ sigma = np.random.rand()
+ elif self.sigma_type == 'ndarray':
+ sigma = np.random.rand(self.action_size)
+ theta = np.random.rand()
- explorer = AdditiveOU()
+ explorer = AdditiveOU(theta=theta, sigma=sigma)
+ print('theta:', theta, 'sigma', sigma)
for t in range(100):
a = explorer.select_action(t, greedy_action_func)
print(t, a) |
6aabf31aeb6766677f805bd4c0d5e4fc26522e53 | tests/test_memory.py | tests/test_memory.py | import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
| import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@pytest.mark.skipif(sys.implementation.version.minor > 7,
reason="Pympler 0.6 is broken under Python 3.8. See pympler#74")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
| Disable test_object_size under CPython 3.8 | tests/memory: Disable test_object_size under CPython 3.8
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
+ @pytest.mark.skipif(sys.implementation.version.minor > 7,
+ reason="Pympler 0.6 is broken under Python 3.8. See pympler#74")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
| Disable test_object_size under CPython 3.8 | ## Code Before:
import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
## Instruction:
Disable test_object_size under CPython 3.8
## Code After:
import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@pytest.mark.skipif(sys.implementation.version.minor > 7,
reason="Pympler 0.6 is broken under Python 3.8. See pympler#74")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
| import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
+ @pytest.mark.skipif(sys.implementation.version.minor > 7,
+ reason="Pympler 0.6 is broken under Python 3.8. See pympler#74")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None |
2995accb21d9b8c45792d12402470cfcf322d6a1 | models/phase3_eval/process_sparser.py | models/phase3_eval/process_sparser.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170210')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
xml_bytes = fh.read()
xml_bytes = xml_bytes.replace(b'hmsid', b'pmid')
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
| from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
| Update Sparser script for phase3 | Update Sparser script for phase3
| Python | bsd-2-clause | johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
- 'data/darpa/phase3_eval/sources/sparser-20170210')
+ 'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
+ print(fname)
xml_bytes = fh.read()
- xml_bytes = xml_bytes.replace(b'hmsid', b'pmid')
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
| Update Sparser script for phase3 | ## Code Before:
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170210')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
xml_bytes = fh.read()
xml_bytes = xml_bytes.replace(b'hmsid', b'pmid')
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
## Instruction:
Update Sparser script for phase3
## Code After:
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
print(fname)
xml_bytes = fh.read()
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder)
| from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
- 'data/darpa/phase3_eval/sources/sparser-20170210')
? ^^
+ 'data/darpa/phase3_eval/sources/sparser-20170330')
? ^^
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.xml'))
return fnames
def get_file_stmts(fname):
with open(fname, 'rb') as fh:
+ print(fname)
xml_bytes = fh.read()
- xml_bytes = xml_bytes.replace(b'hmsid', b'pmid')
sp = sparser.process_xml(xml_bytes)
if sp is None:
print('ERROR: Could not process %s' % fname.split('/')[-1])
print('----')
return []
return sp.statements
def read_stmts(folder):
fnames = get_file_names(folder)
all_stmts = []
for fname in fnames:
st = get_file_stmts(fname)
all_stmts += st
return all_stmts
if __name__ == '__main__':
stmts = read_stmts(base_folder) |
0167e246b74789cc0181b603520ec7f58ef7b5fe | pandas/core/api.py | pandas/core/api.py |
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
|
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
from pandas.core.config import get_option,set_option,reset_option,\
reset_options,describe_options
| Add new core.config API functions to the pandas top level module | ENH: Add new core.config API functions to the pandas top level module
| Python | bsd-3-clause | pandas-dev/pandas,GuessWhoSamFoo/pandas,TomAugspurger/pandas,toobaz/pandas,MJuddBooth/pandas,cython-testbed/pandas,TomAugspurger/pandas,nmartensen/pandas,cython-testbed/pandas,DGrady/pandas,DGrady/pandas,datapythonista/pandas,kdebrab/pandas,dsm054/pandas,Winand/pandas,linebp/pandas,dsm054/pandas,toobaz/pandas,jmmease/pandas,zfrenchee/pandas,jorisvandenbossche/pandas,cbertinato/pandas,linebp/pandas,harisbal/pandas,rs2/pandas,linebp/pandas,nmartensen/pandas,jmmease/pandas,jreback/pandas,linebp/pandas,cbertinato/pandas,zfrenchee/pandas,nmartensen/pandas,MJuddBooth/pandas,cython-testbed/pandas,amolkahat/pandas,jmmease/pandas,cython-testbed/pandas,GuessWhoSamFoo/pandas,harisbal/pandas,zfrenchee/pandas,jmmease/pandas,jorisvandenbossche/pandas,GuessWhoSamFoo/pandas,gfyoung/pandas,amolkahat/pandas,pandas-dev/pandas,jreback/pandas,kdebrab/pandas,MJuddBooth/pandas,datapythonista/pandas,pratapvardhan/pandas,amolkahat/pandas,Winand/pandas,cbertinato/pandas,jreback/pandas,gfyoung/pandas,pandas-dev/pandas,jreback/pandas,louispotok/pandas,linebp/pandas,toobaz/pandas,gfyoung/pandas,Winand/pandas,jorisvandenbossche/pandas,rs2/pandas,DGrady/pandas,dsm054/pandas,winklerand/pandas,kdebrab/pandas,winklerand/pandas,TomAugspurger/pandas,datapythonista/pandas,winklerand/pandas,kdebrab/pandas,zfrenchee/pandas,pratapvardhan/pandas,Winand/pandas,TomAugspurger/pandas,datapythonista/pandas,toobaz/pandas,DGrady/pandas,cbertinato/pandas,rs2/pandas,rs2/pandas,DGrady/pandas,toobaz/pandas,gfyoung/pandas,harisbal/pandas,jorisvandenbossche/pandas,nmartensen/pandas,louispotok/pandas,harisbal/pandas,amolkahat/pandas,linebp/pandas,cbertinato/pandas,Winand/pandas,louispotok/pandas,Winand/pandas,pratapvardhan/pandas,nmartensen/pandas,winklerand/pandas,DGrady/pandas,gfyoung/pandas,cython-testbed/pandas,pratapvardhan/pandas,louispotok/pandas,zfrenchee/pandas,MJuddBooth/pandas,GuessWhoSamFoo/pandas,pratapvardhan/pandas,winklerand/pandas,amolkahat/pandas,kdebrab/pandas,pandas-dev/pandas,harisbal/pandas,jreback/pandas,dsm054/pandas,GuessWhoSamFoo/pandas,MJuddBooth/pandas,jmmease/pandas,winklerand/pandas,dsm054/pandas,louispotok/pandas,jmmease/pandas,nmartensen/pandas |
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
+ from pandas.core.config import get_option,set_option,reset_option,\
+ reset_options,describe_options
+ | Add new core.config API functions to the pandas top level module | ## Code Before:
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
## Instruction:
Add new core.config API functions to the pandas top level module
## Code After:
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
from pandas.core.config import get_option,set_option,reset_option,\
reset_options,describe_options
|
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
set_eng_float_format)
from pandas.core.index import Index, Int64Index, MultiIndex
from pandas.core.series import Series, TimeSeries
from pandas.core.frame import DataFrame
from pandas.core.panel import Panel
from pandas.core.groupby import groupby
from pandas.core.reshape import (pivot_simple as pivot, get_dummies,
lreshape)
WidePanel = Panel
from pandas.tseries.offsets import DateOffset
from pandas.tseries.tools import to_datetime
from pandas.tseries.index import (DatetimeIndex, Timestamp,
date_range, bdate_range)
from pandas.tseries.period import Period, PeriodIndex
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
+
+ from pandas.core.config import get_option,set_option,reset_option,\
+ reset_options,describe_options |
7cbe2351c2ad93def98005597a24e21d878ea492 | flask_velox/mixins/http.py | flask_velox/mixins/http.py |
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
however this can be overridden using the ``code`` attribute.
Example
-------
.. code-block:: python
:linenos:
from flask.ext.velox.mixins.http import RedirectMixin
class MyView(RedirectMixin):
rule = 'some.url.rule'
code = 301
Attributes
----------
rule : str
Flask URL Rule passed into ``url_for``
code : int, optional
Status code to raise, defaults to ``302``
"""
code = 302
def pre_dispatch(self, *args, **kwargs):
""" If you wish to run an arbitrary piece of code before the
redirect is dispatched you can override this method which is
called before dispatch.
"""
pass
def get_url(self):
""" Return a generated url from ``rule`` attribute.
Returns
-------
str
Generated url
"""
try:
rule = self.rule
except AttributeError:
raise NotImplementedError('``rule`` attr must be defined.')
return url_for(rule)
def dispatch_request(self):
""" Dispatch the request, returning the redirect.func_closure
Returns
-------
werkzeug.wrappers.Response
Redirect response
"""
self.pre_dispatch()
return redirect(self.get_url(), code=getattr(self, 'code', 302))
|
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
however this can be overridden using the ``code`` attribute.
Example
-------
.. code-block:: python
:linenos:
from flask.ext.velox.mixins.http import RedirectMixin
class MyView(RedirectMixin):
rule = 'some.url.rule'
code = 301
Attributes
----------
rule : str
Flask URL Rule passed into ``url_for``
code : int, optional
Status code to raise, defaults to ``302``
"""
code = 302
def pre_dispatch(self, *args, **kwargs):
""" If you wish to run an arbitrary piece of code before the
redirect is dispatched you can override this method which is
called before dispatch.
"""
pass
def get_url(self):
""" Return a generated url from ``rule`` attribute.
Returns
-------
str
Generated url
"""
try:
rule = self.rule
except AttributeError:
raise NotImplementedError('``rule`` attr must be defined.')
return url_for(rule)
def dispatch_request(self, *args, **kwargs):
""" Dispatch the request, returning the redirect.func_closure
Returns
-------
werkzeug.wrappers.Response
Redirect response
"""
self.pre_dispatch()
return redirect(self.get_url(), code=getattr(self, 'code', 302))
| Allow RedirectMixin to work within flask-admin | Allow RedirectMixin to work within flask-admin
| Python | mit | thisissoon/Flask-Velox,thisissoon/Flask-Velox,jstacoder/Flask-Velox,jstacoder/Flask-Velox |
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
however this can be overridden using the ``code`` attribute.
Example
-------
.. code-block:: python
:linenos:
from flask.ext.velox.mixins.http import RedirectMixin
class MyView(RedirectMixin):
rule = 'some.url.rule'
code = 301
Attributes
----------
rule : str
Flask URL Rule passed into ``url_for``
code : int, optional
Status code to raise, defaults to ``302``
"""
code = 302
def pre_dispatch(self, *args, **kwargs):
""" If you wish to run an arbitrary piece of code before the
redirect is dispatched you can override this method which is
called before dispatch.
"""
pass
def get_url(self):
""" Return a generated url from ``rule`` attribute.
Returns
-------
str
Generated url
"""
try:
rule = self.rule
except AttributeError:
raise NotImplementedError('``rule`` attr must be defined.')
return url_for(rule)
- def dispatch_request(self):
+ def dispatch_request(self, *args, **kwargs):
""" Dispatch the request, returning the redirect.func_closure
Returns
-------
werkzeug.wrappers.Response
Redirect response
"""
self.pre_dispatch()
return redirect(self.get_url(), code=getattr(self, 'code', 302))
| Allow RedirectMixin to work within flask-admin | ## Code Before:
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
however this can be overridden using the ``code`` attribute.
Example
-------
.. code-block:: python
:linenos:
from flask.ext.velox.mixins.http import RedirectMixin
class MyView(RedirectMixin):
rule = 'some.url.rule'
code = 301
Attributes
----------
rule : str
Flask URL Rule passed into ``url_for``
code : int, optional
Status code to raise, defaults to ``302``
"""
code = 302
def pre_dispatch(self, *args, **kwargs):
""" If you wish to run an arbitrary piece of code before the
redirect is dispatched you can override this method which is
called before dispatch.
"""
pass
def get_url(self):
""" Return a generated url from ``rule`` attribute.
Returns
-------
str
Generated url
"""
try:
rule = self.rule
except AttributeError:
raise NotImplementedError('``rule`` attr must be defined.')
return url_for(rule)
def dispatch_request(self):
""" Dispatch the request, returning the redirect.func_closure
Returns
-------
werkzeug.wrappers.Response
Redirect response
"""
self.pre_dispatch()
return redirect(self.get_url(), code=getattr(self, 'code', 302))
## Instruction:
Allow RedirectMixin to work within flask-admin
## Code After:
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
however this can be overridden using the ``code`` attribute.
Example
-------
.. code-block:: python
:linenos:
from flask.ext.velox.mixins.http import RedirectMixin
class MyView(RedirectMixin):
rule = 'some.url.rule'
code = 301
Attributes
----------
rule : str
Flask URL Rule passed into ``url_for``
code : int, optional
Status code to raise, defaults to ``302``
"""
code = 302
def pre_dispatch(self, *args, **kwargs):
""" If you wish to run an arbitrary piece of code before the
redirect is dispatched you can override this method which is
called before dispatch.
"""
pass
def get_url(self):
""" Return a generated url from ``rule`` attribute.
Returns
-------
str
Generated url
"""
try:
rule = self.rule
except AttributeError:
raise NotImplementedError('``rule`` attr must be defined.')
return url_for(rule)
def dispatch_request(self, *args, **kwargs):
""" Dispatch the request, returning the redirect.func_closure
Returns
-------
werkzeug.wrappers.Response
Redirect response
"""
self.pre_dispatch()
return redirect(self.get_url(), code=getattr(self, 'code', 302))
|
from flask import url_for
from flask.views import View
from werkzeug.utils import redirect
class RedirectMixin(View):
""" Raise a HTTP Redirect, by default a 302 HTTP Status Code will be used
however this can be overridden using the ``code`` attribute.
Example
-------
.. code-block:: python
:linenos:
from flask.ext.velox.mixins.http import RedirectMixin
class MyView(RedirectMixin):
rule = 'some.url.rule'
code = 301
Attributes
----------
rule : str
Flask URL Rule passed into ``url_for``
code : int, optional
Status code to raise, defaults to ``302``
"""
code = 302
def pre_dispatch(self, *args, **kwargs):
""" If you wish to run an arbitrary piece of code before the
redirect is dispatched you can override this method which is
called before dispatch.
"""
pass
def get_url(self):
""" Return a generated url from ``rule`` attribute.
Returns
-------
str
Generated url
"""
try:
rule = self.rule
except AttributeError:
raise NotImplementedError('``rule`` attr must be defined.')
return url_for(rule)
- def dispatch_request(self):
+ def dispatch_request(self, *args, **kwargs):
? +++++++++++++++++
""" Dispatch the request, returning the redirect.func_closure
Returns
-------
werkzeug.wrappers.Response
Redirect response
"""
self.pre_dispatch()
return redirect(self.get_url(), code=getattr(self, 'code', 302)) |
f8b28c73e0bb46aaa760d4c4afadd75feacbe57a | tools/benchmark/benchmark_date_guessing.py | tools/benchmark/benchmark_date_guessing.py |
import os
import pytest
import sys
from mediawords.tm.guess_date import guess_date, McGuessDateException
def main():
if (len(sys.argv) < 2):
sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>')
exit()
directory = os.fsencode(sys.argv[1]).decode("utf-8")
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory,filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(
url='http://dont.know.the.date/some/path.html',
html=content
)
print(date_guess.date)
main()
|
import os
import sys
from mediawords.tm.guess_date import guess_date
def benchmark_date_guessing():
"""Benchmark Python date guessing code."""
if len(sys.argv) < 2:
sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
directory = sys.argv[1]
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory, filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(url='http://dont.know.the.date/some/path.html',
html=content)
print(date_guess.date)
if __name__ == '__main__':
benchmark_date_guessing()
| Clean up date guessing benchmarking code | Clean up date guessing benchmarking code
* Remove unused imports
* use sys.exit(message) instead of exit()
* Use Pythonic way to call main function (if __name__ == '__main__')
* Reformat code
* Avoid encoding / decoding things to / from UTF-8
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud |
import os
- import pytest
import sys
- from mediawords.tm.guess_date import guess_date, McGuessDateException
+ from mediawords.tm.guess_date import guess_date
- def main():
- if (len(sys.argv) < 2):
- sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>')
- exit()
- directory = os.fsencode(sys.argv[1]).decode("utf-8")
+ def benchmark_date_guessing():
+ """Benchmark Python date guessing code."""
+ if len(sys.argv) < 2:
+ sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
+
+ directory = sys.argv[1]
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
- fh = open(os.path.join(directory,filename))
+ fh = open(os.path.join(directory, filename))
content = fh.read()
print(filename + ": " + str(len(content)))
- date_guess = guess_date(
- url='http://dont.know.the.date/some/path.html',
+ date_guess = guess_date(url='http://dont.know.the.date/some/path.html',
+ html=content)
- html=content
- )
print(date_guess.date)
- main()
+ if __name__ == '__main__':
+ benchmark_date_guessing()
+ | Clean up date guessing benchmarking code | ## Code Before:
import os
import pytest
import sys
from mediawords.tm.guess_date import guess_date, McGuessDateException
def main():
if (len(sys.argv) < 2):
sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>')
exit()
directory = os.fsencode(sys.argv[1]).decode("utf-8")
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory,filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(
url='http://dont.know.the.date/some/path.html',
html=content
)
print(date_guess.date)
main()
## Instruction:
Clean up date guessing benchmarking code
## Code After:
import os
import sys
from mediawords.tm.guess_date import guess_date
def benchmark_date_guessing():
"""Benchmark Python date guessing code."""
if len(sys.argv) < 2:
sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
directory = sys.argv[1]
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
fh = open(os.path.join(directory, filename))
content = fh.read()
print(filename + ": " + str(len(content)))
date_guess = guess_date(url='http://dont.know.the.date/some/path.html',
html=content)
print(date_guess.date)
if __name__ == '__main__':
benchmark_date_guessing()
|
import os
- import pytest
import sys
- from mediawords.tm.guess_date import guess_date, McGuessDateException
? ----------------------
+ from mediawords.tm.guess_date import guess_date
- def main():
- if (len(sys.argv) < 2):
- sys.stderr.write('usage: ' + sys.argv[0] + ' <directory of html files>')
- exit()
- directory = os.fsencode(sys.argv[1]).decode("utf-8")
+ def benchmark_date_guessing():
+ """Benchmark Python date guessing code."""
+ if len(sys.argv) < 2:
+ sys.exit("Usage: %s <directory of html files>" % sys.argv[0])
+
+ directory = sys.argv[1]
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".txt"):
- fh = open(os.path.join(directory,filename))
+ fh = open(os.path.join(directory, filename))
? +
content = fh.read()
print(filename + ": " + str(len(content)))
- date_guess = guess_date(
- url='http://dont.know.the.date/some/path.html',
? ^^
+ date_guess = guess_date(url='http://dont.know.the.date/some/path.html',
? ++++++++++ + ^^^^^^^^^^^
+ html=content)
- html=content
- )
print(date_guess.date)
- main()
+
+ if __name__ == '__main__':
+ benchmark_date_guessing() |
6423bb87a392bf6f8abd3b04a0a1bab3181542a0 | run_time/src/gae_server/font_mapper.py | run_time/src/gae_server/font_mapper.py |
from os import path
tachyfont_major_version = 1
tachyfont_minor_version = 0
BASE_DIR = path.dirname(__file__)
def fontname_to_zipfile(fontname):
family_dir = ''
if fontname[0:10] == 'NotoSansJP':
family_dir = 'NotoSansJP/'
zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
return zip_path
|
from os import path
tachyfont_major_version = 1
tachyfont_minor_version = 0
BASE_DIR = path.dirname(__file__)
def fontname_to_zipfile(fontname):
family_dir = ''
if fontname[0:10] == 'NotoSansJP':
family_dir = 'NotoSansJP/'
elif fontname[0:8] == 'NotoSans':
family_dir = 'NotoSans/'
elif fontname[0:5] == 'Arimo':
family_dir = 'Arimo/'
zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
return zip_path
| Add support for NotoSans and Arimo. | Add support for NotoSans and Arimo. | Python | apache-2.0 | googlefonts/TachyFont,googlei18n/TachyFont,moyogo/tachyfont,googlei18n/TachyFont,moyogo/tachyfont,bstell/TachyFont,bstell/TachyFont,bstell/TachyFont,moyogo/tachyfont,googlefonts/TachyFont,googlei18n/TachyFont,googlei18n/TachyFont,googlei18n/TachyFont,moyogo/tachyfont,googlefonts/TachyFont,bstell/TachyFont,googlefonts/TachyFont,moyogo/tachyfont,bstell/TachyFont,googlefonts/TachyFont |
from os import path
tachyfont_major_version = 1
tachyfont_minor_version = 0
BASE_DIR = path.dirname(__file__)
def fontname_to_zipfile(fontname):
family_dir = ''
if fontname[0:10] == 'NotoSansJP':
family_dir = 'NotoSansJP/'
+ elif fontname[0:8] == 'NotoSans':
+ family_dir = 'NotoSans/'
+ elif fontname[0:5] == 'Arimo':
+ family_dir = 'Arimo/'
zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
return zip_path
| Add support for NotoSans and Arimo. | ## Code Before:
from os import path
tachyfont_major_version = 1
tachyfont_minor_version = 0
BASE_DIR = path.dirname(__file__)
def fontname_to_zipfile(fontname):
family_dir = ''
if fontname[0:10] == 'NotoSansJP':
family_dir = 'NotoSansJP/'
zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
return zip_path
## Instruction:
Add support for NotoSans and Arimo.
## Code After:
from os import path
tachyfont_major_version = 1
tachyfont_minor_version = 0
BASE_DIR = path.dirname(__file__)
def fontname_to_zipfile(fontname):
family_dir = ''
if fontname[0:10] == 'NotoSansJP':
family_dir = 'NotoSansJP/'
elif fontname[0:8] == 'NotoSans':
family_dir = 'NotoSans/'
elif fontname[0:5] == 'Arimo':
family_dir = 'Arimo/'
zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
return zip_path
|
from os import path
tachyfont_major_version = 1
tachyfont_minor_version = 0
BASE_DIR = path.dirname(__file__)
def fontname_to_zipfile(fontname):
family_dir = ''
if fontname[0:10] == 'NotoSansJP':
family_dir = 'NotoSansJP/'
+ elif fontname[0:8] == 'NotoSans':
+ family_dir = 'NotoSans/'
+ elif fontname[0:5] == 'Arimo':
+ family_dir = 'Arimo/'
zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
return zip_path
|
b167b1d9ff4278d142c1eeffc5ef443b11459cd9 | lamson-server/config/settings.py | lamson-server/config/settings.py | import logging
import pymongo
hostnames = ['kasm.clayadavis.net', 'openkasm.com', 'remixmail.com']
# You may add additional parameters such as `username' and `password' if your
# relay server requires authentication, `starttls' (boolean) or `ssl' (boolean)
# for secure connections.
relay_config = {'host': 'localhost', 'port': 8825}
#receiver_config = {'host': 'localhost', 'port': 8823}
#receiver_config = {'host': 'localhost', 'port': 25}
receiver_config = {'host': '0.0.0.0', 'port': 25}
handlers = ['app.handlers.kasm']
#router_defaults = {'host': '.+'}
hosts = ['localhost', '127.0.0.1'] + hostnames
router_defaults = {'host': '|'.join(['(%s)' % x for x in hosts])}
template_config = {'dir': 'app', 'module': 'templates'}
# the config/boot.py will turn these values into variables set in settings
db_client = pymongo.MongoClient()
db = db_client.kasm
| import logging
import pymongo
hostnames = ['kasm.clayadavis.net',
'openkasm.com',
#'remixmail.com',
]
# You may add additional parameters such as `username' and `password' if your
# relay server requires authentication, `starttls' (boolean) or `ssl' (boolean)
# for secure connections.
relay_config = {'host': 'localhost', 'port': 8825}
#receiver_config = {'host': 'localhost', 'port': 8823}
#receiver_config = {'host': 'localhost', 'port': 25}
receiver_config = {'host': '0.0.0.0', 'port': 25}
handlers = ['app.handlers.kasm']
#router_defaults = {'host': '.+'}
hosts = ['localhost', '127.0.0.1'] + hostnames
router_defaults = {'host': '|'.join(['(%s)' % x for x in hosts])}
template_config = {'dir': 'app', 'module': 'templates'}
# the config/boot.py will turn these values into variables set in settings
db_client = pymongo.MongoClient()
db = db_client.kasm
| Remove remixmail from hosts for now | Remove remixmail from hosts for now
| Python | mit | clayadavis/OpenKasm,clayadavis/OpenKasm | import logging
import pymongo
- hostnames = ['kasm.clayadavis.net', 'openkasm.com', 'remixmail.com']
+ hostnames = ['kasm.clayadavis.net',
+ 'openkasm.com',
+ #'remixmail.com',
+ ]
# You may add additional parameters such as `username' and `password' if your
# relay server requires authentication, `starttls' (boolean) or `ssl' (boolean)
# for secure connections.
relay_config = {'host': 'localhost', 'port': 8825}
#receiver_config = {'host': 'localhost', 'port': 8823}
#receiver_config = {'host': 'localhost', 'port': 25}
receiver_config = {'host': '0.0.0.0', 'port': 25}
handlers = ['app.handlers.kasm']
#router_defaults = {'host': '.+'}
hosts = ['localhost', '127.0.0.1'] + hostnames
router_defaults = {'host': '|'.join(['(%s)' % x for x in hosts])}
template_config = {'dir': 'app', 'module': 'templates'}
# the config/boot.py will turn these values into variables set in settings
db_client = pymongo.MongoClient()
db = db_client.kasm
| Remove remixmail from hosts for now | ## Code Before:
import logging
import pymongo
hostnames = ['kasm.clayadavis.net', 'openkasm.com', 'remixmail.com']
# You may add additional parameters such as `username' and `password' if your
# relay server requires authentication, `starttls' (boolean) or `ssl' (boolean)
# for secure connections.
relay_config = {'host': 'localhost', 'port': 8825}
#receiver_config = {'host': 'localhost', 'port': 8823}
#receiver_config = {'host': 'localhost', 'port': 25}
receiver_config = {'host': '0.0.0.0', 'port': 25}
handlers = ['app.handlers.kasm']
#router_defaults = {'host': '.+'}
hosts = ['localhost', '127.0.0.1'] + hostnames
router_defaults = {'host': '|'.join(['(%s)' % x for x in hosts])}
template_config = {'dir': 'app', 'module': 'templates'}
# the config/boot.py will turn these values into variables set in settings
db_client = pymongo.MongoClient()
db = db_client.kasm
## Instruction:
Remove remixmail from hosts for now
## Code After:
import logging
import pymongo
hostnames = ['kasm.clayadavis.net',
'openkasm.com',
#'remixmail.com',
]
# You may add additional parameters such as `username' and `password' if your
# relay server requires authentication, `starttls' (boolean) or `ssl' (boolean)
# for secure connections.
relay_config = {'host': 'localhost', 'port': 8825}
#receiver_config = {'host': 'localhost', 'port': 8823}
#receiver_config = {'host': 'localhost', 'port': 25}
receiver_config = {'host': '0.0.0.0', 'port': 25}
handlers = ['app.handlers.kasm']
#router_defaults = {'host': '.+'}
hosts = ['localhost', '127.0.0.1'] + hostnames
router_defaults = {'host': '|'.join(['(%s)' % x for x in hosts])}
template_config = {'dir': 'app', 'module': 'templates'}
# the config/boot.py will turn these values into variables set in settings
db_client = pymongo.MongoClient()
db = db_client.kasm
| import logging
import pymongo
- hostnames = ['kasm.clayadavis.net', 'openkasm.com', 'remixmail.com']
+ hostnames = ['kasm.clayadavis.net',
+ 'openkasm.com',
+ #'remixmail.com',
+ ]
# You may add additional parameters such as `username' and `password' if your
# relay server requires authentication, `starttls' (boolean) or `ssl' (boolean)
# for secure connections.
relay_config = {'host': 'localhost', 'port': 8825}
#receiver_config = {'host': 'localhost', 'port': 8823}
#receiver_config = {'host': 'localhost', 'port': 25}
receiver_config = {'host': '0.0.0.0', 'port': 25}
handlers = ['app.handlers.kasm']
#router_defaults = {'host': '.+'}
hosts = ['localhost', '127.0.0.1'] + hostnames
router_defaults = {'host': '|'.join(['(%s)' % x for x in hosts])}
template_config = {'dir': 'app', 'module': 'templates'}
# the config/boot.py will turn these values into variables set in settings
db_client = pymongo.MongoClient()
db = db_client.kasm |
b5ecb9c41aacea5450966a2539dc5a6af56ef168 | sale_order_mail_product_attach_prod_pack/__init__.py | sale_order_mail_product_attach_prod_pack/__init__.py |
import email_template
import sale
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
import sale
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| FIX sale order prod attach prod pack | FIX sale order prod attach prod pack
| Python | agpl-3.0 | ingadhoc/account-payment,ingadhoc/product,syci/ingadhoc-odoo-addons,ingadhoc/sale,ingadhoc/sale,jorsea/odoo-addons,ClearCorp/account-financial-tools,bmya/odoo-addons,HBEE/odoo-addons,bmya/odoo-addons,maljac/odoo-addons,maljac/odoo-addons,ingadhoc/odoo-addons,ingadhoc/partner,syci/ingadhoc-odoo-addons,dvitme/odoo-addons,bmya/odoo-addons,ingadhoc/account-financial-tools,ingadhoc/odoo-addons,ingadhoc/sale,syci/ingadhoc-odoo-addons,jorsea/odoo-addons,adhoc-dev/odoo-addons,adhoc-dev/odoo-addons,HBEE/odoo-addons,ingadhoc/odoo-addons,dvitme/odoo-addons,maljac/odoo-addons,sysadminmatmoz/ingadhoc,dvitme/odoo-addons,sysadminmatmoz/ingadhoc,ingadhoc/stock,ingadhoc/account-invoicing,adhoc-dev/account-financial-tools,ClearCorp/account-financial-tools,jorsea/odoo-addons,ingadhoc/account-analytic,sysadminmatmoz/ingadhoc,ingadhoc/product,adhoc-dev/odoo-addons,ingadhoc/sale,HBEE/odoo-addons,adhoc-dev/account-financial-tools |
- import email_template
import sale
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| FIX sale order prod attach prod pack | ## Code Before:
import email_template
import sale
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
## Instruction:
FIX sale order prod attach prod pack
## Code After:
import sale
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
- import email_template
import sale
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
73f7f64ff5a29d5fa007ad44f2d68c6dc2ae65d7 | sql/src/test/BugTracker/Tests/connect_crash.SF-1436626.py | sql/src/test/BugTracker/Tests/connect_crash.SF-1436626.py | import os, time
def main():
srvcmd = '%s --dbname "%s" --dbinit "include sql;"' % (os.getenv('MSERVER'),os.getenv('TSTDB'))
srv = os.popen(srvcmd, 'w')
time.sleep(10) # give server time to start
cltcmd = os.getenv('SQL_CLIENT')
clt = os.popen(cltcmd, 'w')
clt.write('select 1;\n')
clt.close()
srv.close()
main()
| import subprocess, os, time
def main():
srvcmd = '%s --dbname "%s" --dbinit "include sql;"' % (os.getenv('MSERVER'),os.getenv('TSTDB'))
srv = subprocess.Popen(srvcmd, shell = True, stdin = subprocess.PIPE)
time.sleep(10) # give server time to start
cltcmd = os.getenv('SQL_CLIENT')
clt = subprocess.Popen(cltcmd, shell = True, stdin = subprocess.PIPE)
clt.stdin.write('select 1;\n')
clt.communicate()
srv.communicate()
main()
| Use the subprocess module to start processes with pipes. This seems to fix the lack of output on Windows. | Use the subprocess module to start processes with pipes.
This seems to fix the lack of output on Windows.
| Python | mpl-2.0 | zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb,zyzyis/monetdb | - import os, time
+ import subprocess, os, time
def main():
srvcmd = '%s --dbname "%s" --dbinit "include sql;"' % (os.getenv('MSERVER'),os.getenv('TSTDB'))
- srv = os.popen(srvcmd, 'w')
+ srv = subprocess.Popen(srvcmd, shell = True, stdin = subprocess.PIPE)
time.sleep(10) # give server time to start
cltcmd = os.getenv('SQL_CLIENT')
- clt = os.popen(cltcmd, 'w')
+ clt = subprocess.Popen(cltcmd, shell = True, stdin = subprocess.PIPE)
- clt.write('select 1;\n')
+ clt.stdin.write('select 1;\n')
- clt.close()
- srv.close()
+ clt.communicate()
+ srv.communicate()
main()
| Use the subprocess module to start processes with pipes. This seems to fix the lack of output on Windows. | ## Code Before:
import os, time
def main():
srvcmd = '%s --dbname "%s" --dbinit "include sql;"' % (os.getenv('MSERVER'),os.getenv('TSTDB'))
srv = os.popen(srvcmd, 'w')
time.sleep(10) # give server time to start
cltcmd = os.getenv('SQL_CLIENT')
clt = os.popen(cltcmd, 'w')
clt.write('select 1;\n')
clt.close()
srv.close()
main()
## Instruction:
Use the subprocess module to start processes with pipes. This seems to fix the lack of output on Windows.
## Code After:
import subprocess, os, time
def main():
srvcmd = '%s --dbname "%s" --dbinit "include sql;"' % (os.getenv('MSERVER'),os.getenv('TSTDB'))
srv = subprocess.Popen(srvcmd, shell = True, stdin = subprocess.PIPE)
time.sleep(10) # give server time to start
cltcmd = os.getenv('SQL_CLIENT')
clt = subprocess.Popen(cltcmd, shell = True, stdin = subprocess.PIPE)
clt.stdin.write('select 1;\n')
clt.communicate()
srv.communicate()
main()
| - import os, time
+ import subprocess, os, time
def main():
srvcmd = '%s --dbname "%s" --dbinit "include sql;"' % (os.getenv('MSERVER'),os.getenv('TSTDB'))
- srv = os.popen(srvcmd, 'w')
+ srv = subprocess.Popen(srvcmd, shell = True, stdin = subprocess.PIPE)
time.sleep(10) # give server time to start
cltcmd = os.getenv('SQL_CLIENT')
- clt = os.popen(cltcmd, 'w')
+ clt = subprocess.Popen(cltcmd, shell = True, stdin = subprocess.PIPE)
- clt.write('select 1;\n')
+ clt.stdin.write('select 1;\n')
? ++++++
- clt.close()
- srv.close()
+ clt.communicate()
+ srv.communicate()
main() |
e4e4e8d5c3acf5851d33700f8b55aa2e1f9c33f2 | server/app/migrations/0003_region.py | server/app/migrations/0003_region.py | import os
import json
from django.db import migrations
from django.conf import settings
def dfs(apps, root, deep, superset=None, leaf=True):
Region = apps.get_model('app', 'Region')
if isinstance(root, dict):
for k, v in root.items():
s = dfs(apps, k, deep, superset, not v)
dfs(apps, v, deep + 1, s)
elif isinstance(root, list):
for k in root:
dfs(apps, k, deep, superset, True)
else:
region = Region(name=root, superset=superset, admin_level=deep, leaf=leaf)
region.save()
#print("{tab}{name}".format(tab="".join([" " * (deep-1)]), name=region.name))
return region
def add_region(apps, schema_editor):
if settings.TESTING:
data_file = "regions_for_test.json"
else:
data_file = "regions.txt"
regions = json.load(open(os.path.join(os.path.dirname(__file__),
data_file)))
#print("添加省份")
dfs(apps, regions, 1)
class Migration(migrations.Migration):
dependencies = [
('app', '0002_subject'),
]
operations = [
migrations.RunPython(add_region),
]
| import os
import json
from collections import OrderedDict
from django.db import migrations
from django.conf import settings
def dfs(apps, root, deep, superset=None, leaf=True):
Region = apps.get_model('app', 'Region')
if isinstance(root, dict):
for k, v in root.items():
s = dfs(apps, k, deep, superset, not v)
dfs(apps, v, deep + 1, s)
elif isinstance(root, list):
for k in root:
dfs(apps, k, deep, superset, True)
else:
region = Region(
name=root, superset=superset, admin_level=deep, leaf=leaf)
region.save()
return region
def add_region(apps, schema_editor):
if settings.TESTING:
data_file = "regions_for_test.json"
else:
data_file = "regions.txt"
regions = json.load(open(
os.path.join(os.path.dirname(__file__), data_file)),
object_pairs_hook=OrderedDict)
dfs(apps, regions, 1)
class Migration(migrations.Migration):
dependencies = [
('app', '0002_subject'),
]
operations = [
migrations.RunPython(add_region),
]
| Make ID of regions be definite. | SERVER-242: Make ID of regions be definite.
| Python | mit | malaonline/Server,malaonline/iOS,malaonline/Android,malaonline/Android,malaonline/iOS,malaonline/Android,malaonline/Server,malaonline/Server,malaonline/iOS,malaonline/Server | import os
import json
+ from collections import OrderedDict
from django.db import migrations
from django.conf import settings
def dfs(apps, root, deep, superset=None, leaf=True):
Region = apps.get_model('app', 'Region')
if isinstance(root, dict):
for k, v in root.items():
s = dfs(apps, k, deep, superset, not v)
dfs(apps, v, deep + 1, s)
elif isinstance(root, list):
for k in root:
dfs(apps, k, deep, superset, True)
else:
+ region = Region(
- region = Region(name=root, superset=superset, admin_level=deep, leaf=leaf)
+ name=root, superset=superset, admin_level=deep, leaf=leaf)
region.save()
- #print("{tab}{name}".format(tab="".join([" " * (deep-1)]), name=region.name))
return region
def add_region(apps, schema_editor):
if settings.TESTING:
data_file = "regions_for_test.json"
else:
data_file = "regions.txt"
- regions = json.load(open(os.path.join(os.path.dirname(__file__),
- data_file)))
- #print("添加省份")
+ regions = json.load(open(
+ os.path.join(os.path.dirname(__file__), data_file)),
+ object_pairs_hook=OrderedDict)
dfs(apps, regions, 1)
class Migration(migrations.Migration):
dependencies = [
('app', '0002_subject'),
]
operations = [
migrations.RunPython(add_region),
]
| Make ID of regions be definite. | ## Code Before:
import os
import json
from django.db import migrations
from django.conf import settings
def dfs(apps, root, deep, superset=None, leaf=True):
Region = apps.get_model('app', 'Region')
if isinstance(root, dict):
for k, v in root.items():
s = dfs(apps, k, deep, superset, not v)
dfs(apps, v, deep + 1, s)
elif isinstance(root, list):
for k in root:
dfs(apps, k, deep, superset, True)
else:
region = Region(name=root, superset=superset, admin_level=deep, leaf=leaf)
region.save()
#print("{tab}{name}".format(tab="".join([" " * (deep-1)]), name=region.name))
return region
def add_region(apps, schema_editor):
if settings.TESTING:
data_file = "regions_for_test.json"
else:
data_file = "regions.txt"
regions = json.load(open(os.path.join(os.path.dirname(__file__),
data_file)))
#print("添加省份")
dfs(apps, regions, 1)
class Migration(migrations.Migration):
dependencies = [
('app', '0002_subject'),
]
operations = [
migrations.RunPython(add_region),
]
## Instruction:
Make ID of regions be definite.
## Code After:
import os
import json
from collections import OrderedDict
from django.db import migrations
from django.conf import settings
def dfs(apps, root, deep, superset=None, leaf=True):
Region = apps.get_model('app', 'Region')
if isinstance(root, dict):
for k, v in root.items():
s = dfs(apps, k, deep, superset, not v)
dfs(apps, v, deep + 1, s)
elif isinstance(root, list):
for k in root:
dfs(apps, k, deep, superset, True)
else:
region = Region(
name=root, superset=superset, admin_level=deep, leaf=leaf)
region.save()
return region
def add_region(apps, schema_editor):
if settings.TESTING:
data_file = "regions_for_test.json"
else:
data_file = "regions.txt"
regions = json.load(open(
os.path.join(os.path.dirname(__file__), data_file)),
object_pairs_hook=OrderedDict)
dfs(apps, regions, 1)
class Migration(migrations.Migration):
dependencies = [
('app', '0002_subject'),
]
operations = [
migrations.RunPython(add_region),
]
| import os
import json
+ from collections import OrderedDict
from django.db import migrations
from django.conf import settings
def dfs(apps, root, deep, superset=None, leaf=True):
Region = apps.get_model('app', 'Region')
if isinstance(root, dict):
for k, v in root.items():
s = dfs(apps, k, deep, superset, not v)
dfs(apps, v, deep + 1, s)
elif isinstance(root, list):
for k in root:
dfs(apps, k, deep, superset, True)
else:
+ region = Region(
- region = Region(name=root, superset=superset, admin_level=deep, leaf=leaf)
? ------ - ^^^^^^^
+ name=root, superset=superset, admin_level=deep, leaf=leaf)
? ^^^^^^
region.save()
- #print("{tab}{name}".format(tab="".join([" " * (deep-1)]), name=region.name))
return region
def add_region(apps, schema_editor):
if settings.TESTING:
data_file = "regions_for_test.json"
else:
data_file = "regions.txt"
- regions = json.load(open(os.path.join(os.path.dirname(__file__),
- data_file)))
- #print("添加省份")
+ regions = json.load(open(
+ os.path.join(os.path.dirname(__file__), data_file)),
+ object_pairs_hook=OrderedDict)
dfs(apps, regions, 1)
class Migration(migrations.Migration):
dependencies = [
('app', '0002_subject'),
]
operations = [
migrations.RunPython(add_region),
] |
4da5ebbad11a5c5cdbea307668657d843d6d1005 | cotracker/checkouts/middleware.py | cotracker/checkouts/middleware.py | """Checkouts application middleware"""
import logging
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's built-in AuthenticationMiddleware
in the project settings.
"""
def process_request(self, request):
"""Organizes info from each request and saves it to a log."""
context = {
'ip': request.META['REMOTE_ADDR'],
'method': request.method,
'path': request.path,
'user': request.user.username,
'useragent': request.META['HTTP_USER_AGENT'],
}
# Fall-back if the user is not recognized
if not request.user.is_authenticated():
context['user'] = 'anonymous'
template = "%(user)s@%(ip)s: %(method)s %(path)s \"%(useragent)s\""
logger.info(template % context)
| """Checkouts application middleware"""
import logging
import time
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's built-in AuthenticationMiddleware
in the project settings.
"""
def collect_request_details(self, request):
"""Gathers information of interest from the request and returns a dictionary."""
context = {
'ip': request.META['REMOTE_ADDR'],
'method': request.method,
'path': request.path,
'user': request.user.username,
'useragent': request.META['HTTP_USER_AGENT'],
}
# Fall-back if the user is not recognized
if not request.user.is_authenticated():
context['user'] = 'anonymous'
return context
def process_request(self, request):
"""Captures the current time and saves it to the request object."""
request._analytics_start_time = time.time()
def process_response(self, request, response):
"""Organizes info from each request/response and saves it to a log."""
context = self.collect_request_details(request)
context['status'] = response.status_code
if not request._analytics_start_time:
logger.error("Unable to provide timing data for request")
context['elapsed'] = -1.0
else:
elapsed = (time.time() - request._analytics_start_time) * 1000.0
context['elapsed'] = elapsed
template = "%(user)s@%(ip)s: %(method)s %(path)s %(elapsed)fms %(status)s \"%(useragent)s\""
logger.info(template % context)
return response
| Enhance analytics with timing and status code info | Enhance analytics with timing and status code info
| Python | mit | eallrich/checkniner,eallrich/checkniner,eallrich/checkniner | """Checkouts application middleware"""
import logging
+ import time
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's built-in AuthenticationMiddleware
in the project settings.
"""
- def process_request(self, request):
+ def collect_request_details(self, request):
- """Organizes info from each request and saves it to a log."""
+ """Gathers information of interest from the request and returns a dictionary."""
context = {
'ip': request.META['REMOTE_ADDR'],
'method': request.method,
'path': request.path,
'user': request.user.username,
'useragent': request.META['HTTP_USER_AGENT'],
}
# Fall-back if the user is not recognized
if not request.user.is_authenticated():
context['user'] = 'anonymous'
+ return context
+
+ def process_request(self, request):
+ """Captures the current time and saves it to the request object."""
+ request._analytics_start_time = time.time()
+
+ def process_response(self, request, response):
+ """Organizes info from each request/response and saves it to a log."""
+ context = self.collect_request_details(request)
+ context['status'] = response.status_code
+
+ if not request._analytics_start_time:
+ logger.error("Unable to provide timing data for request")
+ context['elapsed'] = -1.0
+ else:
+ elapsed = (time.time() - request._analytics_start_time) * 1000.0
+ context['elapsed'] = elapsed
+
- template = "%(user)s@%(ip)s: %(method)s %(path)s \"%(useragent)s\""
+ template = "%(user)s@%(ip)s: %(method)s %(path)s %(elapsed)fms %(status)s \"%(useragent)s\""
logger.info(template % context)
+
+ return response
| Enhance analytics with timing and status code info | ## Code Before:
"""Checkouts application middleware"""
import logging
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's built-in AuthenticationMiddleware
in the project settings.
"""
def process_request(self, request):
"""Organizes info from each request and saves it to a log."""
context = {
'ip': request.META['REMOTE_ADDR'],
'method': request.method,
'path': request.path,
'user': request.user.username,
'useragent': request.META['HTTP_USER_AGENT'],
}
# Fall-back if the user is not recognized
if not request.user.is_authenticated():
context['user'] = 'anonymous'
template = "%(user)s@%(ip)s: %(method)s %(path)s \"%(useragent)s\""
logger.info(template % context)
## Instruction:
Enhance analytics with timing and status code info
## Code After:
"""Checkouts application middleware"""
import logging
import time
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's built-in AuthenticationMiddleware
in the project settings.
"""
def collect_request_details(self, request):
"""Gathers information of interest from the request and returns a dictionary."""
context = {
'ip': request.META['REMOTE_ADDR'],
'method': request.method,
'path': request.path,
'user': request.user.username,
'useragent': request.META['HTTP_USER_AGENT'],
}
# Fall-back if the user is not recognized
if not request.user.is_authenticated():
context['user'] = 'anonymous'
return context
def process_request(self, request):
"""Captures the current time and saves it to the request object."""
request._analytics_start_time = time.time()
def process_response(self, request, response):
"""Organizes info from each request/response and saves it to a log."""
context = self.collect_request_details(request)
context['status'] = response.status_code
if not request._analytics_start_time:
logger.error("Unable to provide timing data for request")
context['elapsed'] = -1.0
else:
elapsed = (time.time() - request._analytics_start_time) * 1000.0
context['elapsed'] = elapsed
template = "%(user)s@%(ip)s: %(method)s %(path)s %(elapsed)fms %(status)s \"%(useragent)s\""
logger.info(template % context)
return response
| """Checkouts application middleware"""
import logging
+ import time
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's built-in AuthenticationMiddleware
in the project settings.
"""
- def process_request(self, request):
? ^^ ^^^
+ def collect_request_details(self, request):
? ^ +++ ^ ++++++++
- """Organizes info from each request and saves it to a log."""
+ """Gathers information of interest from the request and returns a dictionary."""
context = {
'ip': request.META['REMOTE_ADDR'],
'method': request.method,
'path': request.path,
'user': request.user.username,
'useragent': request.META['HTTP_USER_AGENT'],
}
# Fall-back if the user is not recognized
if not request.user.is_authenticated():
context['user'] = 'anonymous'
+ return context
+
+ def process_request(self, request):
+ """Captures the current time and saves it to the request object."""
+ request._analytics_start_time = time.time()
+
+ def process_response(self, request, response):
+ """Organizes info from each request/response and saves it to a log."""
+ context = self.collect_request_details(request)
+ context['status'] = response.status_code
+
+ if not request._analytics_start_time:
+ logger.error("Unable to provide timing data for request")
+ context['elapsed'] = -1.0
+ else:
+ elapsed = (time.time() - request._analytics_start_time) * 1000.0
+ context['elapsed'] = elapsed
+
- template = "%(user)s@%(ip)s: %(method)s %(path)s \"%(useragent)s\""
+ template = "%(user)s@%(ip)s: %(method)s %(path)s %(elapsed)fms %(status)s \"%(useragent)s\""
? +++++++++++++++++++++++++
logger.info(template % context)
+
+ return response |
cf336ac17ba194066517ab93ea7079415adba0c2 | sum.py | sum.py | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
sum_view.insert(edit, 0, file_text)
sum_view.set_read_only(True)
sum_view.set_scratch(True)
| import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
numbers = []
for s in file_text.split():
if s.isdigit():
numbers.append(int(s))
else:
try:
numbers.append(float(s))
except ValueError:
pass
result = sum(numbers)
sum_view.insert(edit, 0, str(result))
sum_view.set_read_only(True)
sum_view.set_scratch(True)
| Add up all ints (base 10) and floats in the file | Add up all ints (base 10) and floats in the file
| Python | mit | jbrudvik/sublime-sum,jbrudvik/sublime-sum | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
+
+ numbers = []
+ for s in file_text.split():
+ if s.isdigit():
+ numbers.append(int(s))
+ else:
+ try:
+ numbers.append(float(s))
+ except ValueError:
+ pass
+
+ result = sum(numbers)
- sum_view.insert(edit, 0, file_text)
+ sum_view.insert(edit, 0, str(result))
sum_view.set_read_only(True)
sum_view.set_scratch(True)
| Add up all ints (base 10) and floats in the file | ## Code Before:
import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
sum_view.insert(edit, 0, file_text)
sum_view.set_read_only(True)
sum_view.set_scratch(True)
## Instruction:
Add up all ints (base 10) and floats in the file
## Code After:
import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
numbers = []
for s in file_text.split():
if s.isdigit():
numbers.append(int(s))
else:
try:
numbers.append(float(s))
except ValueError:
pass
result = sum(numbers)
sum_view.insert(edit, 0, str(result))
sum_view.set_read_only(True)
sum_view.set_scratch(True)
| import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
+
+ numbers = []
+ for s in file_text.split():
+ if s.isdigit():
+ numbers.append(int(s))
+ else:
+ try:
+ numbers.append(float(s))
+ except ValueError:
+ pass
+
+ result = sum(numbers)
- sum_view.insert(edit, 0, file_text)
? ^^ -----
+ sum_view.insert(edit, 0, str(result))
? ^^^^^^^^ +
sum_view.set_read_only(True)
sum_view.set_scratch(True) |
fd6c7386cfdaa5fb97a428b323fc1f9b17f9f02c | tests/test_helpers.py | tests/test_helpers.py | import pandas
from sharepa.helpers import pretty_print
from sharepa.helpers import source_counts
def test_pretty_print():
some_stuff = '{"Dusty": "Rhodes"}'
pretty_print(some_stuff)
def test_source_counts():
all_counts = source_counts()
assert isinstance(all_counts, pandas.core.frame.DataFrame)
| import vcr
import pandas
import pytest
from sharepa.search import ShareSearch
from sharepa.helpers import pretty_print
from sharepa.helpers import source_counts
@vcr.use_cassette('tests/vcr/simple_execute.yaml')
def test_pretty_print():
my_search = ShareSearch()
result = my_search.execute()
the_dict = result.to_dict()
try:
pretty_print(the_dict)
except:
pytest.fail("Unexpected exception!!")
def test_source_counts():
all_counts = source_counts()
assert isinstance(all_counts, pandas.core.frame.DataFrame)
| Add pytest fail check on raising pretty print exeption | Add pytest fail check on raising pretty print exeption
| Python | mit | CenterForOpenScience/sharepa,fabianvf/sharepa,samanehsan/sharepa,erinspace/sharepa | + import vcr
import pandas
+ import pytest
+ from sharepa.search import ShareSearch
from sharepa.helpers import pretty_print
from sharepa.helpers import source_counts
+ @vcr.use_cassette('tests/vcr/simple_execute.yaml')
def test_pretty_print():
- some_stuff = '{"Dusty": "Rhodes"}'
- pretty_print(some_stuff)
+ my_search = ShareSearch()
+ result = my_search.execute()
+ the_dict = result.to_dict()
+ try:
+ pretty_print(the_dict)
+ except:
+ pytest.fail("Unexpected exception!!")
def test_source_counts():
all_counts = source_counts()
assert isinstance(all_counts, pandas.core.frame.DataFrame)
| Add pytest fail check on raising pretty print exeption | ## Code Before:
import pandas
from sharepa.helpers import pretty_print
from sharepa.helpers import source_counts
def test_pretty_print():
some_stuff = '{"Dusty": "Rhodes"}'
pretty_print(some_stuff)
def test_source_counts():
all_counts = source_counts()
assert isinstance(all_counts, pandas.core.frame.DataFrame)
## Instruction:
Add pytest fail check on raising pretty print exeption
## Code After:
import vcr
import pandas
import pytest
from sharepa.search import ShareSearch
from sharepa.helpers import pretty_print
from sharepa.helpers import source_counts
@vcr.use_cassette('tests/vcr/simple_execute.yaml')
def test_pretty_print():
my_search = ShareSearch()
result = my_search.execute()
the_dict = result.to_dict()
try:
pretty_print(the_dict)
except:
pytest.fail("Unexpected exception!!")
def test_source_counts():
all_counts = source_counts()
assert isinstance(all_counts, pandas.core.frame.DataFrame)
| + import vcr
import pandas
+ import pytest
+ from sharepa.search import ShareSearch
from sharepa.helpers import pretty_print
from sharepa.helpers import source_counts
+ @vcr.use_cassette('tests/vcr/simple_execute.yaml')
def test_pretty_print():
- some_stuff = '{"Dusty": "Rhodes"}'
- pretty_print(some_stuff)
+ my_search = ShareSearch()
+ result = my_search.execute()
+ the_dict = result.to_dict()
+ try:
+ pretty_print(the_dict)
+ except:
+ pytest.fail("Unexpected exception!!")
def test_source_counts():
all_counts = source_counts()
assert isinstance(all_counts, pandas.core.frame.DataFrame) |
e9edc74a28442c2f519d4a3c40253f7844c9ca2f | thecut/authorship/forms.py | thecut/authorship/forms.py | from __future__ import absolute_import, unicode_literals
class AuthorshipFormMixin(object):
"""Set the ``created_by`` and ``updated_by`` fields on a model.
This form requires that a property, ``self.user`` be set to an instance of
:py:class`~django.contrib.auth.models.User` before the ``save()`` method is
called.
"""
def save(self, *args, **kwargs):
self.instance.updated_by = self.user
if not self.instance.pk:
self.instance.created_by = self.user
return super(AuthorshipFormMixin, self).save(*args, **kwargs)
| from __future__ import absolute_import, unicode_literals
class AuthorshipFormMixin(object):
"""Set the ``created_by`` and ``updated_by`` fields on a model.
Requires that a ``User`` instance be passed in to the constructor. Views
that inherit from ``AuthorshipViewMixin`` automatically pass this in.
"""
def __init__(self, user, *args, **kwargs):
self.user = user
super(AuthorshipFormMixin, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
self.instance.updated_by = self.user
if not self.instance.pk:
self.instance.created_by = self.user
return super(AuthorshipFormMixin, self).save(*args, **kwargs)
| Set the `self.user` property on the `AuthorshipFormMixin`. | Set the `self.user` property on the `AuthorshipFormMixin`.
| Python | apache-2.0 | thecut/thecut-authorship | from __future__ import absolute_import, unicode_literals
class AuthorshipFormMixin(object):
"""Set the ``created_by`` and ``updated_by`` fields on a model.
+ Requires that a ``User`` instance be passed in to the constructor. Views
+ that inherit from ``AuthorshipViewMixin`` automatically pass this in.
- This form requires that a property, ``self.user`` be set to an instance of
- :py:class`~django.contrib.auth.models.User` before the ``save()`` method is
- called.
"""
+
+ def __init__(self, user, *args, **kwargs):
+ self.user = user
+ super(AuthorshipFormMixin, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
self.instance.updated_by = self.user
if not self.instance.pk:
self.instance.created_by = self.user
return super(AuthorshipFormMixin, self).save(*args, **kwargs)
| Set the `self.user` property on the `AuthorshipFormMixin`. | ## Code Before:
from __future__ import absolute_import, unicode_literals
class AuthorshipFormMixin(object):
"""Set the ``created_by`` and ``updated_by`` fields on a model.
This form requires that a property, ``self.user`` be set to an instance of
:py:class`~django.contrib.auth.models.User` before the ``save()`` method is
called.
"""
def save(self, *args, **kwargs):
self.instance.updated_by = self.user
if not self.instance.pk:
self.instance.created_by = self.user
return super(AuthorshipFormMixin, self).save(*args, **kwargs)
## Instruction:
Set the `self.user` property on the `AuthorshipFormMixin`.
## Code After:
from __future__ import absolute_import, unicode_literals
class AuthorshipFormMixin(object):
"""Set the ``created_by`` and ``updated_by`` fields on a model.
Requires that a ``User`` instance be passed in to the constructor. Views
that inherit from ``AuthorshipViewMixin`` automatically pass this in.
"""
def __init__(self, user, *args, **kwargs):
self.user = user
super(AuthorshipFormMixin, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
self.instance.updated_by = self.user
if not self.instance.pk:
self.instance.created_by = self.user
return super(AuthorshipFormMixin, self).save(*args, **kwargs)
| from __future__ import absolute_import, unicode_literals
class AuthorshipFormMixin(object):
"""Set the ``created_by`` and ``updated_by`` fields on a model.
+ Requires that a ``User`` instance be passed in to the constructor. Views
+ that inherit from ``AuthorshipViewMixin`` automatically pass this in.
- This form requires that a property, ``self.user`` be set to an instance of
- :py:class`~django.contrib.auth.models.User` before the ``save()`` method is
- called.
"""
+
+ def __init__(self, user, *args, **kwargs):
+ self.user = user
+ super(AuthorshipFormMixin, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
self.instance.updated_by = self.user
if not self.instance.pk:
self.instance.created_by = self.user
return super(AuthorshipFormMixin, self).save(*args, **kwargs) |
074dcf9c822827c6609dc11c0047aa79dd8c1ad8 | tests/test_cli.py | tests/test_cli.py |
"""Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
class TestYoutrack_cli(unittest.TestCase):
def test_improt(self):
import pyutrack
def test_command_line_interface(self):
runner = CliRunner()
result = runner.invoke(cli.cli)
assert result.exit_code == 0
assert 'YouTrack' in result.output
help_result = runner.invoke(cli.cli, ['--help'])
assert help_result.exit_code == 0
assert 'Show this message and exit.' in help_result.output
| """Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
from tests import PyutrackTest
class TestYoutrack_cli(PyutrackTest):
def test_improt(self):
import pyutrack
def test_command_line_interface(self):
runner = CliRunner()
result = runner.invoke(cli.cli)
assert result.exit_code == 0
assert 'YouTrack' in result.output
help_result = runner.invoke(cli.cli, ['--help'])
assert help_result.exit_code == 0
assert 'Show this message and exit.' in help_result.output
| Set cli tests to base test class | Set cli tests to base test class
| Python | mit | alisaifee/pyutrack,alisaifee/pyutrack | -
"""Tests for `pyutrack` package."""
-
import unittest
from click.testing import CliRunner
from pyutrack import cli
+ from tests import PyutrackTest
- class TestYoutrack_cli(unittest.TestCase):
+ class TestYoutrack_cli(PyutrackTest):
-
def test_improt(self):
import pyutrack
def test_command_line_interface(self):
runner = CliRunner()
result = runner.invoke(cli.cli)
assert result.exit_code == 0
assert 'YouTrack' in result.output
help_result = runner.invoke(cli.cli, ['--help'])
assert help_result.exit_code == 0
assert 'Show this message and exit.' in help_result.output
| Set cli tests to base test class | ## Code Before:
"""Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
class TestYoutrack_cli(unittest.TestCase):
def test_improt(self):
import pyutrack
def test_command_line_interface(self):
runner = CliRunner()
result = runner.invoke(cli.cli)
assert result.exit_code == 0
assert 'YouTrack' in result.output
help_result = runner.invoke(cli.cli, ['--help'])
assert help_result.exit_code == 0
assert 'Show this message and exit.' in help_result.output
## Instruction:
Set cli tests to base test class
## Code After:
"""Tests for `pyutrack` package."""
import unittest
from click.testing import CliRunner
from pyutrack import cli
from tests import PyutrackTest
class TestYoutrack_cli(PyutrackTest):
def test_improt(self):
import pyutrack
def test_command_line_interface(self):
runner = CliRunner()
result = runner.invoke(cli.cli)
assert result.exit_code == 0
assert 'YouTrack' in result.output
help_result = runner.invoke(cli.cli, ['--help'])
assert help_result.exit_code == 0
assert 'Show this message and exit.' in help_result.output
| -
"""Tests for `pyutrack` package."""
-
import unittest
from click.testing import CliRunner
from pyutrack import cli
+ from tests import PyutrackTest
- class TestYoutrack_cli(unittest.TestCase):
? -- ^^^^^ ----
+ class TestYoutrack_cli(PyutrackTest):
? ++ ^^^^
-
def test_improt(self):
import pyutrack
def test_command_line_interface(self):
runner = CliRunner()
result = runner.invoke(cli.cli)
assert result.exit_code == 0
assert 'YouTrack' in result.output
help_result = runner.invoke(cli.cli, ['--help'])
assert help_result.exit_code == 0
assert 'Show this message and exit.' in help_result.output |
3ff9f60e857c9ffbd7c72c53403ae7bf3afecab8 | test/features/steps/system.py | test/features/steps/system.py | from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
pass
else:
try:
binary = subprocess.check_output(["which", exe]).decode('utf8').strip()
except:
pass
if binary is None:
print(
"Skipping scenario", context.scenario,
"(executable %s not found)" % exe,
file = sys.stderr
)
context.scenario.skip("The executable '%s' is not present" % exe)
else:
print(
"Found executable '%s' at '%s'" % (exe, binary),
file = sys.stderr
)
@then('{exe} is a static executable')
def step_impl(ctx, exe):
if sys.platform.lower().startswith('darwin'):
context.scenario.skip("Static runtime linking is not supported on OS X")
if sys.platform.startswith('win'):
lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n')
for line in lines:
if 'msvcrt' in line.lower():
assert False, 'Found MSVCRT: %s' % line
else:
out = subprocess.check_output(["file", exe]).decode('utf8')
assert 'statically linked' in out, "Not a static executable: %s" % out
| from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
pass
else:
try:
binary = subprocess.check_output(["which", exe]).decode('utf8').strip()
except:
pass
if binary is None:
print(
"Skipping scenario", context.scenario,
"(executable %s not found)" % exe,
file = sys.stderr
)
context.scenario.skip("The executable '%s' is not present" % exe)
else:
print(
"Found executable '%s' at '%s'" % (exe, binary),
file = sys.stderr
)
@then('{exe} is a static executable')
def step_impl(ctx, exe):
if sys.platform.lower().startswith('darwin'):
ctx.scenario.skip("Static runtime linking is not supported on OS X")
return
if sys.platform.startswith('win'):
lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n')
for line in lines:
if 'msvcrt' in line.lower():
assert False, 'Found MSVCRT: %s' % line
else:
out = subprocess.check_output(["file", exe]).decode('utf8')
assert 'statically linked' in out, "Not a static executable: %s" % out
| Fix OS X test skip. | tests.features: Fix OS X test skip.
| Python | bsd-3-clause | hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure,hotgloupi/configure | from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
pass
else:
try:
binary = subprocess.check_output(["which", exe]).decode('utf8').strip()
except:
pass
if binary is None:
print(
"Skipping scenario", context.scenario,
"(executable %s not found)" % exe,
file = sys.stderr
)
context.scenario.skip("The executable '%s' is not present" % exe)
else:
print(
"Found executable '%s' at '%s'" % (exe, binary),
file = sys.stderr
)
@then('{exe} is a static executable')
def step_impl(ctx, exe):
if sys.platform.lower().startswith('darwin'):
- context.scenario.skip("Static runtime linking is not supported on OS X")
+ ctx.scenario.skip("Static runtime linking is not supported on OS X")
+ return
if sys.platform.startswith('win'):
lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n')
for line in lines:
if 'msvcrt' in line.lower():
assert False, 'Found MSVCRT: %s' % line
else:
out = subprocess.check_output(["file", exe]).decode('utf8')
assert 'statically linked' in out, "Not a static executable: %s" % out
| Fix OS X test skip. | ## Code Before:
from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
pass
else:
try:
binary = subprocess.check_output(["which", exe]).decode('utf8').strip()
except:
pass
if binary is None:
print(
"Skipping scenario", context.scenario,
"(executable %s not found)" % exe,
file = sys.stderr
)
context.scenario.skip("The executable '%s' is not present" % exe)
else:
print(
"Found executable '%s' at '%s'" % (exe, binary),
file = sys.stderr
)
@then('{exe} is a static executable')
def step_impl(ctx, exe):
if sys.platform.lower().startswith('darwin'):
context.scenario.skip("Static runtime linking is not supported on OS X")
if sys.platform.startswith('win'):
lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n')
for line in lines:
if 'msvcrt' in line.lower():
assert False, 'Found MSVCRT: %s' % line
else:
out = subprocess.check_output(["file", exe]).decode('utf8')
assert 'statically linked' in out, "Not a static executable: %s" % out
## Instruction:
Fix OS X test skip.
## Code After:
from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
pass
else:
try:
binary = subprocess.check_output(["which", exe]).decode('utf8').strip()
except:
pass
if binary is None:
print(
"Skipping scenario", context.scenario,
"(executable %s not found)" % exe,
file = sys.stderr
)
context.scenario.skip("The executable '%s' is not present" % exe)
else:
print(
"Found executable '%s' at '%s'" % (exe, binary),
file = sys.stderr
)
@then('{exe} is a static executable')
def step_impl(ctx, exe):
if sys.platform.lower().startswith('darwin'):
ctx.scenario.skip("Static runtime linking is not supported on OS X")
return
if sys.platform.startswith('win'):
lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n')
for line in lines:
if 'msvcrt' in line.lower():
assert False, 'Found MSVCRT: %s' % line
else:
out = subprocess.check_output(["file", exe]).decode('utf8')
assert 'statically linked' in out, "Not a static executable: %s" % out
| from __future__ import print_function
import sys
import subprocess
import os
@given('a system executable {exe}')
def step_impl(context, exe):
binary = None
if sys.platform.startswith('win'):
try:
binary = subprocess.check_output(["where", exe]).decode('utf8').strip()
except:
pass
else:
try:
binary = subprocess.check_output(["which", exe]).decode('utf8').strip()
except:
pass
if binary is None:
print(
"Skipping scenario", context.scenario,
"(executable %s not found)" % exe,
file = sys.stderr
)
context.scenario.skip("The executable '%s' is not present" % exe)
else:
print(
"Found executable '%s' at '%s'" % (exe, binary),
file = sys.stderr
)
@then('{exe} is a static executable')
def step_impl(ctx, exe):
if sys.platform.lower().startswith('darwin'):
- context.scenario.skip("Static runtime linking is not supported on OS X")
? -- - -
+ ctx.scenario.skip("Static runtime linking is not supported on OS X")
+ return
if sys.platform.startswith('win'):
lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n')
for line in lines:
if 'msvcrt' in line.lower():
assert False, 'Found MSVCRT: %s' % line
else:
out = subprocess.check_output(["file", exe]).decode('utf8')
assert 'statically linked' in out, "Not a static executable: %s" % out
|
24093369bb1dbd2e9034db9425920ffdc14ee070 | abusehelper/bots/abusech/feodoccbot.py | abusehelper/bots/abusech/feodoccbot.py |
from abusehelper.core import bot
from . import host_or_ip, split_description, AbuseCHFeedBot
class FeodoCcBot(AbuseCHFeedBot):
feed_type = "c&c"
feed_name = "feodo c&c"
feeds = bot.ListParam(default=["https://feodotracker.abuse.ch/feodotracker.rss"])
# The timestamp in the title appears to be the firstseen timestamp,
# skip including it as the "source time".
parse_title = None
def parse_description(self, description):
got_version = False
for key, value in split_description(description):
if key == "version":
yield "malware family", "feodo." + value.strip().lower()
got_version = True
elif key == "host":
yield host_or_ip(value)
if not got_version:
yield "malware family", "feodo"
if __name__ == "__main__":
FeodoCcBot.from_command_line().execute()
|
from abusehelper.core import bot
from . import host_or_ip, split_description, AbuseCHFeedBot
class FeodoCcBot(AbuseCHFeedBot):
feed_type = "c&c"
feed_name = "feodo c&c"
feeds = bot.ListParam(default=["https://feodotracker.abuse.ch/feodotracker.rss"])
# The timestamp in the title appears to be the firstseen timestamp,
# skip including it as the "source time".
parse_title = None
def parse_description(self, description):
got_version = False
for key, value in split_description(description):
if key == "version":
yield "malware family", "feodo." + value.strip().lower()
got_version = True
elif key == "status":
yield "status", value
elif key == "host":
yield host_or_ip(value)
if not got_version:
yield "malware family", "feodo"
if __name__ == "__main__":
FeodoCcBot.from_command_line().execute()
| Include status information in abuse.ch's Feodo C&C feed | Include status information in abuse.ch's Feodo C&C feed
| Python | mit | abusesa/abusehelper |
from abusehelper.core import bot
from . import host_or_ip, split_description, AbuseCHFeedBot
class FeodoCcBot(AbuseCHFeedBot):
feed_type = "c&c"
feed_name = "feodo c&c"
feeds = bot.ListParam(default=["https://feodotracker.abuse.ch/feodotracker.rss"])
# The timestamp in the title appears to be the firstseen timestamp,
# skip including it as the "source time".
parse_title = None
def parse_description(self, description):
got_version = False
for key, value in split_description(description):
if key == "version":
yield "malware family", "feodo." + value.strip().lower()
got_version = True
+ elif key == "status":
+ yield "status", value
elif key == "host":
yield host_or_ip(value)
if not got_version:
yield "malware family", "feodo"
if __name__ == "__main__":
FeodoCcBot.from_command_line().execute()
| Include status information in abuse.ch's Feodo C&C feed | ## Code Before:
from abusehelper.core import bot
from . import host_or_ip, split_description, AbuseCHFeedBot
class FeodoCcBot(AbuseCHFeedBot):
feed_type = "c&c"
feed_name = "feodo c&c"
feeds = bot.ListParam(default=["https://feodotracker.abuse.ch/feodotracker.rss"])
# The timestamp in the title appears to be the firstseen timestamp,
# skip including it as the "source time".
parse_title = None
def parse_description(self, description):
got_version = False
for key, value in split_description(description):
if key == "version":
yield "malware family", "feodo." + value.strip().lower()
got_version = True
elif key == "host":
yield host_or_ip(value)
if not got_version:
yield "malware family", "feodo"
if __name__ == "__main__":
FeodoCcBot.from_command_line().execute()
## Instruction:
Include status information in abuse.ch's Feodo C&C feed
## Code After:
from abusehelper.core import bot
from . import host_or_ip, split_description, AbuseCHFeedBot
class FeodoCcBot(AbuseCHFeedBot):
feed_type = "c&c"
feed_name = "feodo c&c"
feeds = bot.ListParam(default=["https://feodotracker.abuse.ch/feodotracker.rss"])
# The timestamp in the title appears to be the firstseen timestamp,
# skip including it as the "source time".
parse_title = None
def parse_description(self, description):
got_version = False
for key, value in split_description(description):
if key == "version":
yield "malware family", "feodo." + value.strip().lower()
got_version = True
elif key == "status":
yield "status", value
elif key == "host":
yield host_or_ip(value)
if not got_version:
yield "malware family", "feodo"
if __name__ == "__main__":
FeodoCcBot.from_command_line().execute()
|
from abusehelper.core import bot
from . import host_or_ip, split_description, AbuseCHFeedBot
class FeodoCcBot(AbuseCHFeedBot):
feed_type = "c&c"
feed_name = "feodo c&c"
feeds = bot.ListParam(default=["https://feodotracker.abuse.ch/feodotracker.rss"])
# The timestamp in the title appears to be the firstseen timestamp,
# skip including it as the "source time".
parse_title = None
def parse_description(self, description):
got_version = False
for key, value in split_description(description):
if key == "version":
yield "malware family", "feodo." + value.strip().lower()
got_version = True
+ elif key == "status":
+ yield "status", value
elif key == "host":
yield host_or_ip(value)
if not got_version:
yield "malware family", "feodo"
if __name__ == "__main__":
FeodoCcBot.from_command_line().execute() |
00cffc4197d393e6fc8d8031a4d1f8e78d5c532c | IPython/config/profile/pysh/ipython_config.py | IPython/config/profile/pysh/ipython_config.py | c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
c.InteractiveShell.prompt_in1 = r'\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
c.InteractiveShell.prompt_in2 = r'\C_Green|\C_LightGreen\D\C_Green> '
c.InteractiveShell.prompt_out = r'<\#> '
c.InteractiveShell.prompts_pad_left = True
c.InteractiveShell.separate_in = ''
c.InteractiveShell.separate_out = ''
c.InteractiveShell.separate_out2 = ''
c.PrefilterManager.multi_line_specials = True
lines = """
%rehashx
"""
# You have to make sure that attributes that are containers already
# exist before using them. Simple assigning a new list will override
# all previous values.
if hasattr(app, 'exec_lines'):
app.exec_lines.append(lines)
else:
app.exec_lines = [lines]
| c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
c.PromptManager.out_template = r'<\#> '
c.PromptManager.justify = True
c.InteractiveShell.separate_in = ''
c.InteractiveShell.separate_out = ''
c.InteractiveShell.separate_out2 = ''
c.PrefilterManager.multi_line_specials = True
lines = """
%rehashx
"""
# You have to make sure that attributes that are containers already
# exist before using them. Simple assigning a new list will override
# all previous values.
if hasattr(app, 'exec_lines'):
app.exec_lines.append(lines)
else:
app.exec_lines = [lines]
| Update prompt config for pysh profile. | Update prompt config for pysh profile.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
- c.InteractiveShell.prompt_in1 = r'\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
- c.InteractiveShell.prompt_in2 = r'\C_Green|\C_LightGreen\D\C_Green> '
- c.InteractiveShell.prompt_out = r'<\#> '
+ c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
+ c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
+ c.PromptManager.out_template = r'<\#> '
- c.InteractiveShell.prompts_pad_left = True
+ c.PromptManager.justify = True
c.InteractiveShell.separate_in = ''
c.InteractiveShell.separate_out = ''
c.InteractiveShell.separate_out2 = ''
c.PrefilterManager.multi_line_specials = True
lines = """
%rehashx
"""
# You have to make sure that attributes that are containers already
# exist before using them. Simple assigning a new list will override
# all previous values.
if hasattr(app, 'exec_lines'):
app.exec_lines.append(lines)
else:
app.exec_lines = [lines]
| Update prompt config for pysh profile. | ## Code Before:
c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
c.InteractiveShell.prompt_in1 = r'\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
c.InteractiveShell.prompt_in2 = r'\C_Green|\C_LightGreen\D\C_Green> '
c.InteractiveShell.prompt_out = r'<\#> '
c.InteractiveShell.prompts_pad_left = True
c.InteractiveShell.separate_in = ''
c.InteractiveShell.separate_out = ''
c.InteractiveShell.separate_out2 = ''
c.PrefilterManager.multi_line_specials = True
lines = """
%rehashx
"""
# You have to make sure that attributes that are containers already
# exist before using them. Simple assigning a new list will override
# all previous values.
if hasattr(app, 'exec_lines'):
app.exec_lines.append(lines)
else:
app.exec_lines = [lines]
## Instruction:
Update prompt config for pysh profile.
## Code After:
c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
c.PromptManager.out_template = r'<\#> '
c.PromptManager.justify = True
c.InteractiveShell.separate_in = ''
c.InteractiveShell.separate_out = ''
c.InteractiveShell.separate_out2 = ''
c.PrefilterManager.multi_line_specials = True
lines = """
%rehashx
"""
# You have to make sure that attributes that are containers already
# exist before using them. Simple assigning a new list will override
# all previous values.
if hasattr(app, 'exec_lines'):
app.exec_lines.append(lines)
else:
app.exec_lines = [lines]
| c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
- c.InteractiveShell.prompt_in1 = r'\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
- c.InteractiveShell.prompt_in2 = r'\C_Green|\C_LightGreen\D\C_Green> '
- c.InteractiveShell.prompt_out = r'<\#> '
+ c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
+ c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
+ c.PromptManager.out_template = r'<\#> '
- c.InteractiveShell.prompts_pad_left = True
+ c.PromptManager.justify = True
c.InteractiveShell.separate_in = ''
c.InteractiveShell.separate_out = ''
c.InteractiveShell.separate_out2 = ''
c.PrefilterManager.multi_line_specials = True
lines = """
%rehashx
"""
# You have to make sure that attributes that are containers already
# exist before using them. Simple assigning a new list will override
# all previous values.
if hasattr(app, 'exec_lines'):
app.exec_lines.append(lines)
else:
app.exec_lines = [lines] |
4f577eabc45acb6e9a8880d062daa225cc76d64c | logparser/logs/micro/micro.py | logparser/logs/micro/micro.py | """Log parsing functions for Micro."""
from __future__ import absolute_import
from json import load
from pkg_resources import resource_filename
def init(state):
"""Init Micro logs."""
filename = resource_filename(
'logparser.logs.micro', 'error_logs.json')
with open(filename) as json_errors:
state["json_errors"] = load(json_errors)
def on_micro_error(match, state, logger):
"""Error on Micro was thrown."""
module_id = match[2]
error_id = match[3]
errors = state["json_errors"]
error_description = errors[module_id][error_id]["description"]
error_name = errors[module_id][error_id]["name"]
logger.error("[" + error_name + "] " + error_description)
| """Log parsing functions for Micro."""
from __future__ import absolute_import
from json import load
from pkg_resources import resource_filename
def init(state):
"""Init Micro logs."""
filename = resource_filename(
'logparser.logs.micro', 'error_logs.json')
with open(filename) as json_errors:
state["json_errors"] = load(json_errors)
def on_micro_error(match, state, logger):
"""Error on Micro was thrown."""
module_id = match[2]
error_id = match[3]
errors = state["json_errors"]
if module_id in errors:
module = errors[module_id]
if error_id in module:
error_description = module[error_id]["description"]
error_name = module[error_id]["name"]
logger.error("[" + error_name + "] " + error_description)
| Check if module and error code exist | Check if module and error code exist
| Python | apache-2.0 | rticommunity/rticonnextdds-logparser,rticommunity/rticonnextdds-logparser | """Log parsing functions for Micro."""
from __future__ import absolute_import
from json import load
from pkg_resources import resource_filename
def init(state):
"""Init Micro logs."""
filename = resource_filename(
'logparser.logs.micro', 'error_logs.json')
with open(filename) as json_errors:
state["json_errors"] = load(json_errors)
def on_micro_error(match, state, logger):
"""Error on Micro was thrown."""
module_id = match[2]
error_id = match[3]
errors = state["json_errors"]
+ if module_id in errors:
+ module = errors[module_id]
+ if error_id in module:
- error_description = errors[module_id][error_id]["description"]
+ error_description = module[error_id]["description"]
- error_name = errors[module_id][error_id]["name"]
+ error_name = module[error_id]["name"]
+ logger.error("[" + error_name + "] " + error_description)
- logger.error("[" + error_name + "] " + error_description)
- | Check if module and error code exist | ## Code Before:
"""Log parsing functions for Micro."""
from __future__ import absolute_import
from json import load
from pkg_resources import resource_filename
def init(state):
"""Init Micro logs."""
filename = resource_filename(
'logparser.logs.micro', 'error_logs.json')
with open(filename) as json_errors:
state["json_errors"] = load(json_errors)
def on_micro_error(match, state, logger):
"""Error on Micro was thrown."""
module_id = match[2]
error_id = match[3]
errors = state["json_errors"]
error_description = errors[module_id][error_id]["description"]
error_name = errors[module_id][error_id]["name"]
logger.error("[" + error_name + "] " + error_description)
## Instruction:
Check if module and error code exist
## Code After:
"""Log parsing functions for Micro."""
from __future__ import absolute_import
from json import load
from pkg_resources import resource_filename
def init(state):
"""Init Micro logs."""
filename = resource_filename(
'logparser.logs.micro', 'error_logs.json')
with open(filename) as json_errors:
state["json_errors"] = load(json_errors)
def on_micro_error(match, state, logger):
"""Error on Micro was thrown."""
module_id = match[2]
error_id = match[3]
errors = state["json_errors"]
if module_id in errors:
module = errors[module_id]
if error_id in module:
error_description = module[error_id]["description"]
error_name = module[error_id]["name"]
logger.error("[" + error_name + "] " + error_description)
| """Log parsing functions for Micro."""
from __future__ import absolute_import
from json import load
from pkg_resources import resource_filename
def init(state):
"""Init Micro logs."""
filename = resource_filename(
'logparser.logs.micro', 'error_logs.json')
with open(filename) as json_errors:
state["json_errors"] = load(json_errors)
def on_micro_error(match, state, logger):
"""Error on Micro was thrown."""
module_id = match[2]
error_id = match[3]
errors = state["json_errors"]
+ if module_id in errors:
+ module = errors[module_id]
+ if error_id in module:
- error_description = errors[module_id][error_id]["description"]
? ------- ----
+ error_description = module[error_id]["description"]
? ++++++++
- error_name = errors[module_id][error_id]["name"]
? ------- ----
+ error_name = module[error_id]["name"]
? ++++++++
-
- logger.error("[" + error_name + "] " + error_description)
+ logger.error("[" + error_name + "] " + error_description)
? ++++++++
|
a7be90536618ac52c91f599bb167e05f831cddfb | mangopaysdk/entities/transaction.py | mangopaysdk/entities/transaction.py | from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties | from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
self.ResultMessage = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
| Add possibilty to get ResultMessage | Add possibilty to get ResultMessage | Python | mit | chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk | from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
+ self.ResultMessage = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
+ | Add possibilty to get ResultMessage | ## Code Before:
from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
## Instruction:
Add possibilty to get ResultMessage
## Code After:
from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
self.ResultMessage = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties
| from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
# Money
self.DebitedFunds = None
# Money
self.CreditedFunds = None
# Money
self.Fees = None
# TransactionType {PAYIN, PAYOUT, TRANSFER}
self.Type = None
# TransactionNature {REGULAR, REFUND, REPUDIATION}
self.Nature = None
# TransactionStatus {CREATED, SUCCEEDED, FAILED}
self.Status = None
self.ResultCode = None
+ self.ResultMessage = None
# timestamp
self.ExecutionDate = None
return super(Transaction, self).__init__(id)
def GetSubObjects(self):
return {
'DebitedFunds': 'Money' ,
'CreditedFunds': 'Money' ,
'Fees': 'Money'
}
def GetReadOnlyProperties(self):
properties = super(Transaction, self).GetReadOnlyProperties()
properties.append('Status' )
properties.append('ResultCode' )
properties.append('ExecutionDate' )
return properties |
debcec2e64e85aafec3a11860042401e9d9955a7 | metafunctions/tests/test_star.py | metafunctions/tests/test_star.py | from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase
class TestUnit(BaseTestCase):
def test_simple_star(self):
@node
def f(*args):
return args
cmp = (a | b) | star(f)
self.assertEqual(cmp('_'), ('_', 'a', 'b'))
def test_str_repr(self):
@node
def f(*args):
return args
@star
@node
def g(*x):
return x
@node
@star
def h(*x):
return x
cmp = (a | b) | star(f)
star_a = star(a)
self.assertEqual(str(cmp), '(a | b | star(f))')
self.assertEqual(str(star_a), 'star(a)')
self.assertEqual(str(g), 'star(g)')
self.assertEqual(str(h), 'h')
@node
def a(x):
return x + 'a'
@node
def b(x):
return x + 'b'
| from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase
class TestUnit(BaseTestCase):
def test_simple_star(self):
@node
def f(*args):
return args
cmp = (a | b) | star(f)
self.assertEqual(cmp('_'), ('_', 'a', 'b'))
def test_str_repr(self):
@node
def f(*args):
return args
@star
@node
def g(*x):
return x
@node
@star
def h(*x):
return x
cmp = (a | b) | star(f)
star_a = star(a)
merge_star = star(a+b)
chain_star = star(a|b)
self.assertEqual(str(cmp), '(a | b | star(f))')
self.assertEqual(str(star_a), 'star(a)')
self.assertEqual(str(g), 'star(g)')
self.assertEqual(str(h), 'h')
self.assertEqual(str(merge_star), 'star(a + b)')
self.assertEqual(str(h), 'star(a | b)')
@node
def a(x):
return x + 'a'
@node
def b(x):
return x + 'b'
| Add more expected star str | Add more expected star str
| Python | mit | ForeverWintr/metafunctions | from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase
class TestUnit(BaseTestCase):
def test_simple_star(self):
@node
def f(*args):
return args
cmp = (a | b) | star(f)
self.assertEqual(cmp('_'), ('_', 'a', 'b'))
def test_str_repr(self):
@node
def f(*args):
return args
@star
@node
def g(*x):
return x
@node
@star
def h(*x):
return x
cmp = (a | b) | star(f)
star_a = star(a)
+ merge_star = star(a+b)
+ chain_star = star(a|b)
self.assertEqual(str(cmp), '(a | b | star(f))')
self.assertEqual(str(star_a), 'star(a)')
self.assertEqual(str(g), 'star(g)')
self.assertEqual(str(h), 'h')
+ self.assertEqual(str(merge_star), 'star(a + b)')
+ self.assertEqual(str(h), 'star(a | b)')
+
+
@node
def a(x):
return x + 'a'
@node
def b(x):
return x + 'b'
| Add more expected star str | ## Code Before:
from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase
class TestUnit(BaseTestCase):
def test_simple_star(self):
@node
def f(*args):
return args
cmp = (a | b) | star(f)
self.assertEqual(cmp('_'), ('_', 'a', 'b'))
def test_str_repr(self):
@node
def f(*args):
return args
@star
@node
def g(*x):
return x
@node
@star
def h(*x):
return x
cmp = (a | b) | star(f)
star_a = star(a)
self.assertEqual(str(cmp), '(a | b | star(f))')
self.assertEqual(str(star_a), 'star(a)')
self.assertEqual(str(g), 'star(g)')
self.assertEqual(str(h), 'h')
@node
def a(x):
return x + 'a'
@node
def b(x):
return x + 'b'
## Instruction:
Add more expected star str
## Code After:
from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase
class TestUnit(BaseTestCase):
def test_simple_star(self):
@node
def f(*args):
return args
cmp = (a | b) | star(f)
self.assertEqual(cmp('_'), ('_', 'a', 'b'))
def test_str_repr(self):
@node
def f(*args):
return args
@star
@node
def g(*x):
return x
@node
@star
def h(*x):
return x
cmp = (a | b) | star(f)
star_a = star(a)
merge_star = star(a+b)
chain_star = star(a|b)
self.assertEqual(str(cmp), '(a | b | star(f))')
self.assertEqual(str(star_a), 'star(a)')
self.assertEqual(str(g), 'star(g)')
self.assertEqual(str(h), 'h')
self.assertEqual(str(merge_star), 'star(a + b)')
self.assertEqual(str(h), 'star(a | b)')
@node
def a(x):
return x + 'a'
@node
def b(x):
return x + 'b'
| from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase
class TestUnit(BaseTestCase):
def test_simple_star(self):
@node
def f(*args):
return args
cmp = (a | b) | star(f)
self.assertEqual(cmp('_'), ('_', 'a', 'b'))
def test_str_repr(self):
@node
def f(*args):
return args
@star
@node
def g(*x):
return x
@node
@star
def h(*x):
return x
cmp = (a | b) | star(f)
star_a = star(a)
+ merge_star = star(a+b)
+ chain_star = star(a|b)
self.assertEqual(str(cmp), '(a | b | star(f))')
self.assertEqual(str(star_a), 'star(a)')
self.assertEqual(str(g), 'star(g)')
self.assertEqual(str(h), 'h')
+ self.assertEqual(str(merge_star), 'star(a + b)')
+ self.assertEqual(str(h), 'star(a | b)')
+
+
@node
def a(x):
return x + 'a'
@node
def b(x):
return x + 'b' |
c42856ffd6ab8a762ea095fbfbfd7705e1eabd51 | ideascube/serveradmin/battery.py | ideascube/serveradmin/battery.py | import batinfo
class Lime2Battery(batinfo.Battery):
@property
def status(self):
if self.charging == 0:
return 'Discharging'
elif self.capacity < 100:
return 'Charging'
else:
return 'Full'
def get_batteries():
batteries = batinfo.batteries()
if batteries:
return batteries.stat
try:
# We might be running on a Lime2 Koombook
# https://github.com/ideascube/ideascube/issues/446#issuecomment-244143565
return [Lime2Battery(path='/sys/power/axp_pmu', name='battery')]
except FileNotFoundError:
return []
| import batinfo
class Lime2Battery(batinfo.Battery):
@property
def status(self):
if self.charging == 0:
return 'Discharging'
elif self.capacity < 100:
return 'Charging'
else:
return 'Full'
def get_batteries():
batteries = batinfo.batteries()
if batteries:
return sorted(batteries.stat, key=lambda b: b.name.lower())
try:
# We might be running on a Lime2 Koombook
# https://github.com/ideascube/ideascube/issues/446#issuecomment-244143565
return [Lime2Battery(path='/sys/power/axp_pmu', name='battery')]
except FileNotFoundError:
return []
| Order the batteries by name | settings: Order the batteries by name
Eventually we'll want to do better than this, but batinfo doesn't export
what we'd need to do better.
Moving to udev+upower would help, but that's probably something we
should do with cockpit anyway.
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | import batinfo
class Lime2Battery(batinfo.Battery):
@property
def status(self):
if self.charging == 0:
return 'Discharging'
elif self.capacity < 100:
return 'Charging'
else:
return 'Full'
def get_batteries():
batteries = batinfo.batteries()
if batteries:
- return batteries.stat
+ return sorted(batteries.stat, key=lambda b: b.name.lower())
try:
# We might be running on a Lime2 Koombook
# https://github.com/ideascube/ideascube/issues/446#issuecomment-244143565
return [Lime2Battery(path='/sys/power/axp_pmu', name='battery')]
except FileNotFoundError:
return []
| Order the batteries by name | ## Code Before:
import batinfo
class Lime2Battery(batinfo.Battery):
@property
def status(self):
if self.charging == 0:
return 'Discharging'
elif self.capacity < 100:
return 'Charging'
else:
return 'Full'
def get_batteries():
batteries = batinfo.batteries()
if batteries:
return batteries.stat
try:
# We might be running on a Lime2 Koombook
# https://github.com/ideascube/ideascube/issues/446#issuecomment-244143565
return [Lime2Battery(path='/sys/power/axp_pmu', name='battery')]
except FileNotFoundError:
return []
## Instruction:
Order the batteries by name
## Code After:
import batinfo
class Lime2Battery(batinfo.Battery):
@property
def status(self):
if self.charging == 0:
return 'Discharging'
elif self.capacity < 100:
return 'Charging'
else:
return 'Full'
def get_batteries():
batteries = batinfo.batteries()
if batteries:
return sorted(batteries.stat, key=lambda b: b.name.lower())
try:
# We might be running on a Lime2 Koombook
# https://github.com/ideascube/ideascube/issues/446#issuecomment-244143565
return [Lime2Battery(path='/sys/power/axp_pmu', name='battery')]
except FileNotFoundError:
return []
| import batinfo
class Lime2Battery(batinfo.Battery):
@property
def status(self):
if self.charging == 0:
return 'Discharging'
elif self.capacity < 100:
return 'Charging'
else:
return 'Full'
def get_batteries():
batteries = batinfo.batteries()
if batteries:
- return batteries.stat
+ return sorted(batteries.stat, key=lambda b: b.name.lower())
try:
# We might be running on a Lime2 Koombook
# https://github.com/ideascube/ideascube/issues/446#issuecomment-244143565
return [Lime2Battery(path='/sys/power/axp_pmu', name='battery')]
except FileNotFoundError:
return [] |
29b5337132373d624f291af3f64bb3b05fd48e77 | tests/test_list.py | tests/test_list.py | import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = list(listMetrics(self.rootdir))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = list(listMetrics(self.rootdir + '/'))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
| import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = sorted(list(listMetrics(self.rootdir)))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = sorted(list(listMetrics(self.rootdir + '/')))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
| Make sure we're sorting results | Make sure we're sorting results
| Python | mit | skbkontur/carbonate,unbrice/carbonate,skbkontur/carbonate,ross/carbonate,ross/carbonate,graphite-project/carbonate,deniszh/carbonate,unbrice/carbonate,jssjr/carbonate,criteo-forks/carbonate,criteo-forks/carbonate,ross/carbonate,jssjr/carbonate,unbrice/carbonate,skbkontur/carbonate,jssjr/carbonate,graphite-project/carbonate,deniszh/carbonate,criteo-forks/carbonate,graphite-project/carbonate,deniszh/carbonate | import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
- res = list(listMetrics(self.rootdir))
+ res = sorted(list(listMetrics(self.rootdir)))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
- res = list(listMetrics(self.rootdir + '/'))
+ res = sorted(list(listMetrics(self.rootdir + '/')))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
| Make sure we're sorting results | ## Code Before:
import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = list(listMetrics(self.rootdir))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = list(listMetrics(self.rootdir + '/'))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
## Instruction:
Make sure we're sorting results
## Code After:
import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
res = sorted(list(listMetrics(self.rootdir)))
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
res = sorted(list(listMetrics(self.rootdir + '/')))
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir)
| import os
import unittest
from carbonate.list import listMetrics
class ListTest(unittest.TestCase):
metrics_tree = ["foo",
"foo/sprockets.wsp",
"foo/widgets.wsp",
"ham",
"ham/bones.wsp",
"ham/hocks.wsp"]
expected_metrics = ["foo.sprockets",
"foo.widgets",
"ham.bones",
"ham.hocks"]
rootdir = os.path.join(os.curdir, 'test_storage')
@classmethod
def setUpClass(cls):
os.system("rm -rf %s" % cls.rootdir)
os.mkdir(cls.rootdir)
for f in cls.metrics_tree:
if f.endswith('wsp'):
open(os.path.join(cls.rootdir, f), 'w').close()
else:
os.mkdir(os.path.join(cls.rootdir, f))
def test_list(self):
- res = list(listMetrics(self.rootdir))
+ res = sorted(list(listMetrics(self.rootdir)))
? +++++++ +
self.assertEqual(res, self.expected_metrics)
def test_list_with_trailing_slash(self):
- res = list(listMetrics(self.rootdir + '/'))
+ res = sorted(list(listMetrics(self.rootdir + '/')))
? +++++++ +
self.assertEqual(res, self.expected_metrics)
@classmethod
def tearDownClass(cls):
os.system("rm -rf %s" % cls.rootdir) |
0356392b2933aa7c02f89bdf588a4ec0482db4a8 | tests/main_test.py | tests/main_test.py |
from libpals.util import xor_find_singlechar_key
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
|
from libpals.util import xor_find_singlechar_key, hamming_distance
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
def test_hamming_distance():
assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37
| Add a test for hamming_distance() | Add a test for hamming_distance()
| Python | bsd-2-clause | cpach/cryptopals-python3 |
- from libpals.util import xor_find_singlechar_key
+ from libpals.util import xor_find_singlechar_key, hamming_distance
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
+
+ def test_hamming_distance():
+ assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37
+ | Add a test for hamming_distance() | ## Code Before:
from libpals.util import xor_find_singlechar_key
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
## Instruction:
Add a test for hamming_distance()
## Code After:
from libpals.util import xor_find_singlechar_key, hamming_distance
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
def test_hamming_distance():
assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37
|
- from libpals.util import xor_find_singlechar_key
+ from libpals.util import xor_find_singlechar_key, hamming_distance
? ++++++++++++++++++
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
+
+
+ def test_hamming_distance():
+ assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37 |
62b90eb97c9e32280f7f1a9c1127099f20440c11 | byceps/config_defaults.py | byceps/config_defaults.py |
from datetime import timedelta
from pytz import timezone
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
# user accounts
USER_REGISTRATION_ENABLED = True
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# news item pagination
NEWS_ITEMS_PER_PAGE = 4
# message board pagination
BOARD_TOPICS_PER_PAGE = 10
BOARD_POSTINGS_PER_PAGE = 10
# shop
SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin')
# ticketing
TICKET_MANAGEMENT_ENABLED = True
# seating
SEAT_MANAGEMENT_ENABLED = True
|
from datetime import timedelta
from pytz import timezone
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
WEB_BACKGROUND = 'white'
# user accounts
USER_REGISTRATION_ENABLED = True
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# news item pagination
NEWS_ITEMS_PER_PAGE = 4
# message board pagination
BOARD_TOPICS_PER_PAGE = 10
BOARD_POSTINGS_PER_PAGE = 10
# shop
SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin')
# ticketing
TICKET_MANAGEMENT_ENABLED = True
# seating
SEAT_MANAGEMENT_ENABLED = True
| Set required background color for RQ dashboard | Set required background color for RQ dashboard
BYCEPS doesn't use ra dashboard's default settings, so they need to be set explicitly as necessary.
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps |
from datetime import timedelta
from pytz import timezone
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
+ WEB_BACKGROUND = 'white'
# user accounts
USER_REGISTRATION_ENABLED = True
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# news item pagination
NEWS_ITEMS_PER_PAGE = 4
# message board pagination
BOARD_TOPICS_PER_PAGE = 10
BOARD_POSTINGS_PER_PAGE = 10
# shop
SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin')
# ticketing
TICKET_MANAGEMENT_ENABLED = True
# seating
SEAT_MANAGEMENT_ENABLED = True
| Set required background color for RQ dashboard | ## Code Before:
from datetime import timedelta
from pytz import timezone
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
# user accounts
USER_REGISTRATION_ENABLED = True
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# news item pagination
NEWS_ITEMS_PER_PAGE = 4
# message board pagination
BOARD_TOPICS_PER_PAGE = 10
BOARD_POSTINGS_PER_PAGE = 10
# shop
SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin')
# ticketing
TICKET_MANAGEMENT_ENABLED = True
# seating
SEAT_MANAGEMENT_ENABLED = True
## Instruction:
Set required background color for RQ dashboard
## Code After:
from datetime import timedelta
from pytz import timezone
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
WEB_BACKGROUND = 'white'
# user accounts
USER_REGISTRATION_ENABLED = True
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# news item pagination
NEWS_ITEMS_PER_PAGE = 4
# message board pagination
BOARD_TOPICS_PER_PAGE = 10
BOARD_POSTINGS_PER_PAGE = 10
# shop
SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin')
# ticketing
TICKET_MANAGEMENT_ENABLED = True
# seating
SEAT_MANAGEMENT_ENABLED = True
|
from datetime import timedelta
from pytz import timezone
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_TRACK_MODIFICATIONS = False
# job queue
JOBS_ASYNC = True
# metrics
METRICS_ENABLED = False
# RQ dashboard (for job queue)
RQ_DASHBOARD_ENABLED = False
RQ_POLL_INTERVAL = 2500
+ WEB_BACKGROUND = 'white'
# user accounts
USER_REGISTRATION_ENABLED = True
# login sessions
PERMANENT_SESSION_LIFETIME = timedelta(14)
# localization
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
# home page
ROOT_REDIRECT_TARGET = None
ROOT_REDIRECT_STATUS_CODE = 307
# news item pagination
NEWS_ITEMS_PER_PAGE = 4
# message board pagination
BOARD_TOPICS_PER_PAGE = 10
BOARD_POSTINGS_PER_PAGE = 10
# shop
SHOP_ORDER_EXPORT_TIMEZONE = timezone('Europe/Berlin')
# ticketing
TICKET_MANAGEMENT_ENABLED = True
# seating
SEAT_MANAGEMENT_ENABLED = True |
d58c04d9745f1a0af46f35fba7b3e2aef704547e | application.py | application.py | import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
application = WhiteNoise(app, STATIC_ROOT, STATIC_URL)
| import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL)
| Make Whitenoise serve static assets | Make Whitenoise serve static assets
Currently it’s not configured properly, so isn’t having any effect.
This change makes it wrap the Flask app, so it intercepts any requests
for static content.
Follows the pattern documented in http://whitenoise.evans.io/en/stable/flask.html#enable-whitenoise
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
- application = WhiteNoise(app, STATIC_ROOT, STATIC_URL)
+ app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL)
| Make Whitenoise serve static assets | ## Code Before:
import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
application = WhiteNoise(app, STATIC_ROOT, STATIC_URL)
## Instruction:
Make Whitenoise serve static assets
## Code After:
import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL)
| import os
from flask import Flask
from whitenoise import WhiteNoise
from app import create_app
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'app', 'static')
STATIC_URL = 'static/'
app = Flask('app')
create_app(app)
- application = WhiteNoise(app, STATIC_ROOT, STATIC_URL)
? ^ ^ ^^^^
+ app.wsgi_app = WhiteNoise(app.wsgi_app, STATIC_ROOT, STATIC_URL)
? ^^^^ ^ ^^ +++++++++
|
81d2882d1558ed52fc70927d745474aa46ac1f3b | jarbas/dashboard/admin.py | jarbas/dashboard/admin.py | from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
)
def queryset(self, request, queryset):
return queryset.suspicions() if self.value() == 'yes' else queryset
class ReimbursementModelAdmin(admin.ModelAdmin):
list_display = (
'document_id',
'congressperson_name',
'year',
'subquota_description',
'supplier',
'cnpj_cpf',
'is_suspicious',
'total_net_value',
'available_in_latest_dataset',
)
search_fields = (
'applicant_id',
'cnpj_cpf',
'congressperson_name',
'document_id',
'party',
'state',
'supplier',
)
list_filter = (
SuspiciousListFilter,
'available_in_latest_dataset',
'year',
'state',
)
def is_suspicious(self, obj):
return obj.suspicions is not None
is_suspicious.short_description = 'Suspicious'
is_suspicious.boolean = True
admin.site.register(Reimbursement, ReimbursementModelAdmin)
| from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
)
def queryset(self, request, queryset):
return queryset.suspicions() if self.value() == 'yes' else queryset
class ReimbursementModelAdmin(admin.ModelAdmin):
list_display = (
'document_id',
'congressperson_name',
'year',
'subquota_description',
'supplier',
'cnpj_cpf',
'is_suspicious',
'total_net_value',
'available_in_latest_dataset',
)
search_fields = (
'applicant_id',
'cnpj_cpf',
'congressperson_name',
'document_id',
'party',
'state',
'supplier',
)
list_filter = (
SuspiciousListFilter,
'available_in_latest_dataset',
'year',
'state',
)
readonly_fields = tuple(f.name for f in Reimbursement._meta.fields)
def is_suspicious(self, obj):
return obj.suspicions is not None
is_suspicious.short_description = 'Suspicious'
is_suspicious.boolean = True
admin.site.register(Reimbursement, ReimbursementModelAdmin)
| Mark all fields as read only in the dashboard | Mark all fields as read only in the dashboard
| Python | mit | datasciencebr/jarbas,datasciencebr/jarbas,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor | from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
)
def queryset(self, request, queryset):
return queryset.suspicions() if self.value() == 'yes' else queryset
class ReimbursementModelAdmin(admin.ModelAdmin):
list_display = (
'document_id',
'congressperson_name',
'year',
'subquota_description',
'supplier',
'cnpj_cpf',
'is_suspicious',
'total_net_value',
'available_in_latest_dataset',
)
search_fields = (
'applicant_id',
'cnpj_cpf',
'congressperson_name',
'document_id',
'party',
'state',
'supplier',
)
list_filter = (
SuspiciousListFilter,
'available_in_latest_dataset',
'year',
'state',
)
+ readonly_fields = tuple(f.name for f in Reimbursement._meta.fields)
def is_suspicious(self, obj):
return obj.suspicions is not None
is_suspicious.short_description = 'Suspicious'
is_suspicious.boolean = True
admin.site.register(Reimbursement, ReimbursementModelAdmin)
| Mark all fields as read only in the dashboard | ## Code Before:
from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
)
def queryset(self, request, queryset):
return queryset.suspicions() if self.value() == 'yes' else queryset
class ReimbursementModelAdmin(admin.ModelAdmin):
list_display = (
'document_id',
'congressperson_name',
'year',
'subquota_description',
'supplier',
'cnpj_cpf',
'is_suspicious',
'total_net_value',
'available_in_latest_dataset',
)
search_fields = (
'applicant_id',
'cnpj_cpf',
'congressperson_name',
'document_id',
'party',
'state',
'supplier',
)
list_filter = (
SuspiciousListFilter,
'available_in_latest_dataset',
'year',
'state',
)
def is_suspicious(self, obj):
return obj.suspicions is not None
is_suspicious.short_description = 'Suspicious'
is_suspicious.boolean = True
admin.site.register(Reimbursement, ReimbursementModelAdmin)
## Instruction:
Mark all fields as read only in the dashboard
## Code After:
from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
)
def queryset(self, request, queryset):
return queryset.suspicions() if self.value() == 'yes' else queryset
class ReimbursementModelAdmin(admin.ModelAdmin):
list_display = (
'document_id',
'congressperson_name',
'year',
'subquota_description',
'supplier',
'cnpj_cpf',
'is_suspicious',
'total_net_value',
'available_in_latest_dataset',
)
search_fields = (
'applicant_id',
'cnpj_cpf',
'congressperson_name',
'document_id',
'party',
'state',
'supplier',
)
list_filter = (
SuspiciousListFilter,
'available_in_latest_dataset',
'year',
'state',
)
readonly_fields = tuple(f.name for f in Reimbursement._meta.fields)
def is_suspicious(self, obj):
return obj.suspicions is not None
is_suspicious.short_description = 'Suspicious'
is_suspicious.boolean = True
admin.site.register(Reimbursement, ReimbursementModelAdmin)
| from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
)
def queryset(self, request, queryset):
return queryset.suspicions() if self.value() == 'yes' else queryset
class ReimbursementModelAdmin(admin.ModelAdmin):
list_display = (
'document_id',
'congressperson_name',
'year',
'subquota_description',
'supplier',
'cnpj_cpf',
'is_suspicious',
'total_net_value',
'available_in_latest_dataset',
)
search_fields = (
'applicant_id',
'cnpj_cpf',
'congressperson_name',
'document_id',
'party',
'state',
'supplier',
)
list_filter = (
SuspiciousListFilter,
'available_in_latest_dataset',
'year',
'state',
)
+ readonly_fields = tuple(f.name for f in Reimbursement._meta.fields)
def is_suspicious(self, obj):
return obj.suspicions is not None
is_suspicious.short_description = 'Suspicious'
is_suspicious.boolean = True
admin.site.register(Reimbursement, ReimbursementModelAdmin) |
a3c4f151a9a44aae3528492d4a00a1815c52cda6 | website_membership_contact_visibility/models/res_partner.py | website_membership_contact_visibility/models/res_partner.py |
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
string='Visible In The Website',
copy=False,
default=True)
|
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
string='Visible Contact Info On The Website',
copy=False,
default=True)
| Change the label of "website_membership_published" into "Visible Contact Info On The Website" | Change the label of "website_membership_published" into "Visible Contact Info On The Website"
| Python | agpl-3.0 | open-synergy/vertical-association |
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
- string='Visible In The Website',
+ string='Visible Contact Info On The Website',
copy=False,
default=True)
| Change the label of "website_membership_published" into "Visible Contact Info On The Website" | ## Code Before:
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
string='Visible In The Website',
copy=False,
default=True)
## Instruction:
Change the label of "website_membership_published" into "Visible Contact Info On The Website"
## Code After:
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
string='Visible Contact Info On The Website',
copy=False,
default=True)
|
from openerp import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
website_membership_published = fields.Boolean(
- string='Visible In The Website',
+ string='Visible Contact Info On The Website',
? ++++++++ +++++
copy=False,
default=True) |
2fc45a6a0e2ba1efe06b4282234cf13c0ccd5b7d | dj_experiment/conf.py | dj_experiment/conf.py | from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'rpc://'
class Meta:
prefix = 'dj_experiment'
holder = 'dj_experiment.conf.settings'
| import os
from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
BASE_DATA_DIR = os.path.join(settings.BASE_DIR, 'data')
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'rpc://'
class Meta:
prefix = 'dj_experiment'
holder = 'dj_experiment.conf.settings'
| Add default base data dir for experiments | Add default base data dir for experiments
| Python | mit | francbartoli/dj-experiment,francbartoli/dj-experiment | + import os
+
from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
+ BASE_DATA_DIR = os.path.join(settings.BASE_DIR, 'data')
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'rpc://'
class Meta:
prefix = 'dj_experiment'
holder = 'dj_experiment.conf.settings'
| Add default base data dir for experiments | ## Code Before:
from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'rpc://'
class Meta:
prefix = 'dj_experiment'
holder = 'dj_experiment.conf.settings'
## Instruction:
Add default base data dir for experiments
## Code After:
import os
from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
BASE_DATA_DIR = os.path.join(settings.BASE_DIR, 'data')
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'rpc://'
class Meta:
prefix = 'dj_experiment'
holder = 'dj_experiment.conf.settings'
| + import os
+
from appconf import AppConf
from django.conf import settings
class DjExperimentAppConf(AppConf):
DATA_DIR = "./"
+ BASE_DATA_DIR = os.path.join(settings.BASE_DIR, 'data')
SEPARATOR = "."
OUTPUT_PREFIX = ""
OUTPUT_SUFFIX = ".nc"
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'rpc://'
class Meta:
prefix = 'dj_experiment'
holder = 'dj_experiment.conf.settings' |
8f42513d6845b6b1461150b1e92890c78c72280e | find_text_type_file.py | find_text_type_file.py |
import os
import subprocess
import sys
def find_text_files(directory):
''' , '''
file_list = []
abspath = os.path.abspath(directory)
for i in os.listdir(directory):
result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
file_list.append(i)
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
print(results)
|
from pathlib import Path
import os
import subprocess
import sys
LINE_LIMIT = 100
def find_text_files(directory):
''' find text files and look for file content less than 100 characters. '''
file_list = []
abspath = os.path.abspath(directory)
files = [i[0] for i in os.walk(abspath)]
for i in os.walk(abspath):
for j in i[2]:
file_abspath = '{}/{}'.format(i[0], j)
path_obj = Path(file_abspath)
if path_obj.is_file():
result = subprocess.run(['file', "{}".format(file_abspath)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
with open(file_abspath) as text_file:
for line in text_file.readlines():
if len(line) < LINE_LIMIT:
print('file path = {}'.format(file_abspath))
print(line)
file_list.append("{}".format(file_abspath))
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
| Update find text, walk through the directories with os.walk and print line length less than 100 characters. | Update find text, walk through the directories with os.walk and print line length less than 100 characters.
Signed-off-by: SJ Huang <55a36c562e010d4b156739b1c231e1aa17113c8e@gmail.com>
| Python | apache-2.0 | sjh/python |
+ from pathlib import Path
import os
import subprocess
import sys
+ LINE_LIMIT = 100
+
def find_text_files(directory):
- ''' , '''
+ ''' find text files and look for file content less than 100 characters. '''
file_list = []
abspath = os.path.abspath(directory)
- for i in os.listdir(directory):
+ files = [i[0] for i in os.walk(abspath)]
+ for i in os.walk(abspath):
+ for j in i[2]:
+ file_abspath = '{}/{}'.format(i[0], j)
+ path_obj = Path(file_abspath)
+ if path_obj.is_file():
- result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE)
+ result = subprocess.run(['file', "{}".format(file_abspath)], stdout=subprocess.PIPE)
- if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
+ if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
- file_list.append(i)
+ with open(file_abspath) as text_file:
+ for line in text_file.readlines():
+ if len(line) < LINE_LIMIT:
+ print('file path = {}'.format(file_abspath))
+ print(line)
+
+ file_list.append("{}".format(file_abspath))
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
- print(results)
| Update find text, walk through the directories with os.walk and print line length less than 100 characters. | ## Code Before:
import os
import subprocess
import sys
def find_text_files(directory):
''' , '''
file_list = []
abspath = os.path.abspath(directory)
for i in os.listdir(directory):
result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
file_list.append(i)
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
print(results)
## Instruction:
Update find text, walk through the directories with os.walk and print line length less than 100 characters.
## Code After:
from pathlib import Path
import os
import subprocess
import sys
LINE_LIMIT = 100
def find_text_files(directory):
''' find text files and look for file content less than 100 characters. '''
file_list = []
abspath = os.path.abspath(directory)
files = [i[0] for i in os.walk(abspath)]
for i in os.walk(abspath):
for j in i[2]:
file_abspath = '{}/{}'.format(i[0], j)
path_obj = Path(file_abspath)
if path_obj.is_file():
result = subprocess.run(['file', "{}".format(file_abspath)], stdout=subprocess.PIPE)
if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
with open(file_abspath) as text_file:
for line in text_file.readlines():
if len(line) < LINE_LIMIT:
print('file path = {}'.format(file_abspath))
print(line)
file_list.append("{}".format(file_abspath))
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
|
+ from pathlib import Path
import os
import subprocess
import sys
+ LINE_LIMIT = 100
+
def find_text_files(directory):
- ''' , '''
+ ''' find text files and look for file content less than 100 characters. '''
file_list = []
abspath = os.path.abspath(directory)
- for i in os.listdir(directory):
+ files = [i[0] for i in os.walk(abspath)]
+ for i in os.walk(abspath):
+ for j in i[2]:
+ file_abspath = '{}/{}'.format(i[0], j)
+ path_obj = Path(file_abspath)
+ if path_obj.is_file():
- result = subprocess.run(['file', "{}/{}".format(abspath, i)], stdout=subprocess.PIPE)
? --- ---
+ result = subprocess.run(['file', "{}".format(file_abspath)], stdout=subprocess.PIPE)
? ++++++++ +++++
- if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
+ if 'text' in result.stdout.decode('utf-8').split(':')[-1]:
? ++++++++
- file_list.append(i)
+ with open(file_abspath) as text_file:
+ for line in text_file.readlines():
+ if len(line) < LINE_LIMIT:
+ print('file path = {}'.format(file_abspath))
+ print(line)
+
+ file_list.append("{}".format(file_abspath))
return file_list
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Error, should provide one parameter for program {}".format(sys.argv[0]))
sys.exit(1)
results = find_text_files(sys.argv[1])
- print(results) |
73a9889f0e43d2b1dc94e2235a94cb888e0eda89 | zeus/utils/sentry.py | zeus/utils/sentry.py | from functools import wraps
from sentry_sdk import Hub
def span(op, desc_or_func=None):
def inner(func):
@wraps(func)
def wrapped(*args, **kwargs):
if callable(desc_or_func):
description = desc_or_func(*args, **kwargs)
else:
description = desc_or_func
with Hub.current.start_span(op=op, description=description):
return func(*args, **kwargs)
return wrapped
return inner
| import asyncio
from contextlib import contextmanager
from functools import wraps
from sentry_sdk import Hub
# https://stackoverflow.com/questions/44169998/how-to-create-a-python-decorator-that-can-wrap-either-coroutine-or-function
def span(op, desc_or_func=None):
def inner(func):
@contextmanager
def wrap_with_span(args, kwargs):
if callable(desc_or_func):
description = desc_or_func(*args, **kwargs)
else:
description = desc_or_func
with Hub.current.start_span(op=op, description=description):
yield
@wraps(func)
def wrapper(*args, **kwargs):
if not asyncio.iscoroutinefunction(func):
with wrap_with_span(args, kwargs):
return func(*args, **kwargs)
else:
async def tmp():
with wrap_with_span(args, kwargs):
return await func(*args, **kwargs)
return tmp()
return wrapper
return inner
| Fix span decorator to work with asyncio | Fix span decorator to work with asyncio
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus | + import asyncio
+
+ from contextlib import contextmanager
from functools import wraps
from sentry_sdk import Hub
+ # https://stackoverflow.com/questions/44169998/how-to-create-a-python-decorator-that-can-wrap-either-coroutine-or-function
def span(op, desc_or_func=None):
def inner(func):
- @wraps(func)
+ @contextmanager
- def wrapped(*args, **kwargs):
+ def wrap_with_span(args, kwargs):
if callable(desc_or_func):
description = desc_or_func(*args, **kwargs)
else:
description = desc_or_func
with Hub.current.start_span(op=op, description=description):
- return func(*args, **kwargs)
+ yield
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ if not asyncio.iscoroutinefunction(func):
+ with wrap_with_span(args, kwargs):
+ return func(*args, **kwargs)
+ else:
+
+ async def tmp():
+ with wrap_with_span(args, kwargs):
+ return await func(*args, **kwargs)
+
+ return tmp()
+
- return wrapped
+ return wrapper
return inner
| Fix span decorator to work with asyncio | ## Code Before:
from functools import wraps
from sentry_sdk import Hub
def span(op, desc_or_func=None):
def inner(func):
@wraps(func)
def wrapped(*args, **kwargs):
if callable(desc_or_func):
description = desc_or_func(*args, **kwargs)
else:
description = desc_or_func
with Hub.current.start_span(op=op, description=description):
return func(*args, **kwargs)
return wrapped
return inner
## Instruction:
Fix span decorator to work with asyncio
## Code After:
import asyncio
from contextlib import contextmanager
from functools import wraps
from sentry_sdk import Hub
# https://stackoverflow.com/questions/44169998/how-to-create-a-python-decorator-that-can-wrap-either-coroutine-or-function
def span(op, desc_or_func=None):
def inner(func):
@contextmanager
def wrap_with_span(args, kwargs):
if callable(desc_or_func):
description = desc_or_func(*args, **kwargs)
else:
description = desc_or_func
with Hub.current.start_span(op=op, description=description):
yield
@wraps(func)
def wrapper(*args, **kwargs):
if not asyncio.iscoroutinefunction(func):
with wrap_with_span(args, kwargs):
return func(*args, **kwargs)
else:
async def tmp():
with wrap_with_span(args, kwargs):
return await func(*args, **kwargs)
return tmp()
return wrapper
return inner
| + import asyncio
+
+ from contextlib import contextmanager
from functools import wraps
from sentry_sdk import Hub
+ # https://stackoverflow.com/questions/44169998/how-to-create-a-python-decorator-that-can-wrap-either-coroutine-or-function
def span(op, desc_or_func=None):
def inner(func):
- @wraps(func)
+ @contextmanager
- def wrapped(*args, **kwargs):
? ^^ - --
+ def wrap_with_span(args, kwargs):
? +++++++ ^^
if callable(desc_or_func):
description = desc_or_func(*args, **kwargs)
else:
description = desc_or_func
with Hub.current.start_span(op=op, description=description):
- return func(*args, **kwargs)
+ yield
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ if not asyncio.iscoroutinefunction(func):
+ with wrap_with_span(args, kwargs):
+ return func(*args, **kwargs)
+ else:
+
+ async def tmp():
+ with wrap_with_span(args, kwargs):
+ return await func(*args, **kwargs)
+
+ return tmp()
+
- return wrapped
? ^
+ return wrapper
? ^
return inner |
7aedc2151035174632a7f3e55be7563f71e65117 | tests/audio/test_loading.py | tests/audio/test_loading.py | import pytest
@pytest.mark.xfail
def test_missing_file(audiomgr):
sound = audiomgr.get_sound('/not/a/valid/file.ogg')
assert sound is None
| import pytest
def test_missing_file(audiomgr):
sound = audiomgr.get_sound('/not/a/valid/file.ogg')
assert str(sound).startswith('NullAudioSound')
| Update audio test to recognize missing sounds as NullAudioSound | tests: Update audio test to recognize missing sounds as NullAudioSound
| Python | bsd-3-clause | chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d | import pytest
- @pytest.mark.xfail
def test_missing_file(audiomgr):
sound = audiomgr.get_sound('/not/a/valid/file.ogg')
- assert sound is None
+ assert str(sound).startswith('NullAudioSound')
| Update audio test to recognize missing sounds as NullAudioSound | ## Code Before:
import pytest
@pytest.mark.xfail
def test_missing_file(audiomgr):
sound = audiomgr.get_sound('/not/a/valid/file.ogg')
assert sound is None
## Instruction:
Update audio test to recognize missing sounds as NullAudioSound
## Code After:
import pytest
def test_missing_file(audiomgr):
sound = audiomgr.get_sound('/not/a/valid/file.ogg')
assert str(sound).startswith('NullAudioSound')
| import pytest
- @pytest.mark.xfail
def test_missing_file(audiomgr):
sound = audiomgr.get_sound('/not/a/valid/file.ogg')
- assert sound is None
+ assert str(sound).startswith('NullAudioSound') |
db3cadcf3baa22efe65495aca2efe5352d5a89a5 | nhs/gunicorn_conf.py | nhs/gunicorn_conf.py | bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
| bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
timeout = 60
| Extend Gunicorn worker timeout for long-running API calls. | Extend Gunicorn worker timeout for long-running API calls.
| Python | agpl-3.0 | openhealthcare/open-prescribing,openhealthcare/open-prescribing,openhealthcare/open-prescribing | bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
+ timeout = 60
| Extend Gunicorn worker timeout for long-running API calls. | ## Code Before:
bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
## Instruction:
Extend Gunicorn worker timeout for long-running API calls.
## Code After:
bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
timeout = 60
| bind = "127.0.0.1:4567"
logfile = "/usr/local/ohc/log/op.gunicorn.log"
workers = 3
+ timeout = 60 |
8afbd0fe7f4732d8484a2a41b91451ec220fc2f8 | tools/perf/benchmarks/memory.py | tools/perf/benchmarks/memory.py | from telemetry import test
from measurements import memory
class Memory(test.Test):
test = memory.Memory
page_set = 'page_sets/top_25.json'
class Reload(test.Test):
test = memory.Memory
page_set = 'page_sets/2012Q3.json'
| from telemetry import test
from measurements import memory
class MemoryTop25(test.Test):
test = memory.Memory
page_set = 'page_sets/top_25.json'
class Reload2012Q3(test.Test):
test = memory.Memory
page_set = 'page_sets/2012Q3.json'
| Rename Memory benchmark to avoid conflict with Memory measurement. | [telemetry] Rename Memory benchmark to avoid conflict with Memory measurement.
Quick fix for now, but I may need to reconsider how run_measurement resolved name conflicts.
BUG=263511
TEST=None.
R=tonyg@chromium.org
Review URL: https://chromiumcodereview.appspot.com/19915008
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@213290 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,patrickm/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,anirudhSK/chromium,axinging/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,dednal/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,ondra-novak/chromium.src,markYoungH/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,ltilve/chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,patrickm/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,littlstar/chromium.src,Chilledheart/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,anirudhSK/chromium,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,dednal/chromium.src,littlstar/chromium.src,dednal/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,jaruba/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,Just-D/chromium-1,littlstar/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src | from telemetry import test
from measurements import memory
- class Memory(test.Test):
+ class MemoryTop25(test.Test):
test = memory.Memory
page_set = 'page_sets/top_25.json'
- class Reload(test.Test):
+ class Reload2012Q3(test.Test):
test = memory.Memory
page_set = 'page_sets/2012Q3.json'
| Rename Memory benchmark to avoid conflict with Memory measurement. | ## Code Before:
from telemetry import test
from measurements import memory
class Memory(test.Test):
test = memory.Memory
page_set = 'page_sets/top_25.json'
class Reload(test.Test):
test = memory.Memory
page_set = 'page_sets/2012Q3.json'
## Instruction:
Rename Memory benchmark to avoid conflict with Memory measurement.
## Code After:
from telemetry import test
from measurements import memory
class MemoryTop25(test.Test):
test = memory.Memory
page_set = 'page_sets/top_25.json'
class Reload2012Q3(test.Test):
test = memory.Memory
page_set = 'page_sets/2012Q3.json'
| from telemetry import test
from measurements import memory
- class Memory(test.Test):
+ class MemoryTop25(test.Test):
? +++++
test = memory.Memory
page_set = 'page_sets/top_25.json'
- class Reload(test.Test):
+ class Reload2012Q3(test.Test):
? ++++++
test = memory.Memory
page_set = 'page_sets/2012Q3.json' |
53b176674f1d72396b066705e502b5fcbee16a91 | vulyk/plugins/dummy/__init__.py | vulyk/plugins/dummy/__init__.py | import json
import logging
from werkzeug.utils import import_string
logger = logging.getLogger(__name__)
def get_task(request):
return json.dumps({})
def configure(self_settings):
"""
Getting plugin's default settings, overwriting them with settings
from local_settings.py, returns list of settings
"""
try:
local_settings = import_string('vulyk.local_settings')
for attr in dir(local_settings):
if attr in dir(self_settings):
self_settings[attr] = getattr(local_settings, attr)
except Exception as e:
logger.warning(e)
return self_settings
| import json
import logging
from werkzeug.utils import import_string
logger = logging.getLogger(__name__)
def get_task(request):
return json.dumps({})
def configure(self_settings):
"""
Getting plugin's default settings, overwriting them with settings
from local_settings.py, returns dict of settings
"""
settings = {}
try:
local_settings = import_string('vulyk.local_settings')
for attr in dir(self_settings):
settings[attr] = getattr(self_settings, attr)
for attr in dir(local_settings):
if attr in dir(self_settings):
settings[attr] = getattr(local_settings, attr)
except Exception as e:
logger.warning(e)
return settings
| Fix return format of plugin's settings | Fix return format of plugin's settings
| Python | bsd-3-clause | mrgambal/vulyk,mrgambal/vulyk,mrgambal/vulyk | import json
import logging
from werkzeug.utils import import_string
logger = logging.getLogger(__name__)
def get_task(request):
return json.dumps({})
def configure(self_settings):
"""
Getting plugin's default settings, overwriting them with settings
- from local_settings.py, returns list of settings
+ from local_settings.py, returns dict of settings
"""
+ settings = {}
try:
local_settings = import_string('vulyk.local_settings')
+ for attr in dir(self_settings):
+ settings[attr] = getattr(self_settings, attr)
for attr in dir(local_settings):
if attr in dir(self_settings):
- self_settings[attr] = getattr(local_settings, attr)
+ settings[attr] = getattr(local_settings, attr)
except Exception as e:
logger.warning(e)
- return self_settings
+ return settings
| Fix return format of plugin's settings | ## Code Before:
import json
import logging
from werkzeug.utils import import_string
logger = logging.getLogger(__name__)
def get_task(request):
return json.dumps({})
def configure(self_settings):
"""
Getting plugin's default settings, overwriting them with settings
from local_settings.py, returns list of settings
"""
try:
local_settings = import_string('vulyk.local_settings')
for attr in dir(local_settings):
if attr in dir(self_settings):
self_settings[attr] = getattr(local_settings, attr)
except Exception as e:
logger.warning(e)
return self_settings
## Instruction:
Fix return format of plugin's settings
## Code After:
import json
import logging
from werkzeug.utils import import_string
logger = logging.getLogger(__name__)
def get_task(request):
return json.dumps({})
def configure(self_settings):
"""
Getting plugin's default settings, overwriting them with settings
from local_settings.py, returns dict of settings
"""
settings = {}
try:
local_settings = import_string('vulyk.local_settings')
for attr in dir(self_settings):
settings[attr] = getattr(self_settings, attr)
for attr in dir(local_settings):
if attr in dir(self_settings):
settings[attr] = getattr(local_settings, attr)
except Exception as e:
logger.warning(e)
return settings
| import json
import logging
from werkzeug.utils import import_string
logger = logging.getLogger(__name__)
def get_task(request):
return json.dumps({})
def configure(self_settings):
"""
Getting plugin's default settings, overwriting them with settings
- from local_settings.py, returns list of settings
? ^ ^
+ from local_settings.py, returns dict of settings
? ^ ^
"""
+ settings = {}
try:
local_settings = import_string('vulyk.local_settings')
+ for attr in dir(self_settings):
+ settings[attr] = getattr(self_settings, attr)
for attr in dir(local_settings):
if attr in dir(self_settings):
- self_settings[attr] = getattr(local_settings, attr)
? -----
+ settings[attr] = getattr(local_settings, attr)
except Exception as e:
logger.warning(e)
- return self_settings
? -----
+ return settings |
5e1815f094f40b527406a07ea1ce751ee0b074a6 | tests/__init__.py | tests/__init__.py | tests = (
'parse_token',
'variable_fields',
'filters',
'blockextend',
'template',
)
| tests = (
'parse_token',
'variable_fields',
'filters',
'default_filters',
'blockextend',
'template',
)
| Add defaults filters tests into all tests list | Add defaults filters tests into all tests list
| Python | bsd-3-clause | GrAndSE/lighty-template,GrAndSE/lighty | tests = (
'parse_token',
'variable_fields',
'filters',
+ 'default_filters',
'blockextend',
'template',
)
| Add defaults filters tests into all tests list | ## Code Before:
tests = (
'parse_token',
'variable_fields',
'filters',
'blockextend',
'template',
)
## Instruction:
Add defaults filters tests into all tests list
## Code After:
tests = (
'parse_token',
'variable_fields',
'filters',
'default_filters',
'blockextend',
'template',
)
| tests = (
'parse_token',
'variable_fields',
'filters',
+ 'default_filters',
'blockextend',
'template',
) |
b016fad5d55993b064a1c4d15fd281f439045491 | gateway/camera/device.py | gateway/camera/device.py | from gateway import net
class CameraDevice(object):
def __init__(self, stream, address):
self.resolution = None
self.framerate = None
self.__stream = stream
self.__address = address
def send(self, opcode, body=None):
packet = net.encode_packet(opcode, body)
yield self.__stream.write(packet)
| from tornado import gen
from gateway import net
class CameraDevice(object):
def __init__(self, stream, address):
self.resolution = None
self.framerate = None
self.__stream = stream
self.__address = address
@gen.coroutine
def send(self, opcode, body=None):
packet = net.encode_packet(opcode, body)
yield self.__stream.write(packet)
| Fix CameraDevice's send method is not called | Fix CameraDevice's send method is not called
Add send method @gen.coroutine decorator | Python | mit | walkover/auto-tracking-cctv-gateway | + from tornado import gen
+
from gateway import net
class CameraDevice(object):
def __init__(self, stream, address):
self.resolution = None
self.framerate = None
self.__stream = stream
self.__address = address
+ @gen.coroutine
def send(self, opcode, body=None):
packet = net.encode_packet(opcode, body)
yield self.__stream.write(packet)
| Fix CameraDevice's send method is not called | ## Code Before:
from gateway import net
class CameraDevice(object):
def __init__(self, stream, address):
self.resolution = None
self.framerate = None
self.__stream = stream
self.__address = address
def send(self, opcode, body=None):
packet = net.encode_packet(opcode, body)
yield self.__stream.write(packet)
## Instruction:
Fix CameraDevice's send method is not called
## Code After:
from tornado import gen
from gateway import net
class CameraDevice(object):
def __init__(self, stream, address):
self.resolution = None
self.framerate = None
self.__stream = stream
self.__address = address
@gen.coroutine
def send(self, opcode, body=None):
packet = net.encode_packet(opcode, body)
yield self.__stream.write(packet)
| + from tornado import gen
+
from gateway import net
class CameraDevice(object):
def __init__(self, stream, address):
self.resolution = None
self.framerate = None
self.__stream = stream
self.__address = address
+ @gen.coroutine
def send(self, opcode, body=None):
packet = net.encode_packet(opcode, body)
yield self.__stream.write(packet) |
1069565b596d3bc13b99bcae4ec831c2228e7946 | PrinterApplication.py | PrinterApplication.py | from Cura.WxApplication import WxApplication
import wx
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
super(PrinterApplication, self).run()
| from Cura.Wx.WxApplication import WxApplication
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
super(PrinterApplication, self).run()
| Move WxApplication into its own Wx submodule | Move WxApplication into its own Wx submodule
| Python | agpl-3.0 | lo0ol/Ultimaker-Cura,Curahelper/Cura,senttech/Cura,DeskboxBrazil/Cura,lo0ol/Ultimaker-Cura,bq/Ultimaker-Cura,fxtentacle/Cura,totalretribution/Cura,derekhe/Cura,ad1217/Cura,ad1217/Cura,derekhe/Cura,Curahelper/Cura,ynotstartups/Wanhao,hmflash/Cura,markwal/Cura,fieldOfView/Cura,fxtentacle/Cura,hmflash/Cura,quillford/Cura,senttech/Cura,ynotstartups/Wanhao,markwal/Cura,bq/Ultimaker-Cura,fieldOfView/Cura,DeskboxBrazil/Cura,quillford/Cura,totalretribution/Cura | - from Cura.WxApplication import WxApplication
+ from Cura.Wx.WxApplication import WxApplication
-
- import wx
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
- frame = wx.Frame(None, wx.ID_ANY, "Hello World")
- frame.Show(True)
super(PrinterApplication, self).run()
| Move WxApplication into its own Wx submodule | ## Code Before:
from Cura.WxApplication import WxApplication
import wx
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
super(PrinterApplication, self).run()
## Instruction:
Move WxApplication into its own Wx submodule
## Code After:
from Cura.Wx.WxApplication import WxApplication
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
super(PrinterApplication, self).run()
| - from Cura.WxApplication import WxApplication
+ from Cura.Wx.WxApplication import WxApplication
? +++
-
- import wx
class PrinterApplication(WxApplication):
def __init__(self):
super(PrinterApplication, self).__init__()
def run(self):
- frame = wx.Frame(None, wx.ID_ANY, "Hello World")
- frame.Show(True)
super(PrinterApplication, self).run() |
1f90a3d733de99cc9c412cdd559ed3ad26519acc | autoencoder/api.py | autoencoder/api.py | from .io import preprocess
from .train import train
from .encode import encode
def autoencode(count_matrix, kfold=None,
censor_matrix=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=kfold, censor=censor_matrix)
model = train(x, hidden_size=hidden_size, learning_rate=learning_rate,
aetype=type, epochs=epochs)
encoded = encode(count_matrix, model)
return encoded
| from .io import preprocess
from .train import train
from .encode import encode
def autoencode(count_matrix, kfold=None, reduced=False,
censor_matrix=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=kfold, censor=censor_matrix)
model = train(x, hidden_size=hidden_size, learning_rate=learning_rate,
aetype=type, epochs=epochs)
encoded = encode(count_matrix, model, reduced=reduced)
return encoded
| Add reduce option to API | Add reduce option to API
| Python | apache-2.0 | theislab/dca,theislab/dca,theislab/dca | from .io import preprocess
from .train import train
from .encode import encode
- def autoencode(count_matrix, kfold=None,
+ def autoencode(count_matrix, kfold=None, reduced=False,
censor_matrix=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=kfold, censor=censor_matrix)
model = train(x, hidden_size=hidden_size, learning_rate=learning_rate,
aetype=type, epochs=epochs)
- encoded = encode(count_matrix, model)
+ encoded = encode(count_matrix, model, reduced=reduced)
return encoded
| Add reduce option to API | ## Code Before:
from .io import preprocess
from .train import train
from .encode import encode
def autoencode(count_matrix, kfold=None,
censor_matrix=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=kfold, censor=censor_matrix)
model = train(x, hidden_size=hidden_size, learning_rate=learning_rate,
aetype=type, epochs=epochs)
encoded = encode(count_matrix, model)
return encoded
## Instruction:
Add reduce option to API
## Code After:
from .io import preprocess
from .train import train
from .encode import encode
def autoencode(count_matrix, kfold=None, reduced=False,
censor_matrix=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=kfold, censor=censor_matrix)
model = train(x, hidden_size=hidden_size, learning_rate=learning_rate,
aetype=type, epochs=epochs)
encoded = encode(count_matrix, model, reduced=reduced)
return encoded
| from .io import preprocess
from .train import train
from .encode import encode
- def autoencode(count_matrix, kfold=None,
+ def autoencode(count_matrix, kfold=None, reduced=False,
? +++++++++++++++
censor_matrix=None, type='normal',
learning_rate=1e-2,
hidden_size=10,
epochs=10):
x = preprocess(count_matrix, kfold=kfold, censor=censor_matrix)
model = train(x, hidden_size=hidden_size, learning_rate=learning_rate,
aetype=type, epochs=epochs)
- encoded = encode(count_matrix, model)
+ encoded = encode(count_matrix, model, reduced=reduced)
? +++++++++++++++++
return encoded |
d16a3753d73714a51fbe846e45fe77d5e41cb2ab | examples/dup_and_replay.py | examples/dup_and_replay.py | from mitmproxy import ctx
def request(flow):
f = ctx.master.state.duplicate_flow(flow)
f.request.path = "/changed"
ctx.master.replay_request(f, block=True, run_scripthooks=False)
| from mitmproxy import ctx
def request(flow):
f = ctx.master.state.duplicate_flow(flow)
f.request.path = "/changed"
ctx.master.replay_request(f, block=True)
| Remove dead run_scripthooks example reference. | Remove dead run_scripthooks example reference. | Python | mit | xaxa89/mitmproxy,Kriechi/mitmproxy,cortesi/mitmproxy,zlorb/mitmproxy,dwfreed/mitmproxy,ujjwal96/mitmproxy,vhaupert/mitmproxy,mosajjal/mitmproxy,laurmurclar/mitmproxy,ujjwal96/mitmproxy,Kriechi/mitmproxy,xaxa89/mitmproxy,MatthewShao/mitmproxy,dwfreed/mitmproxy,mosajjal/mitmproxy,mitmproxy/mitmproxy,ddworken/mitmproxy,mosajjal/mitmproxy,mhils/mitmproxy,mitmproxy/mitmproxy,mosajjal/mitmproxy,mitmproxy/mitmproxy,zlorb/mitmproxy,xaxa89/mitmproxy,MatthewShao/mitmproxy,dwfreed/mitmproxy,mitmproxy/mitmproxy,mitmproxy/mitmproxy,Kriechi/mitmproxy,StevenVanAcker/mitmproxy,vhaupert/mitmproxy,vhaupert/mitmproxy,laurmurclar/mitmproxy,MatthewShao/mitmproxy,cortesi/mitmproxy,ddworken/mitmproxy,vhaupert/mitmproxy,dwfreed/mitmproxy,zlorb/mitmproxy,mhils/mitmproxy,ddworken/mitmproxy,cortesi/mitmproxy,ujjwal96/mitmproxy,laurmurclar/mitmproxy,xaxa89/mitmproxy,StevenVanAcker/mitmproxy,cortesi/mitmproxy,ddworken/mitmproxy,laurmurclar/mitmproxy,mhils/mitmproxy,zlorb/mitmproxy,StevenVanAcker/mitmproxy,mhils/mitmproxy,mhils/mitmproxy,StevenVanAcker/mitmproxy,Kriechi/mitmproxy,ujjwal96/mitmproxy,MatthewShao/mitmproxy | from mitmproxy import ctx
def request(flow):
f = ctx.master.state.duplicate_flow(flow)
f.request.path = "/changed"
- ctx.master.replay_request(f, block=True, run_scripthooks=False)
+ ctx.master.replay_request(f, block=True)
| Remove dead run_scripthooks example reference. | ## Code Before:
from mitmproxy import ctx
def request(flow):
f = ctx.master.state.duplicate_flow(flow)
f.request.path = "/changed"
ctx.master.replay_request(f, block=True, run_scripthooks=False)
## Instruction:
Remove dead run_scripthooks example reference.
## Code After:
from mitmproxy import ctx
def request(flow):
f = ctx.master.state.duplicate_flow(flow)
f.request.path = "/changed"
ctx.master.replay_request(f, block=True)
| from mitmproxy import ctx
def request(flow):
f = ctx.master.state.duplicate_flow(flow)
f.request.path = "/changed"
- ctx.master.replay_request(f, block=True, run_scripthooks=False)
? -----------------------
+ ctx.master.replay_request(f, block=True) |
91d24b3ce272ff166d1e828f0822e7b9a0124d2c | tests/test_dataset.py | tests/test_dataset.py | import pytest
from zfssnap import Host, Dataset
import subprocess
PROPERTY_PREFIX = 'zfssnap'
class TestDataset(object):
@pytest.fixture
def fs(self):
fs_name = 'zpool/dataset'
host = Host()
return Dataset(host, fs_name)
@pytest.fixture
def ssh_fs(self):
ssh_user = 'root'
ssh_host = 'host'
fs_name = 'zpool/dataset'
host = Host(ssh_user=ssh_user, ssh_host=ssh_host)
return Dataset(host, fs_name)
def test_autoconvert_to_int(self):
assert isinstance(Dataset._autoconvert('123'), int)
def test_autoconvert_to_str(self):
assert isinstance(Dataset._autoconvert('12f'), str)
def test_return_local_location(self, fs):
assert fs.location == 'zpool/dataset'
def test_return_ssh_location(self, ssh_fs):
assert ssh_fs.location == 'root@host:zpool/dataset' | import pytest
from zfssnap import autotype, Host, Dataset
import subprocess
PROPERTY_PREFIX = 'zfssnap'
class TestDataset(object):
@pytest.fixture
def fs(self):
fs_name = 'zpool/dataset'
host = Host()
return Dataset(host, fs_name)
@pytest.fixture
def ssh_fs(self):
ssh_user = 'root'
ssh_host = 'host'
fs_name = 'zpool/dataset'
host = Host(ssh_user=ssh_user, ssh_host=ssh_host)
return Dataset(host, fs_name)
def test_autotype_to_int(self):
assert isinstance(autotype('123'), int)
def test_autotype_to_str(self):
assert isinstance(autotype('12f'), str)
def test_return_local_location(self, fs):
assert fs.location == 'zpool/dataset'
def test_return_ssh_location(self, ssh_fs):
assert ssh_fs.location == 'root@host:zpool/dataset' | Fix broken tests after moving _autoconvert to autotype | Fix broken tests after moving _autoconvert to autotype
| Python | mit | hkbakke/zfssnap,hkbakke/zfssnap | import pytest
- from zfssnap import Host, Dataset
+ from zfssnap import autotype, Host, Dataset
import subprocess
PROPERTY_PREFIX = 'zfssnap'
class TestDataset(object):
@pytest.fixture
def fs(self):
fs_name = 'zpool/dataset'
host = Host()
return Dataset(host, fs_name)
@pytest.fixture
def ssh_fs(self):
ssh_user = 'root'
ssh_host = 'host'
fs_name = 'zpool/dataset'
host = Host(ssh_user=ssh_user, ssh_host=ssh_host)
return Dataset(host, fs_name)
- def test_autoconvert_to_int(self):
+ def test_autotype_to_int(self):
- assert isinstance(Dataset._autoconvert('123'), int)
+ assert isinstance(autotype('123'), int)
- def test_autoconvert_to_str(self):
+ def test_autotype_to_str(self):
- assert isinstance(Dataset._autoconvert('12f'), str)
+ assert isinstance(autotype('12f'), str)
def test_return_local_location(self, fs):
assert fs.location == 'zpool/dataset'
def test_return_ssh_location(self, ssh_fs):
assert ssh_fs.location == 'root@host:zpool/dataset' | Fix broken tests after moving _autoconvert to autotype | ## Code Before:
import pytest
from zfssnap import Host, Dataset
import subprocess
PROPERTY_PREFIX = 'zfssnap'
class TestDataset(object):
@pytest.fixture
def fs(self):
fs_name = 'zpool/dataset'
host = Host()
return Dataset(host, fs_name)
@pytest.fixture
def ssh_fs(self):
ssh_user = 'root'
ssh_host = 'host'
fs_name = 'zpool/dataset'
host = Host(ssh_user=ssh_user, ssh_host=ssh_host)
return Dataset(host, fs_name)
def test_autoconvert_to_int(self):
assert isinstance(Dataset._autoconvert('123'), int)
def test_autoconvert_to_str(self):
assert isinstance(Dataset._autoconvert('12f'), str)
def test_return_local_location(self, fs):
assert fs.location == 'zpool/dataset'
def test_return_ssh_location(self, ssh_fs):
assert ssh_fs.location == 'root@host:zpool/dataset'
## Instruction:
Fix broken tests after moving _autoconvert to autotype
## Code After:
import pytest
from zfssnap import autotype, Host, Dataset
import subprocess
PROPERTY_PREFIX = 'zfssnap'
class TestDataset(object):
@pytest.fixture
def fs(self):
fs_name = 'zpool/dataset'
host = Host()
return Dataset(host, fs_name)
@pytest.fixture
def ssh_fs(self):
ssh_user = 'root'
ssh_host = 'host'
fs_name = 'zpool/dataset'
host = Host(ssh_user=ssh_user, ssh_host=ssh_host)
return Dataset(host, fs_name)
def test_autotype_to_int(self):
assert isinstance(autotype('123'), int)
def test_autotype_to_str(self):
assert isinstance(autotype('12f'), str)
def test_return_local_location(self, fs):
assert fs.location == 'zpool/dataset'
def test_return_ssh_location(self, ssh_fs):
assert ssh_fs.location == 'root@host:zpool/dataset' | import pytest
- from zfssnap import Host, Dataset
+ from zfssnap import autotype, Host, Dataset
? ++++++++++
import subprocess
PROPERTY_PREFIX = 'zfssnap'
class TestDataset(object):
@pytest.fixture
def fs(self):
fs_name = 'zpool/dataset'
host = Host()
return Dataset(host, fs_name)
@pytest.fixture
def ssh_fs(self):
ssh_user = 'root'
ssh_host = 'host'
fs_name = 'zpool/dataset'
host = Host(ssh_user=ssh_user, ssh_host=ssh_host)
return Dataset(host, fs_name)
- def test_autoconvert_to_int(self):
? ^^^^ --
+ def test_autotype_to_int(self):
? ^^^
- assert isinstance(Dataset._autoconvert('123'), int)
? --------- ^^^^ --
+ assert isinstance(autotype('123'), int)
? ^^^
- def test_autoconvert_to_str(self):
? ^^^^ --
+ def test_autotype_to_str(self):
? ^^^
- assert isinstance(Dataset._autoconvert('12f'), str)
? --------- ^^^^ --
+ assert isinstance(autotype('12f'), str)
? ^^^
def test_return_local_location(self, fs):
assert fs.location == 'zpool/dataset'
def test_return_ssh_location(self, ssh_fs):
assert ssh_fs.location == 'root@host:zpool/dataset' |
36c2e7449b7817a66b60eaff4c8518ae6d4f4a01 | categories/tests.py | categories/tests.py | from .models import Category
from .serializers import CategorySerializer
from employees.models import Employee
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class CategoryTestCase(APITestCase):
def setUp(self):
Category.objects.create(name='Coworker')
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Category.objects.create(name='Category1', weight=2)
Category.objects.create(name='Category2')
self.client.login(username='user1', password='user1password')
def test_category_creation(self):
category1 = Category.objects.get(name='Category1')
category2 = Category.objects.get(name='Category2')
self.assertEqual(category1.weight, 2)
self.assertEqual(category2.weight, 1)
def test_category_list(self):
categories = Category.objects.all()
response_data = CategorySerializer(categories, many=True).data
url = reverse('categories:category_list')
response = self.client.get(url, format='json')
self.assertEqual(response.data, response_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
| from .models import Category
from .serializers import CategorySerializer
from employees.models import Employee
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class CategoryTestCase(APITestCase):
def setUp(self):
Category.objects.create(name='Coworker')
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Category.objects.create(name='Category1', weight=2)
Category.objects.create(name='Category2')
self.client.login(username='user1', password='user1password')
def test_category_creation(self):
category1 = Category.objects.get(name='Category1')
category2 = Category.objects.get(name='Category2')
self.assertEqual(category1.weight, 2)
self.assertEqual(category2.weight, 1)
| Remove categoy_list test until urls will fixed. | Remove categoy_list test until urls will fixed.
| Python | apache-2.0 | belatrix/BackendAllStars | from .models import Category
from .serializers import CategorySerializer
from employees.models import Employee
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class CategoryTestCase(APITestCase):
def setUp(self):
Category.objects.create(name='Coworker')
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Category.objects.create(name='Category1', weight=2)
Category.objects.create(name='Category2')
self.client.login(username='user1', password='user1password')
def test_category_creation(self):
category1 = Category.objects.get(name='Category1')
category2 = Category.objects.get(name='Category2')
self.assertEqual(category1.weight, 2)
self.assertEqual(category2.weight, 1)
- def test_category_list(self):
- categories = Category.objects.all()
- response_data = CategorySerializer(categories, many=True).data
- url = reverse('categories:category_list')
- response = self.client.get(url, format='json')
- self.assertEqual(response.data, response_data)
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- | Remove categoy_list test until urls will fixed. | ## Code Before:
from .models import Category
from .serializers import CategorySerializer
from employees.models import Employee
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class CategoryTestCase(APITestCase):
def setUp(self):
Category.objects.create(name='Coworker')
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Category.objects.create(name='Category1', weight=2)
Category.objects.create(name='Category2')
self.client.login(username='user1', password='user1password')
def test_category_creation(self):
category1 = Category.objects.get(name='Category1')
category2 = Category.objects.get(name='Category2')
self.assertEqual(category1.weight, 2)
self.assertEqual(category2.weight, 1)
def test_category_list(self):
categories = Category.objects.all()
response_data = CategorySerializer(categories, many=True).data
url = reverse('categories:category_list')
response = self.client.get(url, format='json')
self.assertEqual(response.data, response_data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
## Instruction:
Remove categoy_list test until urls will fixed.
## Code After:
from .models import Category
from .serializers import CategorySerializer
from employees.models import Employee
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class CategoryTestCase(APITestCase):
def setUp(self):
Category.objects.create(name='Coworker')
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Category.objects.create(name='Category1', weight=2)
Category.objects.create(name='Category2')
self.client.login(username='user1', password='user1password')
def test_category_creation(self):
category1 = Category.objects.get(name='Category1')
category2 = Category.objects.get(name='Category2')
self.assertEqual(category1.weight, 2)
self.assertEqual(category2.weight, 1)
| from .models import Category
from .serializers import CategorySerializer
from employees.models import Employee
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class CategoryTestCase(APITestCase):
def setUp(self):
Category.objects.create(name='Coworker')
Employee.objects.create_superuser('user1', 'user1@email.com', 'user1password')
Category.objects.create(name='Category1', weight=2)
Category.objects.create(name='Category2')
self.client.login(username='user1', password='user1password')
def test_category_creation(self):
category1 = Category.objects.get(name='Category1')
category2 = Category.objects.get(name='Category2')
self.assertEqual(category1.weight, 2)
self.assertEqual(category2.weight, 1)
-
- def test_category_list(self):
- categories = Category.objects.all()
- response_data = CategorySerializer(categories, many=True).data
- url = reverse('categories:category_list')
- response = self.client.get(url, format='json')
- self.assertEqual(response.data, response_data)
- self.assertEqual(response.status_code, status.HTTP_200_OK) |
bb34b21ebd2378f944498708ac4f13d16aa61aa1 | src/mist/io/tests/api/features/steps/backends.py | src/mist/io/tests/api/features/steps/backends.py | from behave import *
@given(u'"{text}" backend added')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = context.client.list_backends() | from behave import *
@given(u'"{text}" backend added through api')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = context.client.list_backends() | Rename Behave steps for api tests | Rename Behave steps for api tests
| Python | agpl-3.0 | johnnyWalnut/mist.io,DimensionDataCBUSydney/mist.io,zBMNForks/mist.io,afivos/mist.io,Lao-liu/mist.io,Lao-liu/mist.io,munkiat/mist.io,kelonye/mist.io,kelonye/mist.io,afivos/mist.io,Lao-liu/mist.io,Lao-liu/mist.io,DimensionDataCBUSydney/mist.io,johnnyWalnut/mist.io,zBMNForks/mist.io,DimensionDataCBUSydney/mist.io,DimensionDataCBUSydney/mist.io,munkiat/mist.io,zBMNForks/mist.io,munkiat/mist.io,johnnyWalnut/mist.io,afivos/mist.io,munkiat/mist.io,kelonye/mist.io | from behave import *
- @given(u'"{text}" backend added')
+ @given(u'"{text}" backend added through api')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = context.client.list_backends() | Rename Behave steps for api tests | ## Code Before:
from behave import *
@given(u'"{text}" backend added')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = context.client.list_backends()
## Instruction:
Rename Behave steps for api tests
## Code After:
from behave import *
@given(u'"{text}" backend added through api')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = context.client.list_backends() | from behave import *
- @given(u'"{text}" backend added')
+ @given(u'"{text}" backend added through api')
? ++++++++++++
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = context.client.list_backends() |
87d2e511b0fedd2a09610c35337336d443a756a4 | tests/unit/cli/filewatch/test_stat.py | tests/unit/cli/filewatch/test_stat.py | import os
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
assert len(calls) == 1
| import os
import time
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
for _ in range(10):
if len(calls) == 1:
break
time.sleep(0.2)
else:
raise AssertionError("Expected callback to be invoked but was not.")
| Add polling loop to allow time for callback to be invoked | Add polling loop to allow time for callback to be invoked
| Python | apache-2.0 | awslabs/chalice | import os
+ import time
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
+ for _ in range(10):
- assert len(calls) == 1
+ if len(calls) == 1:
+ break
+ time.sleep(0.2)
+ else:
+ raise AssertionError("Expected callback to be invoked but was not.")
| Add polling loop to allow time for callback to be invoked | ## Code Before:
import os
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
assert len(calls) == 1
## Instruction:
Add polling loop to allow time for callback to be invoked
## Code After:
import os
import time
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
for _ in range(10):
if len(calls) == 1:
break
time.sleep(0.2)
else:
raise AssertionError("Expected callback to be invoked but was not.")
| import os
+ import time
from chalice.cli.filewatch import stat
class FakeOSUtils(object):
def __init__(self):
self.initial_scan = True
def walk(self, rootdir):
yield 'rootdir', [], ['bad-file', 'baz']
if self.initial_scan:
self.initial_scan = False
def joinpath(self, *parts):
return os.path.join(*parts)
def mtime(self, path):
if self.initial_scan:
return 1
if path.endswith('bad-file'):
raise OSError("Bad file")
return 2
def test_can_ignore_stat_errors():
calls = []
def callback(*args, **kwargs):
calls.append((args, kwargs))
watcher = stat.StatFileWatcher(FakeOSUtils())
watcher.watch_for_file_changes('rootdir', callback)
+ for _ in range(10):
- assert len(calls) == 1
? ^^^^^^
+ if len(calls) == 1:
? ^^^^^^ +
+ break
+ time.sleep(0.2)
+ else:
+ raise AssertionError("Expected callback to be invoked but was not.") |
d31382c666444c4947ca35bb67ddb851236e2e49 | automata/automaton.py | automata/automaton.py |
import abc
class AutomatonError(Exception):
"""the base class for all automaton-related errors"""
pass
class InvalidStateError(AutomatonError):
"""a state is not a valid state for this automaton"""
pass
class InvalidSymbolError(AutomatonError):
"""a symbol is not a valid symbol for this automaton"""
pass
class MissingStateError(AutomatonError):
"""a state is missing from the transition function"""
pass
class MissingSymbolError(AutomatonError):
"""a symbol is missing from the transition function"""
pass
class FinalStateError(AutomatonError):
"""the automaton stopped at a non-final state"""
pass
class Automaton(metaclass=abc.ABCMeta):
def __init__(self, states, symbols, transitions, initial_state,
final_states):
"""initialize a complete finite automaton"""
self.states = states
self.symbols = symbols
self.transitions = transitions
self.initial_state = initial_state
self.final_states = final_states
self.validate_automaton()
@abc.abstractmethod
def validate_input(self):
pass
@abc.abstractmethod
def validate_automaton(self):
pass
|
import abc
class Automaton(metaclass=abc.ABCMeta):
def __init__(self, states, symbols, transitions, initial_state,
final_states):
"""initialize a complete finite automaton"""
self.states = states
self.symbols = symbols
self.transitions = transitions
self.initial_state = initial_state
self.final_states = final_states
self.validate_automaton()
@abc.abstractmethod
def validate_input(self):
pass
@abc.abstractmethod
def validate_automaton(self):
pass
class AutomatonError(Exception):
"""the base class for all automaton-related errors"""
pass
class InvalidStateError(AutomatonError):
"""a state is not a valid state for this automaton"""
pass
class InvalidSymbolError(AutomatonError):
"""a symbol is not a valid symbol for this automaton"""
pass
class MissingStateError(AutomatonError):
"""a state is missing from the transition function"""
pass
class MissingSymbolError(AutomatonError):
"""a symbol is missing from the transition function"""
pass
class FinalStateError(AutomatonError):
"""the automaton stopped at a non-final state"""
pass
| Move Automaton class above exception classes | Move Automaton class above exception classes
| Python | mit | caleb531/automata |
import abc
+
+
+ class Automaton(metaclass=abc.ABCMeta):
+
+ def __init__(self, states, symbols, transitions, initial_state,
+ final_states):
+ """initialize a complete finite automaton"""
+ self.states = states
+ self.symbols = symbols
+ self.transitions = transitions
+ self.initial_state = initial_state
+ self.final_states = final_states
+ self.validate_automaton()
+
+ @abc.abstractmethod
+ def validate_input(self):
+ pass
+
+ @abc.abstractmethod
+ def validate_automaton(self):
+ pass
class AutomatonError(Exception):
"""the base class for all automaton-related errors"""
pass
class InvalidStateError(AutomatonError):
"""a state is not a valid state for this automaton"""
pass
class InvalidSymbolError(AutomatonError):
"""a symbol is not a valid symbol for this automaton"""
pass
class MissingStateError(AutomatonError):
"""a state is missing from the transition function"""
pass
class MissingSymbolError(AutomatonError):
"""a symbol is missing from the transition function"""
pass
class FinalStateError(AutomatonError):
"""the automaton stopped at a non-final state"""
pass
-
- class Automaton(metaclass=abc.ABCMeta):
-
- def __init__(self, states, symbols, transitions, initial_state,
- final_states):
- """initialize a complete finite automaton"""
- self.states = states
- self.symbols = symbols
- self.transitions = transitions
- self.initial_state = initial_state
- self.final_states = final_states
- self.validate_automaton()
-
- @abc.abstractmethod
- def validate_input(self):
- pass
-
- @abc.abstractmethod
- def validate_automaton(self):
- pass
- | Move Automaton class above exception classes | ## Code Before:
import abc
class AutomatonError(Exception):
"""the base class for all automaton-related errors"""
pass
class InvalidStateError(AutomatonError):
"""a state is not a valid state for this automaton"""
pass
class InvalidSymbolError(AutomatonError):
"""a symbol is not a valid symbol for this automaton"""
pass
class MissingStateError(AutomatonError):
"""a state is missing from the transition function"""
pass
class MissingSymbolError(AutomatonError):
"""a symbol is missing from the transition function"""
pass
class FinalStateError(AutomatonError):
"""the automaton stopped at a non-final state"""
pass
class Automaton(metaclass=abc.ABCMeta):
def __init__(self, states, symbols, transitions, initial_state,
final_states):
"""initialize a complete finite automaton"""
self.states = states
self.symbols = symbols
self.transitions = transitions
self.initial_state = initial_state
self.final_states = final_states
self.validate_automaton()
@abc.abstractmethod
def validate_input(self):
pass
@abc.abstractmethod
def validate_automaton(self):
pass
## Instruction:
Move Automaton class above exception classes
## Code After:
import abc
class Automaton(metaclass=abc.ABCMeta):
def __init__(self, states, symbols, transitions, initial_state,
final_states):
"""initialize a complete finite automaton"""
self.states = states
self.symbols = symbols
self.transitions = transitions
self.initial_state = initial_state
self.final_states = final_states
self.validate_automaton()
@abc.abstractmethod
def validate_input(self):
pass
@abc.abstractmethod
def validate_automaton(self):
pass
class AutomatonError(Exception):
"""the base class for all automaton-related errors"""
pass
class InvalidStateError(AutomatonError):
"""a state is not a valid state for this automaton"""
pass
class InvalidSymbolError(AutomatonError):
"""a symbol is not a valid symbol for this automaton"""
pass
class MissingStateError(AutomatonError):
"""a state is missing from the transition function"""
pass
class MissingSymbolError(AutomatonError):
"""a symbol is missing from the transition function"""
pass
class FinalStateError(AutomatonError):
"""the automaton stopped at a non-final state"""
pass
|
import abc
+
+
+ class Automaton(metaclass=abc.ABCMeta):
+
+ def __init__(self, states, symbols, transitions, initial_state,
+ final_states):
+ """initialize a complete finite automaton"""
+ self.states = states
+ self.symbols = symbols
+ self.transitions = transitions
+ self.initial_state = initial_state
+ self.final_states = final_states
+ self.validate_automaton()
+
+ @abc.abstractmethod
+ def validate_input(self):
+ pass
+
+ @abc.abstractmethod
+ def validate_automaton(self):
+ pass
class AutomatonError(Exception):
"""the base class for all automaton-related errors"""
pass
class InvalidStateError(AutomatonError):
"""a state is not a valid state for this automaton"""
pass
class InvalidSymbolError(AutomatonError):
"""a symbol is not a valid symbol for this automaton"""
pass
class MissingStateError(AutomatonError):
"""a state is missing from the transition function"""
pass
class MissingSymbolError(AutomatonError):
"""a symbol is missing from the transition function"""
pass
class FinalStateError(AutomatonError):
"""the automaton stopped at a non-final state"""
pass
-
-
- class Automaton(metaclass=abc.ABCMeta):
-
- def __init__(self, states, symbols, transitions, initial_state,
- final_states):
- """initialize a complete finite automaton"""
- self.states = states
- self.symbols = symbols
- self.transitions = transitions
- self.initial_state = initial_state
- self.final_states = final_states
- self.validate_automaton()
-
- @abc.abstractmethod
- def validate_input(self):
- pass
-
- @abc.abstractmethod
- def validate_automaton(self):
- pass |
49f5802a02a550cc8cee3be417426a83c31de5c9 | Source/Git/Experiments/git_log.py | Source/Git/Experiments/git_log.py | import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
| import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
if index > 1:
break
| Exit the loop early when experimenting. | Exit the loop early when experimenting. | Python | apache-2.0 | barry-scott/scm-workbench,barry-scott/scm-workbench,barry-scott/scm-workbench | import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
+ if index > 1:
+ break
+ | Exit the loop early when experimenting. | ## Code Before:
import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
## Instruction:
Exit the loop early when experimenting.
## Code After:
import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
if index > 1:
break
| import sys
import git
r = git.Repo( sys.argv[1] )
def printTree( tree, indent=0 ):
prefix = ' '*indent
print( prefix, '-' * 16 )
print( prefix, 'Tree path %s' % (tree.path,) )
for blob in tree:
print( prefix, '%s %s (%s)' % (blob.type, blob.path, blob.hexsha) )
for child in tree.trees:
printTree( child, indent+4 )
for index, commit in enumerate(r.iter_commits( None )):
print( '=' * 60 )
for name in sorted( dir( commit ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
print( 'Commit: %s: %r' % (name, getattr( commit, name )) )
print( '-' * 60 )
stats = commit.stats
for name in sorted( dir( stats ) ):
if name[0] not in 'abcdefghijklmnopqrstuvwxyz':
continue
if name == 'files':
for file in stats.files:
print( 'Commit.Stats.files: %s: %r' % (file, stats.files[file]) )
else:
print( 'Commit.Stats: %s: %r' % (name, getattr( stats, name )) )
print( '-' * 60 )
tree = commit.tree
printTree( tree )
+
+ if index > 1:
+ break |
e2962b3888a2a82cff8f0f01a213c0a123873f60 | application.py | application.py |
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
manager = init_manager(application, 5000, ['./json_schemas'])
@manager.command
def update_index(index_name):
from app.main.services.search_service import create_index
with application.app_context():
message, status = create_index(index_name)
assert status == 200, message
application.logger.info("Created index %s", index_name)
if __name__ == '__main__':
manager.run()
|
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
manager = init_manager(application, 5001, ['./mappings'])
@manager.command
def update_index(index_name):
from app.main.services.search_service import create_index
with application.app_context():
message, status = create_index(index_name)
assert status == 200, message
application.logger.info("Created index %s", index_name)
if __name__ == '__main__':
manager.run()
| Fix local search-api port to 5001 | Fix local search-api port to 5001
When upgrading dmutils I've copied the new `init_manager` code from
the API but forgot to update the port.
Also adds mappings to the list of watched locations for the development
server, so the app will restart if the files are modified.
| Python | mit | alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api |
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
- manager = init_manager(application, 5000, ['./json_schemas'])
+ manager = init_manager(application, 5001, ['./mappings'])
@manager.command
def update_index(index_name):
from app.main.services.search_service import create_index
with application.app_context():
message, status = create_index(index_name)
assert status == 200, message
application.logger.info("Created index %s", index_name)
if __name__ == '__main__':
manager.run()
| Fix local search-api port to 5001 | ## Code Before:
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
manager = init_manager(application, 5000, ['./json_schemas'])
@manager.command
def update_index(index_name):
from app.main.services.search_service import create_index
with application.app_context():
message, status = create_index(index_name)
assert status == 200, message
application.logger.info("Created index %s", index_name)
if __name__ == '__main__':
manager.run()
## Instruction:
Fix local search-api port to 5001
## Code After:
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
manager = init_manager(application, 5001, ['./mappings'])
@manager.command
def update_index(index_name):
from app.main.services.search_service import create_index
with application.app_context():
message, status = create_index(index_name)
assert status == 200, message
application.logger.info("Created index %s", index_name)
if __name__ == '__main__':
manager.run()
|
import os
from dmutils import init_manager
from app import create_app
application = create_app(os.getenv('DM_ENVIRONMENT') or 'development')
- manager = init_manager(application, 5000, ['./json_schemas'])
? ^ ---------
+ manager = init_manager(application, 5001, ['./mappings'])
? ^ +++++
@manager.command
def update_index(index_name):
from app.main.services.search_service import create_index
with application.app_context():
message, status = create_index(index_name)
assert status == 200, message
application.logger.info("Created index %s", index_name)
if __name__ == '__main__':
manager.run() |
0da5820816187dd6b6d6ebbd554fc9646853e0fc | tests/git_code_debt/logic_test.py | tests/git_code_debt/logic_test.py |
import testify as T
from git_code_debt.create_tables import get_metric_ids
from git_code_debt.discovery import get_metric_parsers
from git_code_debt.logic import get_metric_mapping
from testing.base_classes.sandbox_test_case import SandboxTestCase
class TestLogic(SandboxTestCase):
def test_get_metric_mapping(self):
with self.db() as db:
ret = get_metric_mapping(db)
T.assert_equal(set(ret.keys()), set(get_metric_ids(get_metric_parsers())))
|
import testify as T
from git_code_debt.create_tables import get_metric_ids
from git_code_debt.discovery import get_metric_parsers
from git_code_debt.logic import get_metric_mapping
from git_code_debt.logic import get_metric_values
from git_code_debt.logic import get_previous_sha
from git_code_debt.logic import insert_metric_values
from git_code_debt.repo_parser import Commit
from testing.base_classes.sandbox_test_case import SandboxTestCase
class TestLogic(SandboxTestCase):
sha = 'a' * 40
repo = 'git@github.com:asottile/git-code-debt'
def test_get_metric_mapping(self):
with self.db() as db:
ret = get_metric_mapping(db)
T.assert_equal(set(ret.keys()), set(get_metric_ids(get_metric_parsers())))
def test_get_previous_sha_no_previous_sha(self):
with self.db() as db:
ret = get_previous_sha(db, self.repo)
T.assert_is(ret, None)
def get_fake_metrics(self, metric_mapping):
return dict(
(metric_name, 1) for metric_name in metric_mapping.keys()
)
def get_fake_commit(self):
return Commit(self.sha, 1, 'foo')
def insert_fake_metrics(self, db):
metric_mapping = get_metric_mapping(db)
metric_values = self.get_fake_metrics(metric_mapping)
commit = self.get_fake_commit()
insert_metric_values(db, metric_values, metric_mapping, self.repo, commit)
def test_get_previous_sha_previous_existing_sha(self):
with self.db() as db:
self.insert_fake_metrics(db)
ret = get_previous_sha(db, self.repo)
T.assert_equal(ret, self.sha)
def test_insert_and_get_metric_values(self):
with self.db() as db:
fake_metrics = self.get_fake_metrics(get_metric_mapping(db))
fake_commit = self.get_fake_commit()
self.insert_fake_metrics(db)
T.assert_equal(fake_metrics, get_metric_values(db, fake_commit))
| Add more tests to logic test | Add more tests to logic test
| Python | mit | ucarion/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,ucarion/git-code-debt,Yelp/git-code-debt |
import testify as T
from git_code_debt.create_tables import get_metric_ids
from git_code_debt.discovery import get_metric_parsers
from git_code_debt.logic import get_metric_mapping
+ from git_code_debt.logic import get_metric_values
+ from git_code_debt.logic import get_previous_sha
+ from git_code_debt.logic import insert_metric_values
+ from git_code_debt.repo_parser import Commit
from testing.base_classes.sandbox_test_case import SandboxTestCase
class TestLogic(SandboxTestCase):
+
+ sha = 'a' * 40
+ repo = 'git@github.com:asottile/git-code-debt'
def test_get_metric_mapping(self):
with self.db() as db:
ret = get_metric_mapping(db)
T.assert_equal(set(ret.keys()), set(get_metric_ids(get_metric_parsers())))
+ def test_get_previous_sha_no_previous_sha(self):
+ with self.db() as db:
+ ret = get_previous_sha(db, self.repo)
+ T.assert_is(ret, None)
+
+ def get_fake_metrics(self, metric_mapping):
+ return dict(
+ (metric_name, 1) for metric_name in metric_mapping.keys()
+ )
+
+ def get_fake_commit(self):
+ return Commit(self.sha, 1, 'foo')
+
+ def insert_fake_metrics(self, db):
+ metric_mapping = get_metric_mapping(db)
+ metric_values = self.get_fake_metrics(metric_mapping)
+ commit = self.get_fake_commit()
+ insert_metric_values(db, metric_values, metric_mapping, self.repo, commit)
+
+ def test_get_previous_sha_previous_existing_sha(self):
+ with self.db() as db:
+ self.insert_fake_metrics(db)
+ ret = get_previous_sha(db, self.repo)
+ T.assert_equal(ret, self.sha)
+
+ def test_insert_and_get_metric_values(self):
+ with self.db() as db:
+ fake_metrics = self.get_fake_metrics(get_metric_mapping(db))
+ fake_commit = self.get_fake_commit()
+ self.insert_fake_metrics(db)
+ T.assert_equal(fake_metrics, get_metric_values(db, fake_commit))
+ | Add more tests to logic test | ## Code Before:
import testify as T
from git_code_debt.create_tables import get_metric_ids
from git_code_debt.discovery import get_metric_parsers
from git_code_debt.logic import get_metric_mapping
from testing.base_classes.sandbox_test_case import SandboxTestCase
class TestLogic(SandboxTestCase):
def test_get_metric_mapping(self):
with self.db() as db:
ret = get_metric_mapping(db)
T.assert_equal(set(ret.keys()), set(get_metric_ids(get_metric_parsers())))
## Instruction:
Add more tests to logic test
## Code After:
import testify as T
from git_code_debt.create_tables import get_metric_ids
from git_code_debt.discovery import get_metric_parsers
from git_code_debt.logic import get_metric_mapping
from git_code_debt.logic import get_metric_values
from git_code_debt.logic import get_previous_sha
from git_code_debt.logic import insert_metric_values
from git_code_debt.repo_parser import Commit
from testing.base_classes.sandbox_test_case import SandboxTestCase
class TestLogic(SandboxTestCase):
sha = 'a' * 40
repo = 'git@github.com:asottile/git-code-debt'
def test_get_metric_mapping(self):
with self.db() as db:
ret = get_metric_mapping(db)
T.assert_equal(set(ret.keys()), set(get_metric_ids(get_metric_parsers())))
def test_get_previous_sha_no_previous_sha(self):
with self.db() as db:
ret = get_previous_sha(db, self.repo)
T.assert_is(ret, None)
def get_fake_metrics(self, metric_mapping):
return dict(
(metric_name, 1) for metric_name in metric_mapping.keys()
)
def get_fake_commit(self):
return Commit(self.sha, 1, 'foo')
def insert_fake_metrics(self, db):
metric_mapping = get_metric_mapping(db)
metric_values = self.get_fake_metrics(metric_mapping)
commit = self.get_fake_commit()
insert_metric_values(db, metric_values, metric_mapping, self.repo, commit)
def test_get_previous_sha_previous_existing_sha(self):
with self.db() as db:
self.insert_fake_metrics(db)
ret = get_previous_sha(db, self.repo)
T.assert_equal(ret, self.sha)
def test_insert_and_get_metric_values(self):
with self.db() as db:
fake_metrics = self.get_fake_metrics(get_metric_mapping(db))
fake_commit = self.get_fake_commit()
self.insert_fake_metrics(db)
T.assert_equal(fake_metrics, get_metric_values(db, fake_commit))
|
import testify as T
from git_code_debt.create_tables import get_metric_ids
from git_code_debt.discovery import get_metric_parsers
from git_code_debt.logic import get_metric_mapping
+ from git_code_debt.logic import get_metric_values
+ from git_code_debt.logic import get_previous_sha
+ from git_code_debt.logic import insert_metric_values
+ from git_code_debt.repo_parser import Commit
from testing.base_classes.sandbox_test_case import SandboxTestCase
class TestLogic(SandboxTestCase):
+
+ sha = 'a' * 40
+ repo = 'git@github.com:asottile/git-code-debt'
def test_get_metric_mapping(self):
with self.db() as db:
ret = get_metric_mapping(db)
T.assert_equal(set(ret.keys()), set(get_metric_ids(get_metric_parsers())))
+
+ def test_get_previous_sha_no_previous_sha(self):
+ with self.db() as db:
+ ret = get_previous_sha(db, self.repo)
+ T.assert_is(ret, None)
+
+ def get_fake_metrics(self, metric_mapping):
+ return dict(
+ (metric_name, 1) for metric_name in metric_mapping.keys()
+ )
+
+ def get_fake_commit(self):
+ return Commit(self.sha, 1, 'foo')
+
+ def insert_fake_metrics(self, db):
+ metric_mapping = get_metric_mapping(db)
+ metric_values = self.get_fake_metrics(metric_mapping)
+ commit = self.get_fake_commit()
+ insert_metric_values(db, metric_values, metric_mapping, self.repo, commit)
+
+ def test_get_previous_sha_previous_existing_sha(self):
+ with self.db() as db:
+ self.insert_fake_metrics(db)
+ ret = get_previous_sha(db, self.repo)
+ T.assert_equal(ret, self.sha)
+
+ def test_insert_and_get_metric_values(self):
+ with self.db() as db:
+ fake_metrics = self.get_fake_metrics(get_metric_mapping(db))
+ fake_commit = self.get_fake_commit()
+ self.insert_fake_metrics(db)
+ T.assert_equal(fake_metrics, get_metric_values(db, fake_commit)) |
7d0f3ba1aa82c2ea5a4a2eca2bbe842b63a82c72 | wafer/talks/serializers.py | wafer/talks/serializers.py | from rest_framework import serializers
from reversion import revisions
from wafer.talks.models import Talk
class TalkSerializer(serializers.ModelSerializer):
class Meta:
model = Talk
exclude = ('_abstract_rendered', )
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(TalkSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, talk, validated_data):
revisions.set_comment("Changed via REST api")
talk.abstract = validated_data['abstract']
talk.title = validated_data['title']
talk.status = validated_data['status']
talk.talk_type = validated_data['talk_type']
talk.notes = validated_data['notes']
talk.private_notes = validated_data['private_notes']
talk.save()
return talk
| from rest_framework import serializers
from reversion import revisions
from wafer.talks.models import Talk
class TalkSerializer(serializers.ModelSerializer):
class Meta:
model = Talk
# private_notes should possibly be accessible to
# talk reviewers by the API, but certainly
# not to the other users.
# Similar considerations apply to notes, which should
# not be generally accessible
exclude = ('_abstract_rendered', 'private_notes', 'notes')
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(TalkSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, talk, validated_data):
revisions.set_comment("Changed via REST api")
talk.abstract = validated_data['abstract']
talk.title = validated_data['title']
talk.status = validated_data['status']
talk.talk_type = validated_data['talk_type']
talk.notes = validated_data['notes']
talk.private_notes = validated_data['private_notes']
talk.save()
return talk
| Exclude notes and private_notes from api for now | Exclude notes and private_notes from api for now
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | from rest_framework import serializers
from reversion import revisions
from wafer.talks.models import Talk
class TalkSerializer(serializers.ModelSerializer):
class Meta:
model = Talk
+ # private_notes should possibly be accessible to
+ # talk reviewers by the API, but certainly
+ # not to the other users.
+ # Similar considerations apply to notes, which should
+ # not be generally accessible
- exclude = ('_abstract_rendered', )
+ exclude = ('_abstract_rendered', 'private_notes', 'notes')
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(TalkSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, talk, validated_data):
revisions.set_comment("Changed via REST api")
talk.abstract = validated_data['abstract']
talk.title = validated_data['title']
talk.status = validated_data['status']
talk.talk_type = validated_data['talk_type']
talk.notes = validated_data['notes']
talk.private_notes = validated_data['private_notes']
talk.save()
return talk
| Exclude notes and private_notes from api for now | ## Code Before:
from rest_framework import serializers
from reversion import revisions
from wafer.talks.models import Talk
class TalkSerializer(serializers.ModelSerializer):
class Meta:
model = Talk
exclude = ('_abstract_rendered', )
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(TalkSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, talk, validated_data):
revisions.set_comment("Changed via REST api")
talk.abstract = validated_data['abstract']
talk.title = validated_data['title']
talk.status = validated_data['status']
talk.talk_type = validated_data['talk_type']
talk.notes = validated_data['notes']
talk.private_notes = validated_data['private_notes']
talk.save()
return talk
## Instruction:
Exclude notes and private_notes from api for now
## Code After:
from rest_framework import serializers
from reversion import revisions
from wafer.talks.models import Talk
class TalkSerializer(serializers.ModelSerializer):
class Meta:
model = Talk
# private_notes should possibly be accessible to
# talk reviewers by the API, but certainly
# not to the other users.
# Similar considerations apply to notes, which should
# not be generally accessible
exclude = ('_abstract_rendered', 'private_notes', 'notes')
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(TalkSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, talk, validated_data):
revisions.set_comment("Changed via REST api")
talk.abstract = validated_data['abstract']
talk.title = validated_data['title']
talk.status = validated_data['status']
talk.talk_type = validated_data['talk_type']
talk.notes = validated_data['notes']
talk.private_notes = validated_data['private_notes']
talk.save()
return talk
| from rest_framework import serializers
from reversion import revisions
from wafer.talks.models import Talk
class TalkSerializer(serializers.ModelSerializer):
class Meta:
model = Talk
+ # private_notes should possibly be accessible to
+ # talk reviewers by the API, but certainly
+ # not to the other users.
+ # Similar considerations apply to notes, which should
+ # not be generally accessible
- exclude = ('_abstract_rendered', )
+ exclude = ('_abstract_rendered', 'private_notes', 'notes')
? ++++++++++++++++++++++++
@revisions.create_revision()
def create(self, validated_data):
revisions.set_comment("Created via REST api")
return super(TalkSerializer, self).create(validated_data)
@revisions.create_revision()
def update(self, talk, validated_data):
revisions.set_comment("Changed via REST api")
talk.abstract = validated_data['abstract']
talk.title = validated_data['title']
talk.status = validated_data['status']
talk.talk_type = validated_data['talk_type']
talk.notes = validated_data['notes']
talk.private_notes = validated_data['private_notes']
talk.save()
return talk |
2722a59aad0775f1bcd1e81232ff445b9012a2ae | ssim/compat.py | ssim/compat.py | """Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
basestring = basestring # pylint: disable=invalid-name
| """Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
# pylint: disable=redefined-variable-type
basestring = basestring # pylint: disable=invalid-name
| Add pylint to disable redefined variable. | Add pylint to disable redefined variable.
| Python | mit | jterrace/pyssim | """Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
+ # pylint: disable=redefined-variable-type
basestring = basestring # pylint: disable=invalid-name
| Add pylint to disable redefined variable. | ## Code Before:
"""Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
basestring = basestring # pylint: disable=invalid-name
## Instruction:
Add pylint to disable redefined variable.
## Code After:
"""Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
# pylint: disable=redefined-variable-type
basestring = basestring # pylint: disable=invalid-name
| """Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError:
from PIL import ImageOps # pylint: disable=unused-import
if sys.version_info[0] > 2:
basestring = (str, bytes) # pylint: disable=redefined-builtin,invalid-name
else:
+ # pylint: disable=redefined-variable-type
basestring = basestring # pylint: disable=invalid-name |
c12cbae226f42405a998b93c6fd7049aadc6a19c | build.py | build.py | import os
import string
if __name__ == '__main__':
patch_file = 'example.patch'
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{}.ko'.format(base_name),
'description': 'Package generated from {} by '
'kpatch-package-builder'.format(patch_file),
}
with open('kpatch-patch.spec') as f:
spec_template = string.Template(f.read())
print(spec_template.substitute(values))
| import os
import string
def generate_rpm_spec(template, patch_file):
spec_template = string.Template(template)
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{}.ko'.format(base_name),
'description': 'Package generated from {} by '
'kpatch-package-builder'.format(patch_file),
}
return spec_template.substitute(values)
if __name__ == '__main__':
with open('kpatch-patch.spec') as f:
template = f.read()
print(generate_rpm_spec(template, 'example.patch'))
| Split spec generation into function | Split spec generation into function
| Python | mit | centos-livepatching/kpatch-package-builder | import os
import string
- if __name__ == '__main__':
- patch_file = 'example.patch'
+ def generate_rpm_spec(template, patch_file):
+ spec_template = string.Template(template)
+
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{}.ko'.format(base_name),
'description': 'Package generated from {} by '
'kpatch-package-builder'.format(patch_file),
}
+ return spec_template.substitute(values)
+
+ if __name__ == '__main__':
+
with open('kpatch-patch.spec') as f:
- spec_template = string.Template(f.read())
+ template = f.read()
- print(spec_template.substitute(values))
+ print(generate_rpm_spec(template, 'example.patch'))
| Split spec generation into function | ## Code Before:
import os
import string
if __name__ == '__main__':
patch_file = 'example.patch'
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{}.ko'.format(base_name),
'description': 'Package generated from {} by '
'kpatch-package-builder'.format(patch_file),
}
with open('kpatch-patch.spec') as f:
spec_template = string.Template(f.read())
print(spec_template.substitute(values))
## Instruction:
Split spec generation into function
## Code After:
import os
import string
def generate_rpm_spec(template, patch_file):
spec_template = string.Template(template)
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{}.ko'.format(base_name),
'description': 'Package generated from {} by '
'kpatch-package-builder'.format(patch_file),
}
return spec_template.substitute(values)
if __name__ == '__main__':
with open('kpatch-patch.spec') as f:
template = f.read()
print(generate_rpm_spec(template, 'example.patch'))
| import os
import string
- if __name__ == '__main__':
- patch_file = 'example.patch'
+ def generate_rpm_spec(template, patch_file):
+ spec_template = string.Template(template)
+
base_name, _ = os.path.splitext(patch_file)
values = {
'name': 'kpatch-module-{}'.format(base_name),
'patch_file': patch_file,
'kmod_filename': 'kpatch-{}.ko'.format(base_name),
'description': 'Package generated from {} by '
'kpatch-package-builder'.format(patch_file),
}
+ return spec_template.substitute(values)
+
+ if __name__ == '__main__':
+
with open('kpatch-patch.spec') as f:
- spec_template = string.Template(f.read())
+ template = f.read()
- print(spec_template.substitute(values))
+ print(generate_rpm_spec(template, 'example.patch')) |
ea1389d6dfb0060cda8d194079aacc900bbf56ae | simple_graph.py | simple_graph.py | from __future__ import print_function
from __future__ import unicode_literals
class Graph(object):
''' Create an empty graph. '''
def __init__(self):
self.graph = {}
return
def nodes():
return nodes
def edges():
return edges
def add_node(self, node):
self.graph.setdefault(node, [])
return
def add_edge(self, node1, node2):
return
def del_node(self, node):
try:
del self.graph[node]
except KeyError:
raise KeyError('node not in graph')
def has_node(self, node):
return node in self.graph
def neighbors(self, node):
return self.graph[node]
def adjecent(self, node1, node2):
if node2 in self.graph[node1] or node1 in self.graph[node2]:
return True
else:
return False
| from __future__ import print_function
from __future__ import unicode_literals
class Graph(object):
''' Create an empty graph. '''
def __init__(self):
self.graph = {}
return
def nodes(self):
return self.graph.keys()
def edges(self):
edge_list = []
for key, value in self.graph():
for item in value:
edge_list.append((key, item))
return edge_list
def add_node(self, node):
self.graph.setdefault(node, [])
def add_edge(self, node1, node2):
if node1 in self.graph:
self.graph.append(node2)
else:
self.graph[node1] = node2
def del_node(self, node):
try:
del self.graph[node]
except KeyError:
raise KeyError('node not in graph')
def has_node(self, node):
return node in self.graph
def neighbors(self, node):
return self.graph[node]
def adjecent(self, node1, node2):
if node2 in self.graph[node1] or node1 in self.graph[node2]:
return True
else:
return False
| Add functions for adding a node, an edge, and defining a node | Add functions for adding a node, an edge, and defining a node
| Python | mit | constanthatz/data-structures | from __future__ import print_function
from __future__ import unicode_literals
class Graph(object):
''' Create an empty graph. '''
def __init__(self):
self.graph = {}
return
- def nodes():
+ def nodes(self):
- return nodes
+ return self.graph.keys()
- def edges():
+ def edges(self):
+ edge_list = []
+ for key, value in self.graph():
+ for item in value:
+ edge_list.append((key, item))
- return edges
+ return edge_list
def add_node(self, node):
self.graph.setdefault(node, [])
- return
def add_edge(self, node1, node2):
- return
+ if node1 in self.graph:
+ self.graph.append(node2)
+ else:
+ self.graph[node1] = node2
def del_node(self, node):
try:
del self.graph[node]
except KeyError:
raise KeyError('node not in graph')
def has_node(self, node):
return node in self.graph
def neighbors(self, node):
return self.graph[node]
def adjecent(self, node1, node2):
if node2 in self.graph[node1] or node1 in self.graph[node2]:
return True
else:
return False
| Add functions for adding a node, an edge, and defining a node | ## Code Before:
from __future__ import print_function
from __future__ import unicode_literals
class Graph(object):
''' Create an empty graph. '''
def __init__(self):
self.graph = {}
return
def nodes():
return nodes
def edges():
return edges
def add_node(self, node):
self.graph.setdefault(node, [])
return
def add_edge(self, node1, node2):
return
def del_node(self, node):
try:
del self.graph[node]
except KeyError:
raise KeyError('node not in graph')
def has_node(self, node):
return node in self.graph
def neighbors(self, node):
return self.graph[node]
def adjecent(self, node1, node2):
if node2 in self.graph[node1] or node1 in self.graph[node2]:
return True
else:
return False
## Instruction:
Add functions for adding a node, an edge, and defining a node
## Code After:
from __future__ import print_function
from __future__ import unicode_literals
class Graph(object):
''' Create an empty graph. '''
def __init__(self):
self.graph = {}
return
def nodes(self):
return self.graph.keys()
def edges(self):
edge_list = []
for key, value in self.graph():
for item in value:
edge_list.append((key, item))
return edge_list
def add_node(self, node):
self.graph.setdefault(node, [])
def add_edge(self, node1, node2):
if node1 in self.graph:
self.graph.append(node2)
else:
self.graph[node1] = node2
def del_node(self, node):
try:
del self.graph[node]
except KeyError:
raise KeyError('node not in graph')
def has_node(self, node):
return node in self.graph
def neighbors(self, node):
return self.graph[node]
def adjecent(self, node1, node2):
if node2 in self.graph[node1] or node1 in self.graph[node2]:
return True
else:
return False
| from __future__ import print_function
from __future__ import unicode_literals
class Graph(object):
''' Create an empty graph. '''
def __init__(self):
self.graph = {}
return
- def nodes():
+ def nodes(self):
? ++++
- return nodes
+ return self.graph.keys()
- def edges():
+ def edges(self):
? ++++
+ edge_list = []
+ for key, value in self.graph():
+ for item in value:
+ edge_list.append((key, item))
- return edges
+ return edge_list
? +++ +
def add_node(self, node):
self.graph.setdefault(node, [])
- return
def add_edge(self, node1, node2):
- return
+ if node1 in self.graph:
+ self.graph.append(node2)
+ else:
+ self.graph[node1] = node2
def del_node(self, node):
try:
del self.graph[node]
except KeyError:
raise KeyError('node not in graph')
def has_node(self, node):
return node in self.graph
def neighbors(self, node):
return self.graph[node]
def adjecent(self, node1, node2):
if node2 in self.graph[node1] or node1 in self.graph[node2]:
return True
else:
return False |
ad6a0b466c47d945265423c66c71777d61a82de0 | utils/http.py | utils/http.py | import httplib2
def url_exists(url):
"""
Check that a url- when following redirection - exists.
This is needed because django's validators rely on python's urllib2
which in verions < 2.6 won't follow redirects.
"""
h = httplib2.Http()
resp, content = h.request(url)
h.follow_all_redirects = True
return 200<= resp.status <400
| import httplib2
def url_exists(url):
"""
Check that a url- when following redirection - exists.
This is needed because django's validators rely on python's urllib2
which in verions < 2.6 won't follow redirects.
"""
h = httplib2.Http()
resp, content = h.request(url, method="HEAD")
h.follow_all_redirects = True
return 200<= resp.status <400
| Make url field check work over head requests | Make url field check work over head requests
| Python | agpl-3.0 | pculture/unisubs,pculture/unisubs,pculture/unisubs,ReachingOut/unisubs,norayr/unisubs,eloquence/unisubs,norayr/unisubs,ujdhesa/unisubs,norayr/unisubs,ofer43211/unisubs,ujdhesa/unisubs,eloquence/unisubs,ReachingOut/unisubs,pculture/unisubs,wevoice/wesub,ofer43211/unisubs,eloquence/unisubs,wevoice/wesub,ujdhesa/unisubs,wevoice/wesub,wevoice/wesub,ofer43211/unisubs,ujdhesa/unisubs,eloquence/unisubs,norayr/unisubs,ReachingOut/unisubs,ReachingOut/unisubs,ofer43211/unisubs | import httplib2
def url_exists(url):
"""
Check that a url- when following redirection - exists.
This is needed because django's validators rely on python's urllib2
which in verions < 2.6 won't follow redirects.
"""
h = httplib2.Http()
- resp, content = h.request(url)
+ resp, content = h.request(url, method="HEAD")
h.follow_all_redirects = True
return 200<= resp.status <400
| Make url field check work over head requests | ## Code Before:
import httplib2
def url_exists(url):
"""
Check that a url- when following redirection - exists.
This is needed because django's validators rely on python's urllib2
which in verions < 2.6 won't follow redirects.
"""
h = httplib2.Http()
resp, content = h.request(url)
h.follow_all_redirects = True
return 200<= resp.status <400
## Instruction:
Make url field check work over head requests
## Code After:
import httplib2
def url_exists(url):
"""
Check that a url- when following redirection - exists.
This is needed because django's validators rely on python's urllib2
which in verions < 2.6 won't follow redirects.
"""
h = httplib2.Http()
resp, content = h.request(url, method="HEAD")
h.follow_all_redirects = True
return 200<= resp.status <400
| import httplib2
def url_exists(url):
"""
Check that a url- when following redirection - exists.
This is needed because django's validators rely on python's urllib2
which in verions < 2.6 won't follow redirects.
"""
h = httplib2.Http()
- resp, content = h.request(url)
+ resp, content = h.request(url, method="HEAD")
? +++++++++++++++
h.follow_all_redirects = True
return 200<= resp.status <400 |
054c283d1cdccdf8277acc96435672480587f6b9 | devicehive/api_subscribe_request.py | devicehive/api_subscribe_request.py | class ApiSubscribeRequest(object):
"""Api request class."""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
'response_key': None}
def action(self, action):
self._action = action
def set(self, key, value):
if not value:
return
self._request[key] = value
def method(self, method):
self._params['method'] = method
def url(self, url, **args):
for key in args:
value = args[key]
url = url.replace('{%s}' % key, str(value))
self._params['url'] = url
def param(self, key, value):
if not value:
return
self._params['params'][key] = value
def header(self, name, value):
self._params['headers'][name] = value
def response_key(self, response_key):
self._params['response_key'] = response_key
def extract(self):
return self._action, self._request, self._params
| class ApiSubscribeRequest(object):
"""Api request class."""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
'response_key': None,
'params_timestamp_key': 'timestamp',
'response_timestamp_key': 'timestamp'}
def action(self, action):
self._action = action
def set(self, key, value):
if not value:
return
self._request[key] = value
def method(self, method):
self._params['method'] = method
def url(self, url, **args):
for key in args:
value = args[key]
url = url.replace('{%s}' % key, str(value))
self._params['url'] = url
def param(self, key, value):
if not value:
return
self._params['params'][key] = value
def header(self, name, value):
self._params['headers'][name] = value
def response_key(self, response_key):
self._params['response_key'] = response_key
def params_timestamp_key(self, params_timestamp_key):
self._params['params_timestamp_key'] = params_timestamp_key
def response_timestamp_key(self, response_timestamp_key):
self._params['response_timestamp_key'] = response_timestamp_key
def extract(self):
return self._action, self._request, self._params
| Add params_timestamp_key and response_timestamp_key methods | Add params_timestamp_key and response_timestamp_key methods
| Python | apache-2.0 | devicehive/devicehive-python | class ApiSubscribeRequest(object):
"""Api request class."""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
- 'response_key': None}
+ 'response_key': None,
+ 'params_timestamp_key': 'timestamp',
+ 'response_timestamp_key': 'timestamp'}
def action(self, action):
self._action = action
def set(self, key, value):
if not value:
return
self._request[key] = value
def method(self, method):
self._params['method'] = method
def url(self, url, **args):
for key in args:
value = args[key]
url = url.replace('{%s}' % key, str(value))
self._params['url'] = url
def param(self, key, value):
if not value:
return
self._params['params'][key] = value
def header(self, name, value):
self._params['headers'][name] = value
def response_key(self, response_key):
self._params['response_key'] = response_key
+ def params_timestamp_key(self, params_timestamp_key):
+ self._params['params_timestamp_key'] = params_timestamp_key
+
+ def response_timestamp_key(self, response_timestamp_key):
+ self._params['response_timestamp_key'] = response_timestamp_key
+
def extract(self):
return self._action, self._request, self._params
| Add params_timestamp_key and response_timestamp_key methods | ## Code Before:
class ApiSubscribeRequest(object):
"""Api request class."""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
'response_key': None}
def action(self, action):
self._action = action
def set(self, key, value):
if not value:
return
self._request[key] = value
def method(self, method):
self._params['method'] = method
def url(self, url, **args):
for key in args:
value = args[key]
url = url.replace('{%s}' % key, str(value))
self._params['url'] = url
def param(self, key, value):
if not value:
return
self._params['params'][key] = value
def header(self, name, value):
self._params['headers'][name] = value
def response_key(self, response_key):
self._params['response_key'] = response_key
def extract(self):
return self._action, self._request, self._params
## Instruction:
Add params_timestamp_key and response_timestamp_key methods
## Code After:
class ApiSubscribeRequest(object):
"""Api request class."""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
'response_key': None,
'params_timestamp_key': 'timestamp',
'response_timestamp_key': 'timestamp'}
def action(self, action):
self._action = action
def set(self, key, value):
if not value:
return
self._request[key] = value
def method(self, method):
self._params['method'] = method
def url(self, url, **args):
for key in args:
value = args[key]
url = url.replace('{%s}' % key, str(value))
self._params['url'] = url
def param(self, key, value):
if not value:
return
self._params['params'][key] = value
def header(self, name, value):
self._params['headers'][name] = value
def response_key(self, response_key):
self._params['response_key'] = response_key
def params_timestamp_key(self, params_timestamp_key):
self._params['params_timestamp_key'] = params_timestamp_key
def response_timestamp_key(self, response_timestamp_key):
self._params['response_timestamp_key'] = response_timestamp_key
def extract(self):
return self._action, self._request, self._params
| class ApiSubscribeRequest(object):
"""Api request class."""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
- 'response_key': None}
? ^
+ 'response_key': None,
? ^
+ 'params_timestamp_key': 'timestamp',
+ 'response_timestamp_key': 'timestamp'}
def action(self, action):
self._action = action
def set(self, key, value):
if not value:
return
self._request[key] = value
def method(self, method):
self._params['method'] = method
def url(self, url, **args):
for key in args:
value = args[key]
url = url.replace('{%s}' % key, str(value))
self._params['url'] = url
def param(self, key, value):
if not value:
return
self._params['params'][key] = value
def header(self, name, value):
self._params['headers'][name] = value
def response_key(self, response_key):
self._params['response_key'] = response_key
+ def params_timestamp_key(self, params_timestamp_key):
+ self._params['params_timestamp_key'] = params_timestamp_key
+
+ def response_timestamp_key(self, response_timestamp_key):
+ self._params['response_timestamp_key'] = response_timestamp_key
+
def extract(self):
return self._action, self._request, self._params |
9168abf53be960d1630ec6ecb01c6d8f55d21739 | promotions_app/models.py | promotions_app/models.py | from django.db import models
from authentication_app.models import Account
'''
@name : Promotion
@desc : The promotion model.
'''
class Promotion(models.Model):
account = models.ForeignKey(Account)
name = models.CharField(max_length=50, unique=True)
desc = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
expire_date = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='promotions')
def _unicode_(self):
return self.name
def get_short_promotion(self):
return ' '.join([self.name, self.expire_date])
def get_promotion(self):
return ' '.join([self.name, self.desc, self.expire_date])
| from django.db import models
from authentication_app.models import Account
'''
@name : PromotionManager.
@desc : The PromotionManager is responsible to create, delete and update the promotions.
'''
class PromotionManager(models.Manager):
def create_promotion(self, name, desc, expire_date, image):
promotion = self.create(name=name, desc=desc, expire_date=expire_date, image=image)
promotion.save()
return promotion
def delete_promotion(self, name):
promotion = super(PromotionManager, self).get_queryset().filter(name=name)
promotion.delete()
def update_promotion(self, name, expire_date):
promotion = super(PromotionManager, self).get_queryset().filter(name=name)
promotion.set_expire_date(expire_date)
return promotion
'''
@name : Promotion.
@desc : The promotion model.
'''
class Promotion(models.Model):
account = models.ForeignKey(Account)
name = models.CharField(max_length=50, unique=True)
desc = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
expire_date = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='promotions')
objects = PromotionManager()
def _unicode_(self):
return self.name
def get_short_promotion(self):
return ' '.join([self.name, self.expire_date])
def get_promotion(self):
return ' '.join([self.name, self.desc, self.expire_date])
| Add the promotion manager to the promotions app. | Add the promotion manager to the promotions app.
| Python | mit | mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app | from django.db import models
from authentication_app.models import Account
'''
+ @name : PromotionManager.
+ @desc : The PromotionManager is responsible to create, delete and update the promotions.
+ '''
+ class PromotionManager(models.Manager):
+
+ def create_promotion(self, name, desc, expire_date, image):
+ promotion = self.create(name=name, desc=desc, expire_date=expire_date, image=image)
+ promotion.save()
+ return promotion
+
+ def delete_promotion(self, name):
+ promotion = super(PromotionManager, self).get_queryset().filter(name=name)
+ promotion.delete()
+
+ def update_promotion(self, name, expire_date):
+ promotion = super(PromotionManager, self).get_queryset().filter(name=name)
+ promotion.set_expire_date(expire_date)
+ return promotion
+
+ '''
- @name : Promotion
+ @name : Promotion.
@desc : The promotion model.
'''
class Promotion(models.Model):
account = models.ForeignKey(Account)
name = models.CharField(max_length=50, unique=True)
desc = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
expire_date = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='promotions')
+ objects = PromotionManager()
+
def _unicode_(self):
return self.name
def get_short_promotion(self):
return ' '.join([self.name, self.expire_date])
def get_promotion(self):
return ' '.join([self.name, self.desc, self.expire_date])
| Add the promotion manager to the promotions app. | ## Code Before:
from django.db import models
from authentication_app.models import Account
'''
@name : Promotion
@desc : The promotion model.
'''
class Promotion(models.Model):
account = models.ForeignKey(Account)
name = models.CharField(max_length=50, unique=True)
desc = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
expire_date = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='promotions')
def _unicode_(self):
return self.name
def get_short_promotion(self):
return ' '.join([self.name, self.expire_date])
def get_promotion(self):
return ' '.join([self.name, self.desc, self.expire_date])
## Instruction:
Add the promotion manager to the promotions app.
## Code After:
from django.db import models
from authentication_app.models import Account
'''
@name : PromotionManager.
@desc : The PromotionManager is responsible to create, delete and update the promotions.
'''
class PromotionManager(models.Manager):
def create_promotion(self, name, desc, expire_date, image):
promotion = self.create(name=name, desc=desc, expire_date=expire_date, image=image)
promotion.save()
return promotion
def delete_promotion(self, name):
promotion = super(PromotionManager, self).get_queryset().filter(name=name)
promotion.delete()
def update_promotion(self, name, expire_date):
promotion = super(PromotionManager, self).get_queryset().filter(name=name)
promotion.set_expire_date(expire_date)
return promotion
'''
@name : Promotion.
@desc : The promotion model.
'''
class Promotion(models.Model):
account = models.ForeignKey(Account)
name = models.CharField(max_length=50, unique=True)
desc = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
expire_date = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='promotions')
objects = PromotionManager()
def _unicode_(self):
return self.name
def get_short_promotion(self):
return ' '.join([self.name, self.expire_date])
def get_promotion(self):
return ' '.join([self.name, self.desc, self.expire_date])
| from django.db import models
from authentication_app.models import Account
'''
+ @name : PromotionManager.
+ @desc : The PromotionManager is responsible to create, delete and update the promotions.
+ '''
+ class PromotionManager(models.Manager):
+
+ def create_promotion(self, name, desc, expire_date, image):
+ promotion = self.create(name=name, desc=desc, expire_date=expire_date, image=image)
+ promotion.save()
+ return promotion
+
+ def delete_promotion(self, name):
+ promotion = super(PromotionManager, self).get_queryset().filter(name=name)
+ promotion.delete()
+
+ def update_promotion(self, name, expire_date):
+ promotion = super(PromotionManager, self).get_queryset().filter(name=name)
+ promotion.set_expire_date(expire_date)
+ return promotion
+
+ '''
- @name : Promotion
+ @name : Promotion.
? +
@desc : The promotion model.
'''
class Promotion(models.Model):
account = models.ForeignKey(Account)
name = models.CharField(max_length=50, unique=True)
desc = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
expire_date = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='promotions')
+ objects = PromotionManager()
+
def _unicode_(self):
return self.name
def get_short_promotion(self):
return ' '.join([self.name, self.expire_date])
def get_promotion(self):
return ' '.join([self.name, self.desc, self.expire_date]) |
435fce76241d41eaffaf63bbd948eb306806d8f0 | microdash/settings/production.py | microdash/settings/production.py | import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
| import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
TWITTER_KEY = env('TWITTER_KEY')
TWITTER_SECRET = env('TWITTER_KEY')
| Read settings from the environment. | Read settings from the environment.
| Python | bsd-3-clause | alfredo/microdash,alfredo/microdash | import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
+ TWITTER_KEY = env('TWITTER_KEY')
+ TWITTER_SECRET = env('TWITTER_KEY')
+ | Read settings from the environment. | ## Code Before:
import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
## Instruction:
Read settings from the environment.
## Code After:
import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
TWITTER_KEY = env('TWITTER_KEY')
TWITTER_SECRET = env('TWITTER_KEY')
| import os
import dj_database_url
from microdash.settings.base import *
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SECRET_KEY = env('SECRET_KEY')
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
+
+ TWITTER_KEY = env('TWITTER_KEY')
+ TWITTER_SECRET = env('TWITTER_KEY') |
0003ef7fe3d59c4bda034dee334d45b6d7a2622d | pyvm_test.py | pyvm_test.py | import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
def test_load_const_str(self):
self.assertEqual(
"hoge",
self.vm.eval('"hoge"')
)
if __name__ == '__main__':
unittest.main()
| import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
def test_load_const_num_float(self):
self.assertEqual(
10.55,
self.vm.eval('10.55')
)
def test_load_const_str(self):
self.assertEqual(
"hoge",
self.vm.eval('"hoge"')
)
if __name__ == '__main__':
unittest.main()
| Add test of storing float | Add test of storing float
| Python | mit | utgwkk/tiny-python-vm | import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
+ def test_load_const_num_float(self):
+ self.assertEqual(
+ 10.55,
+ self.vm.eval('10.55')
+ )
+
def test_load_const_str(self):
self.assertEqual(
"hoge",
self.vm.eval('"hoge"')
)
if __name__ == '__main__':
unittest.main()
| Add test of storing float | ## Code Before:
import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
def test_load_const_str(self):
self.assertEqual(
"hoge",
self.vm.eval('"hoge"')
)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add test of storing float
## Code After:
import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
def test_load_const_num_float(self):
self.assertEqual(
10.55,
self.vm.eval('10.55')
)
def test_load_const_str(self):
self.assertEqual(
"hoge",
self.vm.eval('"hoge"')
)
if __name__ == '__main__':
unittest.main()
| import pyvm
import unittest
class PyVMTest(unittest.TestCase):
def setUp(self):
self.vm = pyvm.PythonVM()
def test_load_const_num(self):
self.assertEqual(
10,
self.vm.eval('10')
)
+ def test_load_const_num_float(self):
+ self.assertEqual(
+ 10.55,
+ self.vm.eval('10.55')
+ )
+
def test_load_const_str(self):
self.assertEqual(
"hoge",
self.vm.eval('"hoge"')
)
if __name__ == '__main__':
unittest.main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.