repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
CEA-COSMIC/ModOpt | modopt/base/types.py | check_int | def check_int(val):
r"""Check if input value is an int or a np.ndarray of ints, if not convert.
Parameters
----------
val : any
Input value
Returns
-------
int or np.ndarray of ints
Examples
--------
>>> from modopt.base.types import check_int
>>> a = np.arange(5).astype(float)
>>> a
array([ 0., 1., 2., 3., 4.])
>>> check_float(a)
array([0, 1, 2, 3, 4])
"""
if not isinstance(val, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid input type.')
if isinstance(val, float):
val = int(val)
elif isinstance(val, (list, tuple)):
val = np.array(val, dtype=int)
elif isinstance(val, np.ndarray) and (not np.issubdtype(val.dtype,
np.integer)):
val = val.astype(int)
return val | python | def check_int(val):
r"""Check if input value is an int or a np.ndarray of ints, if not convert.
Parameters
----------
val : any
Input value
Returns
-------
int or np.ndarray of ints
Examples
--------
>>> from modopt.base.types import check_int
>>> a = np.arange(5).astype(float)
>>> a
array([ 0., 1., 2., 3., 4.])
>>> check_float(a)
array([0, 1, 2, 3, 4])
"""
if not isinstance(val, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid input type.')
if isinstance(val, float):
val = int(val)
elif isinstance(val, (list, tuple)):
val = np.array(val, dtype=int)
elif isinstance(val, np.ndarray) and (not np.issubdtype(val.dtype,
np.integer)):
val = val.astype(int)
return val | [
"def",
"check_int",
"(",
"val",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"float",
",",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid input type.'",
")",
"if",
"isins... | r"""Check if input value is an int or a np.ndarray of ints, if not convert.
Parameters
----------
val : any
Input value
Returns
-------
int or np.ndarray of ints
Examples
--------
>>> from modopt.base.types import check_int
>>> a = np.arange(5).astype(float)
>>> a
array([ 0., 1., 2., 3., 4.])
>>> check_float(a)
array([0, 1, 2, 3, 4]) | [
"r",
"Check",
"if",
"input",
"value",
"is",
"an",
"int",
"or",
"a",
"np",
".",
"ndarray",
"of",
"ints",
"if",
"not",
"convert",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/types.py#L87-L120 | train | 25,400 |
CEA-COSMIC/ModOpt | modopt/base/types.py | check_npndarray | def check_npndarray(val, dtype=None, writeable=True, verbose=True):
"""Check if input object is a numpy array.
Parameters
----------
val : np.ndarray
Input object
"""
if not isinstance(val, np.ndarray):
raise TypeError('Input is not a numpy array.')
if ((not isinstance(dtype, type(None))) and
(not np.issubdtype(val.dtype, dtype))):
raise TypeError('The numpy array elements are not of type: {}'
''.format(dtype))
if not writeable and verbose and val.flags.writeable:
warn('Making input data immutable.')
val.flags.writeable = writeable | python | def check_npndarray(val, dtype=None, writeable=True, verbose=True):
"""Check if input object is a numpy array.
Parameters
----------
val : np.ndarray
Input object
"""
if not isinstance(val, np.ndarray):
raise TypeError('Input is not a numpy array.')
if ((not isinstance(dtype, type(None))) and
(not np.issubdtype(val.dtype, dtype))):
raise TypeError('The numpy array elements are not of type: {}'
''.format(dtype))
if not writeable and verbose and val.flags.writeable:
warn('Making input data immutable.')
val.flags.writeable = writeable | [
"def",
"check_npndarray",
"(",
"val",
",",
"dtype",
"=",
"None",
",",
"writeable",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"'Input is not... | Check if input object is a numpy array.
Parameters
----------
val : np.ndarray
Input object | [
"Check",
"if",
"input",
"object",
"is",
"a",
"numpy",
"array",
"."
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/types.py#L123-L144 | train | 25,401 |
CEA-COSMIC/ModOpt | modopt/signal/positivity.py | positive | def positive(data):
r"""Positivity operator
This method preserves only the positive coefficients of the input data, all
negative coefficients are set to zero
Parameters
----------
data : int, float, list, tuple or np.ndarray
Input data
Returns
-------
int or float, or np.ndarray array with only positive coefficients
Raises
------
TypeError
For invalid input type.
Examples
--------
>>> from modopt.signal.positivity import positive
>>> a = np.arange(9).reshape(3, 3) - 5
>>> a
array([[-5, -4, -3],
[-2, -1, 0],
[ 1, 2, 3]])
>>> positive(a)
array([[0, 0, 0],
[0, 0, 0],
[1, 2, 3]])
"""
if not isinstance(data, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid data type, input must be `int`, `float`, '
'`list`, `tuple` or `np.ndarray`.')
def pos_thresh(data):
return data * (data > 0)
def pos_recursive(data):
data = np.array(data)
if not data.dtype == 'O':
result = list(pos_thresh(data))
else:
result = [pos_recursive(x) for x in data]
return result
if isinstance(data, (int, float)):
return pos_thresh(data)
else:
return np.array(pos_recursive(data)) | python | def positive(data):
r"""Positivity operator
This method preserves only the positive coefficients of the input data, all
negative coefficients are set to zero
Parameters
----------
data : int, float, list, tuple or np.ndarray
Input data
Returns
-------
int or float, or np.ndarray array with only positive coefficients
Raises
------
TypeError
For invalid input type.
Examples
--------
>>> from modopt.signal.positivity import positive
>>> a = np.arange(9).reshape(3, 3) - 5
>>> a
array([[-5, -4, -3],
[-2, -1, 0],
[ 1, 2, 3]])
>>> positive(a)
array([[0, 0, 0],
[0, 0, 0],
[1, 2, 3]])
"""
if not isinstance(data, (int, float, list, tuple, np.ndarray)):
raise TypeError('Invalid data type, input must be `int`, `float`, '
'`list`, `tuple` or `np.ndarray`.')
def pos_thresh(data):
return data * (data > 0)
def pos_recursive(data):
data = np.array(data)
if not data.dtype == 'O':
result = list(pos_thresh(data))
else:
result = [pos_recursive(x) for x in data]
return result
if isinstance(data, (int, float)):
return pos_thresh(data)
else:
return np.array(pos_recursive(data)) | [
"def",
"positive",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"int",
",",
"float",
",",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid data type, input must be `int`, `floa... | r"""Positivity operator
This method preserves only the positive coefficients of the input data, all
negative coefficients are set to zero
Parameters
----------
data : int, float, list, tuple or np.ndarray
Input data
Returns
-------
int or float, or np.ndarray array with only positive coefficients
Raises
------
TypeError
For invalid input type.
Examples
--------
>>> from modopt.signal.positivity import positive
>>> a = np.arange(9).reshape(3, 3) - 5
>>> a
array([[-5, -4, -3],
[-2, -1, 0],
[ 1, 2, 3]])
>>> positive(a)
array([[0, 0, 0],
[0, 0, 0],
[1, 2, 3]]) | [
"r",
"Positivity",
"operator"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/positivity.py#L15-L78 | train | 25,402 |
scidash/sciunit | sciunit/scores/collections.py | ScoreArray.mean | def mean(self):
"""Compute a total score for each model over all the tests.
Uses the `norm_score` attribute, since otherwise direct comparison
across different kinds of scores would not be possible.
"""
return np.dot(np.array(self.norm_scores), self.weights) | python | def mean(self):
"""Compute a total score for each model over all the tests.
Uses the `norm_score` attribute, since otherwise direct comparison
across different kinds of scores would not be possible.
"""
return np.dot(np.array(self.norm_scores), self.weights) | [
"def",
"mean",
"(",
"self",
")",
":",
"return",
"np",
".",
"dot",
"(",
"np",
".",
"array",
"(",
"self",
".",
"norm_scores",
")",
",",
"self",
".",
"weights",
")"
] | Compute a total score for each model over all the tests.
Uses the `norm_score` attribute, since otherwise direct comparison
across different kinds of scores would not be possible. | [
"Compute",
"a",
"total",
"score",
"for",
"each",
"model",
"over",
"all",
"the",
"tests",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/collections.py#L84-L91 | train | 25,403 |
scidash/sciunit | sciunit/scores/collections.py | ScoreMatrix.T | def T(self):
"""Get transpose of this ScoreMatrix."""
return ScoreMatrix(self.tests, self.models, scores=self.values,
weights=self.weights, transpose=True) | python | def T(self):
"""Get transpose of this ScoreMatrix."""
return ScoreMatrix(self.tests, self.models, scores=self.values,
weights=self.weights, transpose=True) | [
"def",
"T",
"(",
"self",
")",
":",
"return",
"ScoreMatrix",
"(",
"self",
".",
"tests",
",",
"self",
".",
"models",
",",
"scores",
"=",
"self",
".",
"values",
",",
"weights",
"=",
"self",
".",
"weights",
",",
"transpose",
"=",
"True",
")"
] | Get transpose of this ScoreMatrix. | [
"Get",
"transpose",
"of",
"this",
"ScoreMatrix",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/collections.py#L210-L213 | train | 25,404 |
scidash/sciunit | sciunit/scores/collections.py | ScoreMatrix.to_html | def to_html(self, show_mean=None, sortable=None, colorize=True, *args,
**kwargs):
"""Extend Pandas built in `to_html` method for rendering a DataFrame
and use it to render a ScoreMatrix."""
if show_mean is None:
show_mean = self.show_mean
if sortable is None:
sortable = self.sortable
df = self.copy()
if show_mean:
df.insert(0, 'Mean', None)
df.loc[:, 'Mean'] = ['%.3f' % self[m].mean() for m in self.models]
html = df.to_html(*args, **kwargs) # Pandas method
html, table_id = self.annotate(df, html, show_mean, colorize)
if sortable:
self.dynamify(table_id)
return html | python | def to_html(self, show_mean=None, sortable=None, colorize=True, *args,
**kwargs):
"""Extend Pandas built in `to_html` method for rendering a DataFrame
and use it to render a ScoreMatrix."""
if show_mean is None:
show_mean = self.show_mean
if sortable is None:
sortable = self.sortable
df = self.copy()
if show_mean:
df.insert(0, 'Mean', None)
df.loc[:, 'Mean'] = ['%.3f' % self[m].mean() for m in self.models]
html = df.to_html(*args, **kwargs) # Pandas method
html, table_id = self.annotate(df, html, show_mean, colorize)
if sortable:
self.dynamify(table_id)
return html | [
"def",
"to_html",
"(",
"self",
",",
"show_mean",
"=",
"None",
",",
"sortable",
"=",
"None",
",",
"colorize",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"show_mean",
"is",
"None",
":",
"show_mean",
"=",
"self",
".",
"sho... | Extend Pandas built in `to_html` method for rendering a DataFrame
and use it to render a ScoreMatrix. | [
"Extend",
"Pandas",
"built",
"in",
"to_html",
"method",
"for",
"rendering",
"a",
"DataFrame",
"and",
"use",
"it",
"to",
"render",
"a",
"ScoreMatrix",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/collections.py#L215-L231 | train | 25,405 |
scidash/sciunit | sciunit/utils.py | rec_apply | def rec_apply(func, n):
"""
Used to determine parent directory n levels up
by repeatedly applying os.path.dirname
"""
if n > 1:
rec_func = rec_apply(func, n - 1)
return lambda x: func(rec_func(x))
return func | python | def rec_apply(func, n):
"""
Used to determine parent directory n levels up
by repeatedly applying os.path.dirname
"""
if n > 1:
rec_func = rec_apply(func, n - 1)
return lambda x: func(rec_func(x))
return func | [
"def",
"rec_apply",
"(",
"func",
",",
"n",
")",
":",
"if",
"n",
">",
"1",
":",
"rec_func",
"=",
"rec_apply",
"(",
"func",
",",
"n",
"-",
"1",
")",
"return",
"lambda",
"x",
":",
"func",
"(",
"rec_func",
"(",
"x",
")",
")",
"return",
"func"
] | Used to determine parent directory n levels up
by repeatedly applying os.path.dirname | [
"Used",
"to",
"determine",
"parent",
"directory",
"n",
"levels",
"up",
"by",
"repeatedly",
"applying",
"os",
".",
"path",
".",
"dirname"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L50-L58 | train | 25,406 |
scidash/sciunit | sciunit/utils.py | printd | def printd(*args, **kwargs):
"""Print if PRINT_DEBUG_STATE is True"""
global settings
if settings['PRINT_DEBUG_STATE']:
print(*args, **kwargs)
return True
return False | python | def printd(*args, **kwargs):
"""Print if PRINT_DEBUG_STATE is True"""
global settings
if settings['PRINT_DEBUG_STATE']:
print(*args, **kwargs)
return True
return False | [
"def",
"printd",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"settings",
"if",
"settings",
"[",
"'PRINT_DEBUG_STATE'",
"]",
":",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"True",
"return",
"False"
] | Print if PRINT_DEBUG_STATE is True | [
"Print",
"if",
"PRINT_DEBUG_STATE",
"is",
"True"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L71-L78 | train | 25,407 |
scidash/sciunit | sciunit/utils.py | assert_dimensionless | def assert_dimensionless(value):
"""
Tests for dimensionlessness of input.
If input is dimensionless but expressed as a Quantity, it returns the
bare value. If it not, it raised an error.
"""
if isinstance(value, Quantity):
value = value.simplified
if value.dimensionality == Dimensionality({}):
value = value.base.item()
else:
raise TypeError("Score value %s must be dimensionless" % value)
return value | python | def assert_dimensionless(value):
"""
Tests for dimensionlessness of input.
If input is dimensionless but expressed as a Quantity, it returns the
bare value. If it not, it raised an error.
"""
if isinstance(value, Quantity):
value = value.simplified
if value.dimensionality == Dimensionality({}):
value = value.base.item()
else:
raise TypeError("Score value %s must be dimensionless" % value)
return value | [
"def",
"assert_dimensionless",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Quantity",
")",
":",
"value",
"=",
"value",
".",
"simplified",
"if",
"value",
".",
"dimensionality",
"==",
"Dimensionality",
"(",
"{",
"}",
")",
":",
"value",
... | Tests for dimensionlessness of input.
If input is dimensionless but expressed as a Quantity, it returns the
bare value. If it not, it raised an error. | [
"Tests",
"for",
"dimensionlessness",
"of",
"input",
".",
"If",
"input",
"is",
"dimensionless",
"but",
"expressed",
"as",
"a",
"Quantity",
"it",
"returns",
"the",
"bare",
"value",
".",
"If",
"it",
"not",
"it",
"raised",
"an",
"error",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L92-L105 | train | 25,408 |
scidash/sciunit | sciunit/utils.py | import_all_modules | def import_all_modules(package, skip=None, verbose=False, prefix="", depth=0):
"""Recursively imports all subpackages, modules, and submodules of a
given package.
'package' should be an imported package, not a string.
'skip' is a list of modules or subpackages not to import.
"""
skip = [] if skip is None else skip
for ff, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
prefix=prefix,
onerror=lambda x: None):
if ff.path not in package.__path__[0]: # Solves weird bug
continue
if verbose:
print('\t'*depth,modname)
if modname in skip:
if verbose:
print('\t'*depth,'*Skipping*')
continue
module = '%s.%s' % (package.__name__,modname)
subpackage = importlib.import_module(module)
if ispkg:
import_all_modules(subpackage, skip=skip,
verbose=verbose,depth=depth+1) | python | def import_all_modules(package, skip=None, verbose=False, prefix="", depth=0):
"""Recursively imports all subpackages, modules, and submodules of a
given package.
'package' should be an imported package, not a string.
'skip' is a list of modules or subpackages not to import.
"""
skip = [] if skip is None else skip
for ff, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
prefix=prefix,
onerror=lambda x: None):
if ff.path not in package.__path__[0]: # Solves weird bug
continue
if verbose:
print('\t'*depth,modname)
if modname in skip:
if verbose:
print('\t'*depth,'*Skipping*')
continue
module = '%s.%s' % (package.__name__,modname)
subpackage = importlib.import_module(module)
if ispkg:
import_all_modules(subpackage, skip=skip,
verbose=verbose,depth=depth+1) | [
"def",
"import_all_modules",
"(",
"package",
",",
"skip",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"prefix",
"=",
"\"\"",
",",
"depth",
"=",
"0",
")",
":",
"skip",
"=",
"[",
"]",
"if",
"skip",
"is",
"None",
"else",
"skip",
"for",
"ff",
",",
... | Recursively imports all subpackages, modules, and submodules of a
given package.
'package' should be an imported package, not a string.
'skip' is a list of modules or subpackages not to import. | [
"Recursively",
"imports",
"all",
"subpackages",
"modules",
"and",
"submodules",
"of",
"a",
"given",
"package",
".",
"package",
"should",
"be",
"an",
"imported",
"package",
"not",
"a",
"string",
".",
"skip",
"is",
"a",
"list",
"of",
"modules",
"or",
"subpacka... | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L352-L376 | train | 25,409 |
scidash/sciunit | sciunit/utils.py | method_cache | def method_cache(by='value',method='run'):
"""A decorator used on any model method which calls the model's 'method'
method if that latter method has not been called using the current
arguments or simply sets model attributes to match the run results if
it has."""
def decorate_(func):
def decorate(*args, **kwargs):
model = args[0] # Assumed to be self.
assert hasattr(model,method), "Model must have a '%s' method."%method
if func.__name__ == method: # Run itself.
method_args = kwargs
else: # Any other method.
method_args = kwargs[method] if method in kwargs else {}
if not hasattr(model.__class__,'cached_runs'): # If there is no run cache.
model.__class__.cached_runs = {} # Create the method cache.
cache = model.__class__.cached_runs
if by == 'value':
model_dict = {key:value for key,value in list(model.__dict__.items()) \
if key[0]!='_'}
method_signature = SciUnit.dict_hash({'attrs':model_dict,'args':method_args}) # Hash key.
elif by == 'instance':
method_signature = SciUnit.dict_hash({'id':id(model),'args':method_args}) # Hash key.
else:
raise ValueError("Cache type must be 'value' or 'instance'")
if method_signature not in cache:
print("Method with this signature not found in the cache. Running...")
f = getattr(model,method)
f(**method_args)
cache[method_signature] = (datetime.now(),model.__dict__.copy())
else:
print("Method with this signature found in the cache. Restoring...")
_,attrs = cache[method_signature]
model.__dict__.update(attrs)
return func(*args, **kwargs)
return decorate
return decorate_ | python | def method_cache(by='value',method='run'):
"""A decorator used on any model method which calls the model's 'method'
method if that latter method has not been called using the current
arguments or simply sets model attributes to match the run results if
it has."""
def decorate_(func):
def decorate(*args, **kwargs):
model = args[0] # Assumed to be self.
assert hasattr(model,method), "Model must have a '%s' method."%method
if func.__name__ == method: # Run itself.
method_args = kwargs
else: # Any other method.
method_args = kwargs[method] if method in kwargs else {}
if not hasattr(model.__class__,'cached_runs'): # If there is no run cache.
model.__class__.cached_runs = {} # Create the method cache.
cache = model.__class__.cached_runs
if by == 'value':
model_dict = {key:value for key,value in list(model.__dict__.items()) \
if key[0]!='_'}
method_signature = SciUnit.dict_hash({'attrs':model_dict,'args':method_args}) # Hash key.
elif by == 'instance':
method_signature = SciUnit.dict_hash({'id':id(model),'args':method_args}) # Hash key.
else:
raise ValueError("Cache type must be 'value' or 'instance'")
if method_signature not in cache:
print("Method with this signature not found in the cache. Running...")
f = getattr(model,method)
f(**method_args)
cache[method_signature] = (datetime.now(),model.__dict__.copy())
else:
print("Method with this signature found in the cache. Restoring...")
_,attrs = cache[method_signature]
model.__dict__.update(attrs)
return func(*args, **kwargs)
return decorate
return decorate_ | [
"def",
"method_cache",
"(",
"by",
"=",
"'value'",
",",
"method",
"=",
"'run'",
")",
":",
"def",
"decorate_",
"(",
"func",
")",
":",
"def",
"decorate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"model",
"=",
"args",
"[",
"0",
"]",
"# As... | A decorator used on any model method which calls the model's 'method'
method if that latter method has not been called using the current
arguments or simply sets model attributes to match the run results if
it has. | [
"A",
"decorator",
"used",
"on",
"any",
"model",
"method",
"which",
"calls",
"the",
"model",
"s",
"method",
"method",
"if",
"that",
"latter",
"method",
"has",
"not",
"been",
"called",
"using",
"the",
"current",
"arguments",
"or",
"simply",
"sets",
"model",
... | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L401-L437 | train | 25,410 |
scidash/sciunit | sciunit/utils.py | NotebookTools.convert_path | def convert_path(cls, file):
"""
Check to see if an extended path is given and convert appropriately
"""
if isinstance(file,str):
return file
elif isinstance(file, list) and all([isinstance(x, str) for x in file]):
return "/".join(file)
else:
print("Incorrect path specified")
return -1 | python | def convert_path(cls, file):
"""
Check to see if an extended path is given and convert appropriately
"""
if isinstance(file,str):
return file
elif isinstance(file, list) and all([isinstance(x, str) for x in file]):
return "/".join(file)
else:
print("Incorrect path specified")
return -1 | [
"def",
"convert_path",
"(",
"cls",
",",
"file",
")",
":",
"if",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"return",
"file",
"elif",
"isinstance",
"(",
"file",
",",
"list",
")",
"and",
"all",
"(",
"[",
"isinstance",
"(",
"x",
",",
"str",
")",... | Check to see if an extended path is given and convert appropriately | [
"Check",
"to",
"see",
"if",
"an",
"extended",
"path",
"is",
"given",
"and",
"convert",
"appropriately"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L120-L131 | train | 25,411 |
scidash/sciunit | sciunit/utils.py | NotebookTools.get_path | def get_path(self, file):
"""Get the full path of the notebook found in the directory
specified by self.path.
"""
class_path = inspect.getfile(self.__class__)
parent_path = os.path.dirname(class_path)
path = os.path.join(parent_path,self.path,file)
return os.path.realpath(path) | python | def get_path(self, file):
"""Get the full path of the notebook found in the directory
specified by self.path.
"""
class_path = inspect.getfile(self.__class__)
parent_path = os.path.dirname(class_path)
path = os.path.join(parent_path,self.path,file)
return os.path.realpath(path) | [
"def",
"get_path",
"(",
"self",
",",
"file",
")",
":",
"class_path",
"=",
"inspect",
".",
"getfile",
"(",
"self",
".",
"__class__",
")",
"parent_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"class_path",
")",
"path",
"=",
"os",
".",
"path",
".... | Get the full path of the notebook found in the directory
specified by self.path. | [
"Get",
"the",
"full",
"path",
"of",
"the",
"notebook",
"found",
"in",
"the",
"directory",
"specified",
"by",
"self",
".",
"path",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L133-L141 | train | 25,412 |
scidash/sciunit | sciunit/utils.py | NotebookTools.fix_display | def fix_display(self):
"""If this is being run on a headless system the Matplotlib
backend must be changed to one that doesn't need a display.
"""
try:
tkinter.Tk()
except (tkinter.TclError, NameError): # If there is no display.
try:
import matplotlib as mpl
except ImportError:
pass
else:
print("Setting matplotlib backend to Agg")
mpl.use('Agg') | python | def fix_display(self):
"""If this is being run on a headless system the Matplotlib
backend must be changed to one that doesn't need a display.
"""
try:
tkinter.Tk()
except (tkinter.TclError, NameError): # If there is no display.
try:
import matplotlib as mpl
except ImportError:
pass
else:
print("Setting matplotlib backend to Agg")
mpl.use('Agg') | [
"def",
"fix_display",
"(",
"self",
")",
":",
"try",
":",
"tkinter",
".",
"Tk",
"(",
")",
"except",
"(",
"tkinter",
".",
"TclError",
",",
"NameError",
")",
":",
"# If there is no display.",
"try",
":",
"import",
"matplotlib",
"as",
"mpl",
"except",
"ImportE... | If this is being run on a headless system the Matplotlib
backend must be changed to one that doesn't need a display. | [
"If",
"this",
"is",
"being",
"run",
"on",
"a",
"headless",
"system",
"the",
"Matplotlib",
"backend",
"must",
"be",
"changed",
"to",
"one",
"that",
"doesn",
"t",
"need",
"a",
"display",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L143-L157 | train | 25,413 |
scidash/sciunit | sciunit/utils.py | NotebookTools.load_notebook | def load_notebook(self, name):
"""Loads a notebook file into memory."""
with open(self.get_path('%s.ipynb'%name)) as f:
nb = nbformat.read(f, as_version=4)
return nb,f | python | def load_notebook(self, name):
"""Loads a notebook file into memory."""
with open(self.get_path('%s.ipynb'%name)) as f:
nb = nbformat.read(f, as_version=4)
return nb,f | [
"def",
"load_notebook",
"(",
"self",
",",
"name",
")",
":",
"with",
"open",
"(",
"self",
".",
"get_path",
"(",
"'%s.ipynb'",
"%",
"name",
")",
")",
"as",
"f",
":",
"nb",
"=",
"nbformat",
".",
"read",
"(",
"f",
",",
"as_version",
"=",
"4",
")",
"r... | Loads a notebook file into memory. | [
"Loads",
"a",
"notebook",
"file",
"into",
"memory",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L159-L164 | train | 25,414 |
scidash/sciunit | sciunit/utils.py | NotebookTools.run_notebook | def run_notebook(self, nb, f):
"""Runs a loaded notebook file."""
if PYTHON_MAJOR_VERSION == 3:
kernel_name = 'python3'
elif PYTHON_MAJOR_VERSION == 2:
kernel_name = 'python2'
else:
raise Exception('Only Python 2 and 3 are supported')
ep = ExecutePreprocessor(timeout=600, kernel_name=kernel_name)
try:
ep.preprocess(nb, {'metadata': {'path': '.'}})
except CellExecutionError:
msg = 'Error executing the notebook "%s".\n\n' % f.name
msg += 'See notebook "%s" for the traceback.' % f.name
print(msg)
raise
finally:
nbformat.write(nb, f) | python | def run_notebook(self, nb, f):
"""Runs a loaded notebook file."""
if PYTHON_MAJOR_VERSION == 3:
kernel_name = 'python3'
elif PYTHON_MAJOR_VERSION == 2:
kernel_name = 'python2'
else:
raise Exception('Only Python 2 and 3 are supported')
ep = ExecutePreprocessor(timeout=600, kernel_name=kernel_name)
try:
ep.preprocess(nb, {'metadata': {'path': '.'}})
except CellExecutionError:
msg = 'Error executing the notebook "%s".\n\n' % f.name
msg += 'See notebook "%s" for the traceback.' % f.name
print(msg)
raise
finally:
nbformat.write(nb, f) | [
"def",
"run_notebook",
"(",
"self",
",",
"nb",
",",
"f",
")",
":",
"if",
"PYTHON_MAJOR_VERSION",
"==",
"3",
":",
"kernel_name",
"=",
"'python3'",
"elif",
"PYTHON_MAJOR_VERSION",
"==",
"2",
":",
"kernel_name",
"=",
"'python2'",
"else",
":",
"raise",
"Exceptio... | Runs a loaded notebook file. | [
"Runs",
"a",
"loaded",
"notebook",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L166-L184 | train | 25,415 |
scidash/sciunit | sciunit/utils.py | NotebookTools.execute_notebook | def execute_notebook(self, name):
"""Loads and then runs a notebook file."""
warnings.filterwarnings("ignore", category=DeprecationWarning)
nb,f = self.load_notebook(name)
self.run_notebook(nb,f)
self.assertTrue(True) | python | def execute_notebook(self, name):
"""Loads and then runs a notebook file."""
warnings.filterwarnings("ignore", category=DeprecationWarning)
nb,f = self.load_notebook(name)
self.run_notebook(nb,f)
self.assertTrue(True) | [
"def",
"execute_notebook",
"(",
"self",
",",
"name",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
",",
"category",
"=",
"DeprecationWarning",
")",
"nb",
",",
"f",
"=",
"self",
".",
"load_notebook",
"(",
"name",
")",
"self",
".",
"run_not... | Loads and then runs a notebook file. | [
"Loads",
"and",
"then",
"runs",
"a",
"notebook",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L186-L192 | train | 25,416 |
scidash/sciunit | sciunit/utils.py | NotebookTools.convert_notebook | def convert_notebook(self, name):
"""Converts a notebook into a python file."""
#subprocess.call(["jupyter","nbconvert","--to","python",
# self.get_path("%s.ipynb"%name)])
exporter = nbconvert.exporters.python.PythonExporter()
relative_path = self.convert_path(name)
file_path = self.get_path("%s.ipynb"%relative_path)
code = exporter.from_filename(file_path)[0]
self.write_code(name, code)
self.clean_code(name, []) | python | def convert_notebook(self, name):
"""Converts a notebook into a python file."""
#subprocess.call(["jupyter","nbconvert","--to","python",
# self.get_path("%s.ipynb"%name)])
exporter = nbconvert.exporters.python.PythonExporter()
relative_path = self.convert_path(name)
file_path = self.get_path("%s.ipynb"%relative_path)
code = exporter.from_filename(file_path)[0]
self.write_code(name, code)
self.clean_code(name, []) | [
"def",
"convert_notebook",
"(",
"self",
",",
"name",
")",
":",
"#subprocess.call([\"jupyter\",\"nbconvert\",\"--to\",\"python\",",
"# self.get_path(\"%s.ipynb\"%name)])",
"exporter",
"=",
"nbconvert",
".",
"exporters",
".",
"python",
".",
"PythonExporter",
"(",
... | Converts a notebook into a python file. | [
"Converts",
"a",
"notebook",
"into",
"a",
"python",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L194-L204 | train | 25,417 |
scidash/sciunit | sciunit/utils.py | NotebookTools.convert_and_execute_notebook | def convert_and_execute_notebook(self, name):
"""Converts a notebook into a python file and then runs it."""
self.convert_notebook(name)
code = self.read_code(name)#clean_code(name,'get_ipython')
exec(code,globals()) | python | def convert_and_execute_notebook(self, name):
"""Converts a notebook into a python file and then runs it."""
self.convert_notebook(name)
code = self.read_code(name)#clean_code(name,'get_ipython')
exec(code,globals()) | [
"def",
"convert_and_execute_notebook",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"convert_notebook",
"(",
"name",
")",
"code",
"=",
"self",
".",
"read_code",
"(",
"name",
")",
"#clean_code(name,'get_ipython')",
"exec",
"(",
"code",
",",
"globals",
"(",
... | Converts a notebook into a python file and then runs it. | [
"Converts",
"a",
"notebook",
"into",
"a",
"python",
"file",
"and",
"then",
"runs",
"it",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L206-L211 | train | 25,418 |
scidash/sciunit | sciunit/utils.py | NotebookTools.gen_file_path | def gen_file_path(self, name):
"""
Returns full path to generated files. Checks to see if directory
exists where generated files are stored and creates one otherwise.
"""
relative_path = self.convert_path(name)
file_path = self.get_path("%s.ipynb"%relative_path)
parent_path = rec_apply(os.path.dirname, self.gen_file_level)(file_path)
gen_file_name = name if isinstance(name,str) else name[1] #Name of generated file
gen_dir_path = self.get_path(os.path.join(parent_path, self.gen_dir_name))
if not os.path.exists(gen_dir_path): # Create folder for generated files if needed
os.makedirs(gen_dir_path)
new_file_path = self.get_path('%s.py'%os.path.join(gen_dir_path, gen_file_name))
return new_file_path | python | def gen_file_path(self, name):
"""
Returns full path to generated files. Checks to see if directory
exists where generated files are stored and creates one otherwise.
"""
relative_path = self.convert_path(name)
file_path = self.get_path("%s.ipynb"%relative_path)
parent_path = rec_apply(os.path.dirname, self.gen_file_level)(file_path)
gen_file_name = name if isinstance(name,str) else name[1] #Name of generated file
gen_dir_path = self.get_path(os.path.join(parent_path, self.gen_dir_name))
if not os.path.exists(gen_dir_path): # Create folder for generated files if needed
os.makedirs(gen_dir_path)
new_file_path = self.get_path('%s.py'%os.path.join(gen_dir_path, gen_file_name))
return new_file_path | [
"def",
"gen_file_path",
"(",
"self",
",",
"name",
")",
":",
"relative_path",
"=",
"self",
".",
"convert_path",
"(",
"name",
")",
"file_path",
"=",
"self",
".",
"get_path",
"(",
"\"%s.ipynb\"",
"%",
"relative_path",
")",
"parent_path",
"=",
"rec_apply",
"(",
... | Returns full path to generated files. Checks to see if directory
exists where generated files are stored and creates one otherwise. | [
"Returns",
"full",
"path",
"to",
"generated",
"files",
".",
"Checks",
"to",
"see",
"if",
"directory",
"exists",
"where",
"generated",
"files",
"are",
"stored",
"and",
"creates",
"one",
"otherwise",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L213-L226 | train | 25,419 |
scidash/sciunit | sciunit/utils.py | NotebookTools.read_code | def read_code(self, name):
"""Reads code from a python file called 'name'"""
file_path = self.gen_file_path(name)
with open(file_path) as f:
code = f.read()
return code | python | def read_code(self, name):
"""Reads code from a python file called 'name'"""
file_path = self.gen_file_path(name)
with open(file_path) as f:
code = f.read()
return code | [
"def",
"read_code",
"(",
"self",
",",
"name",
")",
":",
"file_path",
"=",
"self",
".",
"gen_file_path",
"(",
"name",
")",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"code",
"=",
"f",
".",
"read",
"(",
")",
"return",
"code"
] | Reads code from a python file called 'name | [
"Reads",
"code",
"from",
"a",
"python",
"file",
"called",
"name"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L228-L234 | train | 25,420 |
scidash/sciunit | sciunit/utils.py | NotebookTools.clean_code | def clean_code(self, name, forbidden):
"""
Remove lines containing items in 'forbidden' from the code.
Helpful for executing converted notebooks that still retain IPython
magic commands.
"""
code = self.read_code(name)
code = code.split('\n')
new_code = []
for line in code:
if [bad for bad in forbidden if bad in line]:
pass
else:
allowed = ['time','timeit'] # Magics where we want to keep the command
line = self.strip_line_magic(line, allowed)
if isinstance(line,list):
line = ' '.join(line)
new_code.append(line)
new_code = '\n'.join(new_code)
self.write_code(name, new_code)
return new_code | python | def clean_code(self, name, forbidden):
"""
Remove lines containing items in 'forbidden' from the code.
Helpful for executing converted notebooks that still retain IPython
magic commands.
"""
code = self.read_code(name)
code = code.split('\n')
new_code = []
for line in code:
if [bad for bad in forbidden if bad in line]:
pass
else:
allowed = ['time','timeit'] # Magics where we want to keep the command
line = self.strip_line_magic(line, allowed)
if isinstance(line,list):
line = ' '.join(line)
new_code.append(line)
new_code = '\n'.join(new_code)
self.write_code(name, new_code)
return new_code | [
"def",
"clean_code",
"(",
"self",
",",
"name",
",",
"forbidden",
")",
":",
"code",
"=",
"self",
".",
"read_code",
"(",
"name",
")",
"code",
"=",
"code",
".",
"split",
"(",
"'\\n'",
")",
"new_code",
"=",
"[",
"]",
"for",
"line",
"in",
"code",
":",
... | Remove lines containing items in 'forbidden' from the code.
Helpful for executing converted notebooks that still retain IPython
magic commands. | [
"Remove",
"lines",
"containing",
"items",
"in",
"forbidden",
"from",
"the",
"code",
".",
"Helpful",
"for",
"executing",
"converted",
"notebooks",
"that",
"still",
"retain",
"IPython",
"magic",
"commands",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L247-L268 | train | 25,421 |
scidash/sciunit | sciunit/utils.py | NotebookTools.do_notebook | def do_notebook(self, name):
"""Run a notebook file after optionally
converting it to a python file."""
CONVERT_NOTEBOOKS = int(os.getenv('CONVERT_NOTEBOOKS', True))
s = StringIO()
if mock:
out = unittest.mock.patch('sys.stdout', new=MockDevice(s))
err = unittest.mock.patch('sys.stderr', new=MockDevice(s))
self._do_notebook(name, CONVERT_NOTEBOOKS)
out.close()
err.close()
else:
self._do_notebook(name, CONVERT_NOTEBOOKS)
self.assertTrue(True) | python | def do_notebook(self, name):
"""Run a notebook file after optionally
converting it to a python file."""
CONVERT_NOTEBOOKS = int(os.getenv('CONVERT_NOTEBOOKS', True))
s = StringIO()
if mock:
out = unittest.mock.patch('sys.stdout', new=MockDevice(s))
err = unittest.mock.patch('sys.stderr', new=MockDevice(s))
self._do_notebook(name, CONVERT_NOTEBOOKS)
out.close()
err.close()
else:
self._do_notebook(name, CONVERT_NOTEBOOKS)
self.assertTrue(True) | [
"def",
"do_notebook",
"(",
"self",
",",
"name",
")",
":",
"CONVERT_NOTEBOOKS",
"=",
"int",
"(",
"os",
".",
"getenv",
"(",
"'CONVERT_NOTEBOOKS'",
",",
"True",
")",
")",
"s",
"=",
"StringIO",
"(",
")",
"if",
"mock",
":",
"out",
"=",
"unittest",
".",
"m... | Run a notebook file after optionally
converting it to a python file. | [
"Run",
"a",
"notebook",
"file",
"after",
"optionally",
"converting",
"it",
"to",
"a",
"python",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L319-L332 | train | 25,422 |
scidash/sciunit | sciunit/utils.py | NotebookTools._do_notebook | def _do_notebook(self, name, convert_notebooks=False):
"""Called by do_notebook to actually run the notebook."""
if convert_notebooks:
self.convert_and_execute_notebook(name)
else:
self.execute_notebook(name) | python | def _do_notebook(self, name, convert_notebooks=False):
"""Called by do_notebook to actually run the notebook."""
if convert_notebooks:
self.convert_and_execute_notebook(name)
else:
self.execute_notebook(name) | [
"def",
"_do_notebook",
"(",
"self",
",",
"name",
",",
"convert_notebooks",
"=",
"False",
")",
":",
"if",
"convert_notebooks",
":",
"self",
".",
"convert_and_execute_notebook",
"(",
"name",
")",
"else",
":",
"self",
".",
"execute_notebook",
"(",
"name",
")"
] | Called by do_notebook to actually run the notebook. | [
"Called",
"by",
"do_notebook",
"to",
"actually",
"run",
"the",
"notebook",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/utils.py#L334-L339 | train | 25,423 |
scidash/sciunit | sciunit/models/base.py | Model.get_capabilities | def get_capabilities(cls):
"""List the model's capabilities."""
capabilities = []
for _cls in cls.mro():
if issubclass(_cls, Capability) and _cls is not Capability \
and not issubclass(_cls, Model):
capabilities.append(_cls)
return capabilities | python | def get_capabilities(cls):
"""List the model's capabilities."""
capabilities = []
for _cls in cls.mro():
if issubclass(_cls, Capability) and _cls is not Capability \
and not issubclass(_cls, Model):
capabilities.append(_cls)
return capabilities | [
"def",
"get_capabilities",
"(",
"cls",
")",
":",
"capabilities",
"=",
"[",
"]",
"for",
"_cls",
"in",
"cls",
".",
"mro",
"(",
")",
":",
"if",
"issubclass",
"(",
"_cls",
",",
"Capability",
")",
"and",
"_cls",
"is",
"not",
"Capability",
"and",
"not",
"i... | List the model's capabilities. | [
"List",
"the",
"model",
"s",
"capabilities",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/base.py#L42-L49 | train | 25,424 |
scidash/sciunit | sciunit/models/base.py | Model.failed_extra_capabilities | def failed_extra_capabilities(self):
"""Check to see if instance passes its `extra_capability_checks`."""
failed = []
for capability, f_name in self.extra_capability_checks.items():
f = getattr(self, f_name)
instance_capable = f()
if not instance_capable:
failed.append(capability)
return failed | python | def failed_extra_capabilities(self):
"""Check to see if instance passes its `extra_capability_checks`."""
failed = []
for capability, f_name in self.extra_capability_checks.items():
f = getattr(self, f_name)
instance_capable = f()
if not instance_capable:
failed.append(capability)
return failed | [
"def",
"failed_extra_capabilities",
"(",
"self",
")",
":",
"failed",
"=",
"[",
"]",
"for",
"capability",
",",
"f_name",
"in",
"self",
".",
"extra_capability_checks",
".",
"items",
"(",
")",
":",
"f",
"=",
"getattr",
"(",
"self",
",",
"f_name",
")",
"inst... | Check to see if instance passes its `extra_capability_checks`. | [
"Check",
"to",
"see",
"if",
"instance",
"passes",
"its",
"extra_capability_checks",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/base.py#L56-L64 | train | 25,425 |
scidash/sciunit | sciunit/models/base.py | Model.describe | def describe(self):
"""Describe the model."""
result = "No description available"
if self.description:
result = "%s" % self.description
else:
if self.__doc__:
s = []
s += [self.__doc__.strip().replace('\n', '').
replace(' ', ' ')]
result = '\n'.join(s)
return result | python | def describe(self):
"""Describe the model."""
result = "No description available"
if self.description:
result = "%s" % self.description
else:
if self.__doc__:
s = []
s += [self.__doc__.strip().replace('\n', '').
replace(' ', ' ')]
result = '\n'.join(s)
return result | [
"def",
"describe",
"(",
"self",
")",
":",
"result",
"=",
"\"No description available\"",
"if",
"self",
".",
"description",
":",
"result",
"=",
"\"%s\"",
"%",
"self",
".",
"description",
"else",
":",
"if",
"self",
".",
"__doc__",
":",
"s",
"=",
"[",
"]",
... | Describe the model. | [
"Describe",
"the",
"model",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/base.py#L66-L77 | train | 25,426 |
scidash/sciunit | sciunit/models/base.py | Model.is_match | def is_match(self, match):
"""Return whether this model is the same as `match`.
Matches if the model is the same as or has the same name as `match`.
"""
result = False
if self == match:
result = True
elif isinstance(match, str) and fnmatchcase(self.name, match):
result = True # Found by instance or name
return result | python | def is_match(self, match):
"""Return whether this model is the same as `match`.
Matches if the model is the same as or has the same name as `match`.
"""
result = False
if self == match:
result = True
elif isinstance(match, str) and fnmatchcase(self.name, match):
result = True # Found by instance or name
return result | [
"def",
"is_match",
"(",
"self",
",",
"match",
")",
":",
"result",
"=",
"False",
"if",
"self",
"==",
"match",
":",
"result",
"=",
"True",
"elif",
"isinstance",
"(",
"match",
",",
"str",
")",
"and",
"fnmatchcase",
"(",
"self",
".",
"name",
",",
"match"... | Return whether this model is the same as `match`.
Matches if the model is the same as or has the same name as `match`. | [
"Return",
"whether",
"this",
"model",
"is",
"the",
"same",
"as",
"match",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/base.py#L92-L102 | train | 25,427 |
scidash/sciunit | sciunit/__main__.py | main | def main(*args):
"""Launch the main routine."""
parser = argparse.ArgumentParser()
parser.add_argument("action",
help="create, check, run, make-nb, or run-nb")
parser.add_argument("--directory", "-dir", default=os.getcwd(),
help="path to directory with a .sciunit file")
parser.add_argument("--stop", "-s", default=True,
help="stop and raise errors, halting the program")
parser.add_argument("--tests", "-t", default=False,
help="runs tests instead of suites")
if args:
args = parser.parse_args(args)
else:
args = parser.parse_args()
file_path = os.path.join(args.directory, '.sciunit')
config = None
if args.action == 'create':
create(file_path)
elif args.action == 'check':
config = parse(file_path, show=True)
print("\nNo configuration errors reported.")
elif args.action == 'run':
config = parse(file_path)
run(config, path=args.directory,
stop_on_error=args.stop, just_tests=args.tests)
elif args.action == 'make-nb':
config = parse(file_path)
make_nb(config, path=args.directory,
stop_on_error=args.stop, just_tests=args.tests)
elif args.action == 'run-nb':
config = parse(file_path)
run_nb(config, path=args.directory)
else:
raise NameError('No such action %s' % args.action)
if config:
cleanup(config, path=args.directory) | python | def main(*args):
"""Launch the main routine."""
parser = argparse.ArgumentParser()
parser.add_argument("action",
help="create, check, run, make-nb, or run-nb")
parser.add_argument("--directory", "-dir", default=os.getcwd(),
help="path to directory with a .sciunit file")
parser.add_argument("--stop", "-s", default=True,
help="stop and raise errors, halting the program")
parser.add_argument("--tests", "-t", default=False,
help="runs tests instead of suites")
if args:
args = parser.parse_args(args)
else:
args = parser.parse_args()
file_path = os.path.join(args.directory, '.sciunit')
config = None
if args.action == 'create':
create(file_path)
elif args.action == 'check':
config = parse(file_path, show=True)
print("\nNo configuration errors reported.")
elif args.action == 'run':
config = parse(file_path)
run(config, path=args.directory,
stop_on_error=args.stop, just_tests=args.tests)
elif args.action == 'make-nb':
config = parse(file_path)
make_nb(config, path=args.directory,
stop_on_error=args.stop, just_tests=args.tests)
elif args.action == 'run-nb':
config = parse(file_path)
run_nb(config, path=args.directory)
else:
raise NameError('No such action %s' % args.action)
if config:
cleanup(config, path=args.directory) | [
"def",
"main",
"(",
"*",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"action\"",
",",
"help",
"=",
"\"create, check, run, make-nb, or run-nb\"",
")",
"parser",
".",
"add_argument",
"(",
"\... | Launch the main routine. | [
"Launch",
"the",
"main",
"routine",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L40-L76 | train | 25,428 |
scidash/sciunit | sciunit/__main__.py | create | def create(file_path):
"""Create a default .sciunit config file if one does not already exist."""
if os.path.exists(file_path):
raise IOError("There is already a configuration file at %s" %
file_path)
with open(file_path, 'w') as f:
config = configparser.ConfigParser()
config.add_section('misc')
config.set('misc', 'config-version', '1.0')
default_nb_name = os.path.split(os.path.dirname(file_path))[1]
config.set('misc', 'nb-name', default_nb_name)
config.add_section('root')
config.set('root', 'path', '.')
config.add_section('models')
config.set('models', 'module', 'models')
config.add_section('tests')
config.set('tests', 'module', 'tests')
config.add_section('suites')
config.set('suites', 'module', 'suites')
config.write(f) | python | def create(file_path):
"""Create a default .sciunit config file if one does not already exist."""
if os.path.exists(file_path):
raise IOError("There is already a configuration file at %s" %
file_path)
with open(file_path, 'w') as f:
config = configparser.ConfigParser()
config.add_section('misc')
config.set('misc', 'config-version', '1.0')
default_nb_name = os.path.split(os.path.dirname(file_path))[1]
config.set('misc', 'nb-name', default_nb_name)
config.add_section('root')
config.set('root', 'path', '.')
config.add_section('models')
config.set('models', 'module', 'models')
config.add_section('tests')
config.set('tests', 'module', 'tests')
config.add_section('suites')
config.set('suites', 'module', 'suites')
config.write(f) | [
"def",
"create",
"(",
"file_path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"raise",
"IOError",
"(",
"\"There is already a configuration file at %s\"",
"%",
"file_path",
")",
"with",
"open",
"(",
"file_path",
",",
"'w'",
... | Create a default .sciunit config file if one does not already exist. | [
"Create",
"a",
"default",
".",
"sciunit",
"config",
"file",
"if",
"one",
"does",
"not",
"already",
"exist",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L79-L98 | train | 25,429 |
scidash/sciunit | sciunit/__main__.py | parse | def parse(file_path=None, show=False):
"""Parse a .sciunit config file."""
if file_path is None:
file_path = os.path.join(os.getcwd(), '.sciunit')
if not os.path.exists(file_path):
raise IOError('No .sciunit file was found at %s' % file_path)
# Load the configuration file
config = configparser.RawConfigParser(allow_no_value=True)
config.read(file_path)
# List all contents
for section in config.sections():
if show:
print(section)
for options in config.options(section):
if show:
print("\t%s: %s" % (options, config.get(section, options)))
return config | python | def parse(file_path=None, show=False):
"""Parse a .sciunit config file."""
if file_path is None:
file_path = os.path.join(os.getcwd(), '.sciunit')
if not os.path.exists(file_path):
raise IOError('No .sciunit file was found at %s' % file_path)
# Load the configuration file
config = configparser.RawConfigParser(allow_no_value=True)
config.read(file_path)
# List all contents
for section in config.sections():
if show:
print(section)
for options in config.options(section):
if show:
print("\t%s: %s" % (options, config.get(section, options)))
return config | [
"def",
"parse",
"(",
"file_path",
"=",
"None",
",",
"show",
"=",
"False",
")",
":",
"if",
"file_path",
"is",
"None",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"'.sciunit'",
")",
"if",
"not",
"... | Parse a .sciunit config file. | [
"Parse",
"a",
".",
"sciunit",
"config",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L101-L119 | train | 25,430 |
scidash/sciunit | sciunit/__main__.py | prep | def prep(config=None, path=None):
"""Prepare to read the configuration information."""
if config is None:
config = parse()
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
root = os.path.realpath(root)
os.environ['SCIDASH_HOME'] = root
if sys.path[0] != root:
sys.path.insert(0, root) | python | def prep(config=None, path=None):
"""Prepare to read the configuration information."""
if config is None:
config = parse()
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
root = os.path.realpath(root)
os.environ['SCIDASH_HOME'] = root
if sys.path[0] != root:
sys.path.insert(0, root) | [
"def",
"prep",
"(",
"config",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"parse",
"(",
")",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"root",
"=",
"confi... | Prepare to read the configuration information. | [
"Prepare",
"to",
"read",
"the",
"configuration",
"information",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L122-L133 | train | 25,431 |
scidash/sciunit | sciunit/__main__.py | run | def run(config, path=None, stop_on_error=True, just_tests=False):
"""Run sciunit tests for the given configuration."""
if path is None:
path = os.getcwd()
prep(config, path=path)
models = __import__('models')
tests = __import__('tests')
suites = __import__('suites')
print('\n')
for x in ['models', 'tests', 'suites']:
module = __import__(x)
assert hasattr(module, x), "'%s' module requires attribute '%s'" %\
(x, x)
if just_tests:
for test in tests.tests:
_run(test, models, stop_on_error)
else:
for suite in suites.suites:
_run(suite, models, stop_on_error) | python | def run(config, path=None, stop_on_error=True, just_tests=False):
"""Run sciunit tests for the given configuration."""
if path is None:
path = os.getcwd()
prep(config, path=path)
models = __import__('models')
tests = __import__('tests')
suites = __import__('suites')
print('\n')
for x in ['models', 'tests', 'suites']:
module = __import__(x)
assert hasattr(module, x), "'%s' module requires attribute '%s'" %\
(x, x)
if just_tests:
for test in tests.tests:
_run(test, models, stop_on_error)
else:
for suite in suites.suites:
_run(suite, models, stop_on_error) | [
"def",
"run",
"(",
"config",
",",
"path",
"=",
"None",
",",
"stop_on_error",
"=",
"True",
",",
"just_tests",
"=",
"False",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"prep",
"(",
"config",
",",
"path",
... | Run sciunit tests for the given configuration. | [
"Run",
"sciunit",
"tests",
"for",
"the",
"given",
"configuration",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L136-L158 | train | 25,432 |
scidash/sciunit | sciunit/__main__.py | nb_name_from_path | def nb_name_from_path(config, path):
"""Get a notebook name from a path to a notebook"""
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
root = os.path.realpath(root)
default_nb_name = os.path.split(os.path.realpath(root))[1]
nb_name = config.get('misc', 'nb-name', fallback=default_nb_name)
return root, nb_name | python | def nb_name_from_path(config, path):
"""Get a notebook name from a path to a notebook"""
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
root = os.path.realpath(root)
default_nb_name = os.path.split(os.path.realpath(root))[1]
nb_name = config.get('misc', 'nb-name', fallback=default_nb_name)
return root, nb_name | [
"def",
"nb_name_from_path",
"(",
"config",
",",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"root",
"=",
"config",
".",
"get",
"(",
"'root'",
",",
"'path'",
")",
"root",
"=",
"os",
".",
"path",
"... | Get a notebook name from a path to a notebook | [
"Get",
"a",
"notebook",
"name",
"from",
"a",
"path",
"to",
"a",
"notebook"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L168-L177 | train | 25,433 |
scidash/sciunit | sciunit/__main__.py | make_nb | def make_nb(config, path=None, stop_on_error=True, just_tests=False):
"""Create a Jupyter notebook sciunit tests for the given configuration."""
root, nb_name = nb_name_from_path(config, path)
clean = lambda varStr: re.sub('\W|^(?=\d)', '_', varStr)
name = clean(nb_name)
mpl_style = config.get('misc', 'matplotlib', fallback='inline')
cells = [new_markdown_cell('## Sciunit Testing Notebook for %s' % nb_name)]
add_code_cell(cells, (
"%%matplotlib %s\n"
"from IPython.display import display\n"
"from importlib.machinery import SourceFileLoader\n"
"%s = SourceFileLoader('scidash', '%s/__init__.py').load_module()") %
(mpl_style, name, root))
if just_tests:
add_code_cell(cells, (
"for test in %s.tests.tests:\n"
" score_array = test.judge(%s.models.models, stop_on_error=%r)\n"
" display(score_array)") % (name, name, stop_on_error))
else:
add_code_cell(cells, (
"for suite in %s.suites.suites:\n"
" score_matrix = suite.judge("
"%s.models.models, stop_on_error=%r)\n"
" display(score_matrix)") % (name, name, stop_on_error))
write_nb(root, nb_name, cells) | python | def make_nb(config, path=None, stop_on_error=True, just_tests=False):
"""Create a Jupyter notebook sciunit tests for the given configuration."""
root, nb_name = nb_name_from_path(config, path)
clean = lambda varStr: re.sub('\W|^(?=\d)', '_', varStr)
name = clean(nb_name)
mpl_style = config.get('misc', 'matplotlib', fallback='inline')
cells = [new_markdown_cell('## Sciunit Testing Notebook for %s' % nb_name)]
add_code_cell(cells, (
"%%matplotlib %s\n"
"from IPython.display import display\n"
"from importlib.machinery import SourceFileLoader\n"
"%s = SourceFileLoader('scidash', '%s/__init__.py').load_module()") %
(mpl_style, name, root))
if just_tests:
add_code_cell(cells, (
"for test in %s.tests.tests:\n"
" score_array = test.judge(%s.models.models, stop_on_error=%r)\n"
" display(score_array)") % (name, name, stop_on_error))
else:
add_code_cell(cells, (
"for suite in %s.suites.suites:\n"
" score_matrix = suite.judge("
"%s.models.models, stop_on_error=%r)\n"
" display(score_matrix)") % (name, name, stop_on_error))
write_nb(root, nb_name, cells) | [
"def",
"make_nb",
"(",
"config",
",",
"path",
"=",
"None",
",",
"stop_on_error",
"=",
"True",
",",
"just_tests",
"=",
"False",
")",
":",
"root",
",",
"nb_name",
"=",
"nb_name_from_path",
"(",
"config",
",",
"path",
")",
"clean",
"=",
"lambda",
"varStr",
... | Create a Jupyter notebook sciunit tests for the given configuration. | [
"Create",
"a",
"Jupyter",
"notebook",
"sciunit",
"tests",
"for",
"the",
"given",
"configuration",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L180-L205 | train | 25,434 |
scidash/sciunit | sciunit/__main__.py | write_nb | def write_nb(root, nb_name, cells):
"""Write a jupyter notebook to disk.
Takes a given a root directory, a notebook name, and a list of cells.
"""
nb = new_notebook(cells=cells,
metadata={
'language': 'python',
})
nb_path = os.path.join(root, '%s.ipynb' % nb_name)
with codecs.open(nb_path, encoding='utf-8', mode='w') as nb_file:
nbformat.write(nb, nb_file, NB_VERSION)
print("Created Jupyter notebook at:\n%s" % nb_path) | python | def write_nb(root, nb_name, cells):
"""Write a jupyter notebook to disk.
Takes a given a root directory, a notebook name, and a list of cells.
"""
nb = new_notebook(cells=cells,
metadata={
'language': 'python',
})
nb_path = os.path.join(root, '%s.ipynb' % nb_name)
with codecs.open(nb_path, encoding='utf-8', mode='w') as nb_file:
nbformat.write(nb, nb_file, NB_VERSION)
print("Created Jupyter notebook at:\n%s" % nb_path) | [
"def",
"write_nb",
"(",
"root",
",",
"nb_name",
",",
"cells",
")",
":",
"nb",
"=",
"new_notebook",
"(",
"cells",
"=",
"cells",
",",
"metadata",
"=",
"{",
"'language'",
":",
"'python'",
",",
"}",
")",
"nb_path",
"=",
"os",
".",
"path",
".",
"join",
... | Write a jupyter notebook to disk.
Takes a given a root directory, a notebook name, and a list of cells. | [
"Write",
"a",
"jupyter",
"notebook",
"to",
"disk",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L208-L220 | train | 25,435 |
scidash/sciunit | sciunit/__main__.py | run_nb | def run_nb(config, path=None):
"""Run a notebook file.
Runs the one specified by the config file, or the one at
the location specificed by 'path'.
"""
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
nb_name = config.get('misc', 'nb-name')
nb_path = os.path.join(root, '%s.ipynb' % nb_name)
if not os.path.exists(nb_path):
print(("No notebook found at %s. "
"Create the notebook first with make-nb?") % path)
sys.exit(0)
with codecs.open(nb_path, encoding='utf-8', mode='r') as nb_file:
nb = nbformat.read(nb_file, as_version=NB_VERSION)
ep = ExecutePreprocessor(timeout=600)
ep.preprocess(nb, {'metadata': {'path': root}})
with codecs.open(nb_path, encoding='utf-8', mode='w') as nb_file:
nbformat.write(nb, nb_file, NB_VERSION) | python | def run_nb(config, path=None):
"""Run a notebook file.
Runs the one specified by the config file, or the one at
the location specificed by 'path'.
"""
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
nb_name = config.get('misc', 'nb-name')
nb_path = os.path.join(root, '%s.ipynb' % nb_name)
if not os.path.exists(nb_path):
print(("No notebook found at %s. "
"Create the notebook first with make-nb?") % path)
sys.exit(0)
with codecs.open(nb_path, encoding='utf-8', mode='r') as nb_file:
nb = nbformat.read(nb_file, as_version=NB_VERSION)
ep = ExecutePreprocessor(timeout=600)
ep.preprocess(nb, {'metadata': {'path': root}})
with codecs.open(nb_path, encoding='utf-8', mode='w') as nb_file:
nbformat.write(nb, nb_file, NB_VERSION) | [
"def",
"run_nb",
"(",
"config",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"root",
"=",
"config",
".",
"get",
"(",
"'root'",
",",
"'path'",
")",
"root",
"=",
"os",
".",
"path... | Run a notebook file.
Runs the one specified by the config file, or the one at
the location specificed by 'path'. | [
"Run",
"a",
"notebook",
"file",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L223-L245 | train | 25,436 |
scidash/sciunit | sciunit/__main__.py | add_code_cell | def add_code_cell(cells, source):
"""Add a code cell containing `source` to the notebook."""
from nbformat.v4.nbbase import new_code_cell
n_code_cells = len([c for c in cells if c['cell_type'] == 'code'])
cells.append(new_code_cell(source=source, execution_count=n_code_cells+1)) | python | def add_code_cell(cells, source):
"""Add a code cell containing `source` to the notebook."""
from nbformat.v4.nbbase import new_code_cell
n_code_cells = len([c for c in cells if c['cell_type'] == 'code'])
cells.append(new_code_cell(source=source, execution_count=n_code_cells+1)) | [
"def",
"add_code_cell",
"(",
"cells",
",",
"source",
")",
":",
"from",
"nbformat",
".",
"v4",
".",
"nbbase",
"import",
"new_code_cell",
"n_code_cells",
"=",
"len",
"(",
"[",
"c",
"for",
"c",
"in",
"cells",
"if",
"c",
"[",
"'cell_type'",
"]",
"==",
"'co... | Add a code cell containing `source` to the notebook. | [
"Add",
"a",
"code",
"cell",
"containing",
"source",
"to",
"the",
"notebook",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L248-L252 | train | 25,437 |
scidash/sciunit | sciunit/__main__.py | cleanup | def cleanup(config=None, path=None):
"""Cleanup by removing paths added during earlier in configuration."""
if config is None:
config = parse()
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
if sys.path[0] == root:
sys.path.remove(root) | python | def cleanup(config=None, path=None):
"""Cleanup by removing paths added during earlier in configuration."""
if config is None:
config = parse()
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
if sys.path[0] == root:
sys.path.remove(root) | [
"def",
"cleanup",
"(",
"config",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"parse",
"(",
")",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"root",
"=",
"co... | Cleanup by removing paths added during earlier in configuration. | [
"Cleanup",
"by",
"removing",
"paths",
"added",
"during",
"earlier",
"in",
"configuration",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/__main__.py#L255-L264 | train | 25,438 |
scidash/sciunit | sciunit/base.py | Versioned.get_repo | def get_repo(self, cached=True):
"""Get a git repository object for this instance."""
module = sys.modules[self.__module__]
# We use module.__file__ instead of module.__path__[0]
# to include modules without a __path__ attribute.
if hasattr(self.__class__, '_repo') and cached:
repo = self.__class__._repo
elif hasattr(module, '__file__'):
path = os.path.realpath(module.__file__)
try:
repo = git.Repo(path, search_parent_directories=True)
except InvalidGitRepositoryError:
repo = None
else:
repo = None
self.__class__._repo = repo
return repo | python | def get_repo(self, cached=True):
"""Get a git repository object for this instance."""
module = sys.modules[self.__module__]
# We use module.__file__ instead of module.__path__[0]
# to include modules without a __path__ attribute.
if hasattr(self.__class__, '_repo') and cached:
repo = self.__class__._repo
elif hasattr(module, '__file__'):
path = os.path.realpath(module.__file__)
try:
repo = git.Repo(path, search_parent_directories=True)
except InvalidGitRepositoryError:
repo = None
else:
repo = None
self.__class__._repo = repo
return repo | [
"def",
"get_repo",
"(",
"self",
",",
"cached",
"=",
"True",
")",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"self",
".",
"__module__",
"]",
"# We use module.__file__ instead of module.__path__[0]",
"# to include modules without a __path__ attribute.",
"if",
"hasatt... | Get a git repository object for this instance. | [
"Get",
"a",
"git",
"repository",
"object",
"for",
"this",
"instance",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/base.py#L43-L59 | train | 25,439 |
scidash/sciunit | sciunit/base.py | Versioned.get_remote | def get_remote(self, remote='origin'):
"""Get a git remote object for this instance."""
repo = self.get_repo()
if repo is not None:
remotes = {r.name: r for r in repo.remotes}
r = repo.remotes[0] if remote not in remotes else remotes[remote]
else:
r = None
return r | python | def get_remote(self, remote='origin'):
"""Get a git remote object for this instance."""
repo = self.get_repo()
if repo is not None:
remotes = {r.name: r for r in repo.remotes}
r = repo.remotes[0] if remote not in remotes else remotes[remote]
else:
r = None
return r | [
"def",
"get_remote",
"(",
"self",
",",
"remote",
"=",
"'origin'",
")",
":",
"repo",
"=",
"self",
".",
"get_repo",
"(",
")",
"if",
"repo",
"is",
"not",
"None",
":",
"remotes",
"=",
"{",
"r",
".",
"name",
":",
"r",
"for",
"r",
"in",
"repo",
".",
... | Get a git remote object for this instance. | [
"Get",
"a",
"git",
"remote",
"object",
"for",
"this",
"instance",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/base.py#L78-L86 | train | 25,440 |
scidash/sciunit | sciunit/base.py | Versioned.get_remote_url | def get_remote_url(self, remote='origin', cached=True):
"""Get a git remote URL for this instance."""
if hasattr(self.__class__, '_remote_url') and cached:
url = self.__class__._remote_url
else:
r = self.get_remote(remote)
try:
url = list(r.urls)[0]
except GitCommandError as ex:
if 'correct access rights' in str(ex):
# If ssh is not setup to access this repository
cmd = ['git', 'config', '--get', 'remote.%s.url' % r.name]
url = Git().execute(cmd)
else:
raise ex
except AttributeError:
url = None
if url is not None and url.startswith('git@'):
domain = url.split('@')[1].split(':')[0]
path = url.split(':')[1]
url = "http://%s/%s" % (domain, path)
self.__class__._remote_url = url
return url | python | def get_remote_url(self, remote='origin', cached=True):
"""Get a git remote URL for this instance."""
if hasattr(self.__class__, '_remote_url') and cached:
url = self.__class__._remote_url
else:
r = self.get_remote(remote)
try:
url = list(r.urls)[0]
except GitCommandError as ex:
if 'correct access rights' in str(ex):
# If ssh is not setup to access this repository
cmd = ['git', 'config', '--get', 'remote.%s.url' % r.name]
url = Git().execute(cmd)
else:
raise ex
except AttributeError:
url = None
if url is not None and url.startswith('git@'):
domain = url.split('@')[1].split(':')[0]
path = url.split(':')[1]
url = "http://%s/%s" % (domain, path)
self.__class__._remote_url = url
return url | [
"def",
"get_remote_url",
"(",
"self",
",",
"remote",
"=",
"'origin'",
",",
"cached",
"=",
"True",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"__class__",
",",
"'_remote_url'",
")",
"and",
"cached",
":",
"url",
"=",
"self",
".",
"__class__",
".",
"_re... | Get a git remote URL for this instance. | [
"Get",
"a",
"git",
"remote",
"URL",
"for",
"this",
"instance",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/base.py#L88-L110 | train | 25,441 |
scidash/sciunit | sciunit/validators.py | ObservationValidator._validate_iterable | def _validate_iterable(self, is_iterable, key, value):
"""Validate fields with `iterable` key in schema set to True"""
if is_iterable:
try:
iter(value)
except TypeError:
self._error(key, "Must be iterable (e.g. a list or array)") | python | def _validate_iterable(self, is_iterable, key, value):
"""Validate fields with `iterable` key in schema set to True"""
if is_iterable:
try:
iter(value)
except TypeError:
self._error(key, "Must be iterable (e.g. a list or array)") | [
"def",
"_validate_iterable",
"(",
"self",
",",
"is_iterable",
",",
"key",
",",
"value",
")",
":",
"if",
"is_iterable",
":",
"try",
":",
"iter",
"(",
"value",
")",
"except",
"TypeError",
":",
"self",
".",
"_error",
"(",
"key",
",",
"\"Must be iterable (e.g.... | Validate fields with `iterable` key in schema set to True | [
"Validate",
"fields",
"with",
"iterable",
"key",
"in",
"schema",
"set",
"to",
"True"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/validators.py#L37-L43 | train | 25,442 |
scidash/sciunit | sciunit/validators.py | ObservationValidator._validate_units | def _validate_units(self, has_units, key, value):
"""Validate fields with `units` key in schema set to True.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
if has_units:
if isinstance(self.test.units, dict):
required_units = self.test.units[key]
else:
required_units = self.test.units
if not isinstance(value, pq.quantity.Quantity):
self._error(key, "Must be a python quantity")
if not isinstance(value, pq.quantity.Quantity):
self._error(key, "Must be a python quantity")
provided_units = value.simplified.units
if not isinstance(required_units, pq.Dimensionless):
required_units = required_units.simplified.units
if not required_units == provided_units:
self._error(key,
"Must have units of '%s'" % self.test.units.name) | python | def _validate_units(self, has_units, key, value):
"""Validate fields with `units` key in schema set to True.
The rule's arguments are validated against this schema:
{'type': 'boolean'}
"""
if has_units:
if isinstance(self.test.units, dict):
required_units = self.test.units[key]
else:
required_units = self.test.units
if not isinstance(value, pq.quantity.Quantity):
self._error(key, "Must be a python quantity")
if not isinstance(value, pq.quantity.Quantity):
self._error(key, "Must be a python quantity")
provided_units = value.simplified.units
if not isinstance(required_units, pq.Dimensionless):
required_units = required_units.simplified.units
if not required_units == provided_units:
self._error(key,
"Must have units of '%s'" % self.test.units.name) | [
"def",
"_validate_units",
"(",
"self",
",",
"has_units",
",",
"key",
",",
"value",
")",
":",
"if",
"has_units",
":",
"if",
"isinstance",
"(",
"self",
".",
"test",
".",
"units",
",",
"dict",
")",
":",
"required_units",
"=",
"self",
".",
"test",
".",
"... | Validate fields with `units` key in schema set to True.
The rule's arguments are validated against this schema:
{'type': 'boolean'} | [
"Validate",
"fields",
"with",
"units",
"key",
"in",
"schema",
"set",
"to",
"True",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/validators.py#L45-L65 | train | 25,443 |
scidash/sciunit | sciunit/validators.py | ParametersValidator.validate_quantity | def validate_quantity(self, value):
"""Validate that the value is of the `Quantity` type."""
if not isinstance(value, pq.quantity.Quantity):
self._error('%s' % value, "Must be a Python quantity.") | python | def validate_quantity(self, value):
"""Validate that the value is of the `Quantity` type."""
if not isinstance(value, pq.quantity.Quantity):
self._error('%s' % value, "Must be a Python quantity.") | [
"def",
"validate_quantity",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"pq",
".",
"quantity",
".",
"Quantity",
")",
":",
"self",
".",
"_error",
"(",
"'%s'",
"%",
"value",
",",
"\"Must be a Python quantity.\"",
")"
] | Validate that the value is of the `Quantity` type. | [
"Validate",
"that",
"the",
"value",
"is",
"of",
"the",
"Quantity",
"type",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/validators.py#L73-L76 | train | 25,444 |
scidash/sciunit | sciunit/scores/complete.py | ZScore.compute | def compute(cls, observation, prediction):
"""Compute a z-score from an observation and a prediction."""
assert isinstance(observation, dict)
try:
p_value = prediction['mean'] # Use the prediction's mean.
except (TypeError, KeyError, IndexError): # If there isn't one...
try:
p_value = prediction['value'] # Use the prediction's value.
except (TypeError, IndexError): # If there isn't one...
p_value = prediction # Use the prediction (assume numeric).
o_mean = observation['mean']
o_std = observation['std']
value = (p_value - o_mean)/o_std
value = utils.assert_dimensionless(value)
if np.isnan(value):
score = InsufficientDataScore('One of the input values was NaN')
else:
score = ZScore(value)
return score | python | def compute(cls, observation, prediction):
"""Compute a z-score from an observation and a prediction."""
assert isinstance(observation, dict)
try:
p_value = prediction['mean'] # Use the prediction's mean.
except (TypeError, KeyError, IndexError): # If there isn't one...
try:
p_value = prediction['value'] # Use the prediction's value.
except (TypeError, IndexError): # If there isn't one...
p_value = prediction # Use the prediction (assume numeric).
o_mean = observation['mean']
o_std = observation['std']
value = (p_value - o_mean)/o_std
value = utils.assert_dimensionless(value)
if np.isnan(value):
score = InsufficientDataScore('One of the input values was NaN')
else:
score = ZScore(value)
return score | [
"def",
"compute",
"(",
"cls",
",",
"observation",
",",
"prediction",
")",
":",
"assert",
"isinstance",
"(",
"observation",
",",
"dict",
")",
"try",
":",
"p_value",
"=",
"prediction",
"[",
"'mean'",
"]",
"# Use the prediction's mean.",
"except",
"(",
"TypeError... | Compute a z-score from an observation and a prediction. | [
"Compute",
"a",
"z",
"-",
"score",
"from",
"an",
"observation",
"and",
"a",
"prediction",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L55-L73 | train | 25,445 |
scidash/sciunit | sciunit/scores/complete.py | ZScore.norm_score | def norm_score(self):
"""Return the normalized score.
Equals 1.0 for a z-score of 0, falling to 0.0 for extremely positive
or negative values.
"""
cdf = (1.0 + math.erf(self.score / math.sqrt(2.0))) / 2.0
return 1 - 2*math.fabs(0.5 - cdf) | python | def norm_score(self):
"""Return the normalized score.
Equals 1.0 for a z-score of 0, falling to 0.0 for extremely positive
or negative values.
"""
cdf = (1.0 + math.erf(self.score / math.sqrt(2.0))) / 2.0
return 1 - 2*math.fabs(0.5 - cdf) | [
"def",
"norm_score",
"(",
"self",
")",
":",
"cdf",
"=",
"(",
"1.0",
"+",
"math",
".",
"erf",
"(",
"self",
".",
"score",
"/",
"math",
".",
"sqrt",
"(",
"2.0",
")",
")",
")",
"/",
"2.0",
"return",
"1",
"-",
"2",
"*",
"math",
".",
"fabs",
"(",
... | Return the normalized score.
Equals 1.0 for a z-score of 0, falling to 0.0 for extremely positive
or negative values. | [
"Return",
"the",
"normalized",
"score",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L76-L83 | train | 25,446 |
scidash/sciunit | sciunit/scores/complete.py | CohenDScore.compute | def compute(cls, observation, prediction):
"""Compute a Cohen's D from an observation and a prediction."""
assert isinstance(observation, dict)
assert isinstance(prediction, dict)
p_mean = prediction['mean'] # Use the prediction's mean.
p_std = prediction['std']
o_mean = observation['mean']
o_std = observation['std']
try: # Try to pool taking samples sizes into account.
p_n = prediction['n']
o_n = observation['n']
s = (((p_n-1)*(p_std**2) + (o_n-1)*(o_std**2))/(p_n+o_n-2))**0.5
except KeyError: # If sample sizes are not available.
s = (p_std**2 + o_std**2)**0.5
value = (p_mean - o_mean)/s
value = utils.assert_dimensionless(value)
return CohenDScore(value) | python | def compute(cls, observation, prediction):
"""Compute a Cohen's D from an observation and a prediction."""
assert isinstance(observation, dict)
assert isinstance(prediction, dict)
p_mean = prediction['mean'] # Use the prediction's mean.
p_std = prediction['std']
o_mean = observation['mean']
o_std = observation['std']
try: # Try to pool taking samples sizes into account.
p_n = prediction['n']
o_n = observation['n']
s = (((p_n-1)*(p_std**2) + (o_n-1)*(o_std**2))/(p_n+o_n-2))**0.5
except KeyError: # If sample sizes are not available.
s = (p_std**2 + o_std**2)**0.5
value = (p_mean - o_mean)/s
value = utils.assert_dimensionless(value)
return CohenDScore(value) | [
"def",
"compute",
"(",
"cls",
",",
"observation",
",",
"prediction",
")",
":",
"assert",
"isinstance",
"(",
"observation",
",",
"dict",
")",
"assert",
"isinstance",
"(",
"prediction",
",",
"dict",
")",
"p_mean",
"=",
"prediction",
"[",
"'mean'",
"]",
"# Us... | Compute a Cohen's D from an observation and a prediction. | [
"Compute",
"a",
"Cohen",
"s",
"D",
"from",
"an",
"observation",
"and",
"a",
"prediction",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L99-L115 | train | 25,447 |
scidash/sciunit | sciunit/scores/complete.py | RatioScore.compute | def compute(cls, observation, prediction, key=None):
"""Compute a ratio from an observation and a prediction."""
assert isinstance(observation, (dict, float, int, pq.Quantity))
assert isinstance(prediction, (dict, float, int, pq.Quantity))
obs, pred = cls.extract_means_or_values(observation, prediction,
key=key)
value = pred / obs
value = utils.assert_dimensionless(value)
return RatioScore(value) | python | def compute(cls, observation, prediction, key=None):
"""Compute a ratio from an observation and a prediction."""
assert isinstance(observation, (dict, float, int, pq.Quantity))
assert isinstance(prediction, (dict, float, int, pq.Quantity))
obs, pred = cls.extract_means_or_values(observation, prediction,
key=key)
value = pred / obs
value = utils.assert_dimensionless(value)
return RatioScore(value) | [
"def",
"compute",
"(",
"cls",
",",
"observation",
",",
"prediction",
",",
"key",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"observation",
",",
"(",
"dict",
",",
"float",
",",
"int",
",",
"pq",
".",
"Quantity",
")",
")",
"assert",
"isinstance"... | Compute a ratio from an observation and a prediction. | [
"Compute",
"a",
"ratio",
"from",
"an",
"observation",
"and",
"a",
"prediction",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L139-L148 | train | 25,448 |
scidash/sciunit | sciunit/scores/complete.py | FloatScore.compute_ssd | def compute_ssd(cls, observation, prediction):
"""Compute sum-squared diff between observation and prediction."""
# The sum of the squared differences.
value = ((observation - prediction)**2).sum()
score = FloatScore(value)
return score | python | def compute_ssd(cls, observation, prediction):
"""Compute sum-squared diff between observation and prediction."""
# The sum of the squared differences.
value = ((observation - prediction)**2).sum()
score = FloatScore(value)
return score | [
"def",
"compute_ssd",
"(",
"cls",
",",
"observation",
",",
"prediction",
")",
":",
"# The sum of the squared differences.",
"value",
"=",
"(",
"(",
"observation",
"-",
"prediction",
")",
"**",
"2",
")",
".",
"sum",
"(",
")",
"score",
"=",
"FloatScore",
"(",
... | Compute sum-squared diff between observation and prediction. | [
"Compute",
"sum",
"-",
"squared",
"diff",
"between",
"observation",
"and",
"prediction",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/complete.py#L203-L208 | train | 25,449 |
scidash/sciunit | setup.py | read_requirements | def read_requirements():
'''parses requirements from requirements.txt'''
reqs_path = os.path.join('.', 'requirements.txt')
install_reqs = parse_requirements(reqs_path, session=PipSession())
reqs = [str(ir.req) for ir in install_reqs]
return reqs | python | def read_requirements():
'''parses requirements from requirements.txt'''
reqs_path = os.path.join('.', 'requirements.txt')
install_reqs = parse_requirements(reqs_path, session=PipSession())
reqs = [str(ir.req) for ir in install_reqs]
return reqs | [
"def",
"read_requirements",
"(",
")",
":",
"reqs_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'.'",
",",
"'requirements.txt'",
")",
"install_reqs",
"=",
"parse_requirements",
"(",
"reqs_path",
",",
"session",
"=",
"PipSession",
"(",
")",
")",
"reqs",
... | parses requirements from requirements.txt | [
"parses",
"requirements",
"from",
"requirements",
".",
"txt"
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/setup.py#L21-L26 | train | 25,450 |
scidash/sciunit | sciunit/models/backends.py | register_backends | def register_backends(vars):
"""Register backends for use with models.
`vars` should be a dictionary of variables obtained from e.g. `locals()`,
at least some of which are Backend classes, e.g. from imports.
"""
new_backends = {x.replace('Backend', ''): cls
for x, cls in vars.items()
if inspect.isclass(cls) and issubclass(cls, Backend)}
available_backends.update(new_backends) | python | def register_backends(vars):
"""Register backends for use with models.
`vars` should be a dictionary of variables obtained from e.g. `locals()`,
at least some of which are Backend classes, e.g. from imports.
"""
new_backends = {x.replace('Backend', ''): cls
for x, cls in vars.items()
if inspect.isclass(cls) and issubclass(cls, Backend)}
available_backends.update(new_backends) | [
"def",
"register_backends",
"(",
"vars",
")",
":",
"new_backends",
"=",
"{",
"x",
".",
"replace",
"(",
"'Backend'",
",",
"''",
")",
":",
"cls",
"for",
"x",
",",
"cls",
"in",
"vars",
".",
"items",
"(",
")",
"if",
"inspect",
".",
"isclass",
"(",
"cls... | Register backends for use with models.
`vars` should be a dictionary of variables obtained from e.g. `locals()`,
at least some of which are Backend classes, e.g. from imports. | [
"Register",
"backends",
"for",
"use",
"with",
"models",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L12-L21 | train | 25,451 |
scidash/sciunit | sciunit/models/backends.py | Backend.init_backend | def init_backend(self, *args, **kwargs):
"""Initialize the backend."""
self.model.attrs = {}
self.use_memory_cache = kwargs.get('use_memory_cache', True)
if self.use_memory_cache:
self.init_memory_cache()
self.use_disk_cache = kwargs.get('use_disk_cache', False)
if self.use_disk_cache:
self.init_disk_cache()
self.load_model()
self.model.unpicklable += ['_backend'] | python | def init_backend(self, *args, **kwargs):
"""Initialize the backend."""
self.model.attrs = {}
self.use_memory_cache = kwargs.get('use_memory_cache', True)
if self.use_memory_cache:
self.init_memory_cache()
self.use_disk_cache = kwargs.get('use_disk_cache', False)
if self.use_disk_cache:
self.init_disk_cache()
self.load_model()
self.model.unpicklable += ['_backend'] | [
"def",
"init_backend",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"model",
".",
"attrs",
"=",
"{",
"}",
"self",
".",
"use_memory_cache",
"=",
"kwargs",
".",
"get",
"(",
"'use_memory_cache'",
",",
"True",
")",
"if",... | Initialize the backend. | [
"Initialize",
"the",
"backend",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L33-L44 | train | 25,452 |
scidash/sciunit | sciunit/models/backends.py | Backend.init_disk_cache | def init_disk_cache(self):
"""Initialize the on-disk version of the cache."""
try:
# Cleanup old disk cache files
path = self.disk_cache_location
os.remove(path)
except Exception:
pass
self.disk_cache_location = os.path.join(tempfile.mkdtemp(), 'cache') | python | def init_disk_cache(self):
"""Initialize the on-disk version of the cache."""
try:
# Cleanup old disk cache files
path = self.disk_cache_location
os.remove(path)
except Exception:
pass
self.disk_cache_location = os.path.join(tempfile.mkdtemp(), 'cache') | [
"def",
"init_disk_cache",
"(",
"self",
")",
":",
"try",
":",
"# Cleanup old disk cache files",
"path",
"=",
"self",
".",
"disk_cache_location",
"os",
".",
"remove",
"(",
"path",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"disk_cache_location",
"=",
... | Initialize the on-disk version of the cache. | [
"Initialize",
"the",
"on",
"-",
"disk",
"version",
"of",
"the",
"cache",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L64-L72 | train | 25,453 |
scidash/sciunit | sciunit/models/backends.py | Backend.get_memory_cache | def get_memory_cache(self, key=None):
"""Return result in memory cache for key 'key' or None if not found."""
key = self.model.hash if key is None else key
self._results = self.memory_cache.get(key)
return self._results | python | def get_memory_cache(self, key=None):
"""Return result in memory cache for key 'key' or None if not found."""
key = self.model.hash if key is None else key
self._results = self.memory_cache.get(key)
return self._results | [
"def",
"get_memory_cache",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"model",
".",
"hash",
"if",
"key",
"is",
"None",
"else",
"key",
"self",
".",
"_results",
"=",
"self",
".",
"memory_cache",
".",
"get",
"(",
"key",
"... | Return result in memory cache for key 'key' or None if not found. | [
"Return",
"result",
"in",
"memory",
"cache",
"for",
"key",
"key",
"or",
"None",
"if",
"not",
"found",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L74-L78 | train | 25,454 |
scidash/sciunit | sciunit/models/backends.py | Backend.get_disk_cache | def get_disk_cache(self, key=None):
"""Return result in disk cache for key 'key' or None if not found."""
key = self.model.hash if key is None else key
if not getattr(self, 'disk_cache_location', False):
self.init_disk_cache()
disk_cache = shelve.open(self.disk_cache_location)
self._results = disk_cache.get(key)
disk_cache.close()
return self._results | python | def get_disk_cache(self, key=None):
"""Return result in disk cache for key 'key' or None if not found."""
key = self.model.hash if key is None else key
if not getattr(self, 'disk_cache_location', False):
self.init_disk_cache()
disk_cache = shelve.open(self.disk_cache_location)
self._results = disk_cache.get(key)
disk_cache.close()
return self._results | [
"def",
"get_disk_cache",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"model",
".",
"hash",
"if",
"key",
"is",
"None",
"else",
"key",
"if",
"not",
"getattr",
"(",
"self",
",",
"'disk_cache_location'",
",",
"False",
")",
":... | Return result in disk cache for key 'key' or None if not found. | [
"Return",
"result",
"in",
"disk",
"cache",
"for",
"key",
"key",
"or",
"None",
"if",
"not",
"found",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L80-L88 | train | 25,455 |
scidash/sciunit | sciunit/models/backends.py | Backend.set_memory_cache | def set_memory_cache(self, results, key=None):
"""Store result in memory cache with key matching model state."""
key = self.model.hash if key is None else key
self.memory_cache[key] = results | python | def set_memory_cache(self, results, key=None):
"""Store result in memory cache with key matching model state."""
key = self.model.hash if key is None else key
self.memory_cache[key] = results | [
"def",
"set_memory_cache",
"(",
"self",
",",
"results",
",",
"key",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"model",
".",
"hash",
"if",
"key",
"is",
"None",
"else",
"key",
"self",
".",
"memory_cache",
"[",
"key",
"]",
"=",
"results"
] | Store result in memory cache with key matching model state. | [
"Store",
"result",
"in",
"memory",
"cache",
"with",
"key",
"matching",
"model",
"state",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L90-L93 | train | 25,456 |
scidash/sciunit | sciunit/models/backends.py | Backend.set_disk_cache | def set_disk_cache(self, results, key=None):
"""Store result in disk cache with key matching model state."""
if not getattr(self, 'disk_cache_location', False):
self.init_disk_cache()
disk_cache = shelve.open(self.disk_cache_location)
key = self.model.hash if key is None else key
disk_cache[key] = results
disk_cache.close() | python | def set_disk_cache(self, results, key=None):
"""Store result in disk cache with key matching model state."""
if not getattr(self, 'disk_cache_location', False):
self.init_disk_cache()
disk_cache = shelve.open(self.disk_cache_location)
key = self.model.hash if key is None else key
disk_cache[key] = results
disk_cache.close() | [
"def",
"set_disk_cache",
"(",
"self",
",",
"results",
",",
"key",
"=",
"None",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'disk_cache_location'",
",",
"False",
")",
":",
"self",
".",
"init_disk_cache",
"(",
")",
"disk_cache",
"=",
"shelve",
"."... | Store result in disk cache with key matching model state. | [
"Store",
"result",
"in",
"disk",
"cache",
"with",
"key",
"matching",
"model",
"state",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L95-L102 | train | 25,457 |
scidash/sciunit | sciunit/models/backends.py | Backend.backend_run | def backend_run(self):
"""Check for cached results; then run the model if needed."""
key = self.model.hash
if self.use_memory_cache and self.get_memory_cache(key):
return self._results
if self.use_disk_cache and self.get_disk_cache(key):
return self._results
results = self._backend_run()
if self.use_memory_cache:
self.set_memory_cache(results, key)
if self.use_disk_cache:
self.set_disk_cache(results, key)
return results | python | def backend_run(self):
"""Check for cached results; then run the model if needed."""
key = self.model.hash
if self.use_memory_cache and self.get_memory_cache(key):
return self._results
if self.use_disk_cache and self.get_disk_cache(key):
return self._results
results = self._backend_run()
if self.use_memory_cache:
self.set_memory_cache(results, key)
if self.use_disk_cache:
self.set_disk_cache(results, key)
return results | [
"def",
"backend_run",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"model",
".",
"hash",
"if",
"self",
".",
"use_memory_cache",
"and",
"self",
".",
"get_memory_cache",
"(",
"key",
")",
":",
"return",
"self",
".",
"_results",
"if",
"self",
".",
"use_... | Check for cached results; then run the model if needed. | [
"Check",
"for",
"cached",
"results",
";",
"then",
"run",
"the",
"model",
"if",
"needed",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L116-L128 | train | 25,458 |
scidash/sciunit | sciunit/models/backends.py | Backend.save_results | def save_results(self, path='.'):
"""Save results on disk."""
with open(path, 'wb') as f:
pickle.dump(self.results, f) | python | def save_results(self, path='.'):
"""Save results on disk."""
with open(path, 'wb') as f:
pickle.dump(self.results, f) | [
"def",
"save_results",
"(",
"self",
",",
"path",
"=",
"'.'",
")",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"f",
":",
"pickle",
".",
"dump",
"(",
"self",
".",
"results",
",",
"f",
")"
] | Save results on disk. | [
"Save",
"results",
"on",
"disk",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L134-L137 | train | 25,459 |
scidash/sciunit | sciunit/capabilities.py | Capability.check | def check(cls, model, require_extra=False):
"""Check whether the provided model has this capability.
By default, uses isinstance. If `require_extra`, also requires that an
instance check be present in `model.extra_capability_checks`.
"""
class_capable = isinstance(model, cls)
f_name = model.extra_capability_checks.get(cls, None) \
if model.extra_capability_checks is not None \
else False
if f_name:
f = getattr(model, f_name)
instance_capable = f()
elif not require_extra:
instance_capable = True
else:
instance_capable = False
return class_capable and instance_capable | python | def check(cls, model, require_extra=False):
"""Check whether the provided model has this capability.
By default, uses isinstance. If `require_extra`, also requires that an
instance check be present in `model.extra_capability_checks`.
"""
class_capable = isinstance(model, cls)
f_name = model.extra_capability_checks.get(cls, None) \
if model.extra_capability_checks is not None \
else False
if f_name:
f = getattr(model, f_name)
instance_capable = f()
elif not require_extra:
instance_capable = True
else:
instance_capable = False
return class_capable and instance_capable | [
"def",
"check",
"(",
"cls",
",",
"model",
",",
"require_extra",
"=",
"False",
")",
":",
"class_capable",
"=",
"isinstance",
"(",
"model",
",",
"cls",
")",
"f_name",
"=",
"model",
".",
"extra_capability_checks",
".",
"get",
"(",
"cls",
",",
"None",
")",
... | Check whether the provided model has this capability.
By default, uses isinstance. If `require_extra`, also requires that an
instance check be present in `model.extra_capability_checks`. | [
"Check",
"whether",
"the",
"provided",
"model",
"has",
"this",
"capability",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/capabilities.py#L18-L37 | train | 25,460 |
scidash/sciunit | sciunit/models/runnable.py | RunnableModel.set_backend | def set_backend(self, backend):
"""Set the simulation backend."""
if isinstance(backend, str):
name = backend
args = []
kwargs = {}
elif isinstance(backend, (tuple, list)):
name = ''
args = []
kwargs = {}
for i in range(len(backend)):
if i == 0:
name = backend[i]
else:
if isinstance(backend[i], dict):
kwargs.update(backend[i])
else:
args += backend[i]
else:
raise TypeError("Backend must be string, tuple, or list")
if name in available_backends:
self.backend = name
self._backend = available_backends[name]()
elif name is None:
# The base class should not be called.
raise Exception(("A backend (e.g. 'jNeuroML' or 'NEURON') "
"must be selected"))
else:
raise Exception("Backend %s not found in backends.py"
% name)
self._backend.model = self
self._backend.init_backend(*args, **kwargs) | python | def set_backend(self, backend):
"""Set the simulation backend."""
if isinstance(backend, str):
name = backend
args = []
kwargs = {}
elif isinstance(backend, (tuple, list)):
name = ''
args = []
kwargs = {}
for i in range(len(backend)):
if i == 0:
name = backend[i]
else:
if isinstance(backend[i], dict):
kwargs.update(backend[i])
else:
args += backend[i]
else:
raise TypeError("Backend must be string, tuple, or list")
if name in available_backends:
self.backend = name
self._backend = available_backends[name]()
elif name is None:
# The base class should not be called.
raise Exception(("A backend (e.g. 'jNeuroML' or 'NEURON') "
"must be selected"))
else:
raise Exception("Backend %s not found in backends.py"
% name)
self._backend.model = self
self._backend.init_backend(*args, **kwargs) | [
"def",
"set_backend",
"(",
"self",
",",
"backend",
")",
":",
"if",
"isinstance",
"(",
"backend",
",",
"str",
")",
":",
"name",
"=",
"backend",
"args",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"backend",
",",
"(",
"tuple",
... | Set the simulation backend. | [
"Set",
"the",
"simulation",
"backend",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/runnable.py#L33-L64 | train | 25,461 |
scidash/sciunit | sciunit/scores/base.py | Score.color | def color(self, value=None):
"""Turn the score intp an RGB color tuple of three 8-bit integers."""
if value is None:
value = self.norm_score
rgb = Score.value_color(value)
return rgb | python | def color(self, value=None):
"""Turn the score intp an RGB color tuple of three 8-bit integers."""
if value is None:
value = self.norm_score
rgb = Score.value_color(value)
return rgb | [
"def",
"color",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"self",
".",
"norm_score",
"rgb",
"=",
"Score",
".",
"value_color",
"(",
"value",
")",
"return",
"rgb"
] | Turn the score intp an RGB color tuple of three 8-bit integers. | [
"Turn",
"the",
"score",
"intp",
"an",
"RGB",
"color",
"tuple",
"of",
"three",
"8",
"-",
"bit",
"integers",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/base.py#L83-L88 | train | 25,462 |
scidash/sciunit | sciunit/scores/base.py | Score.extract_means_or_values | def extract_means_or_values(cls, observation, prediction, key=None):
"""Extracts the mean, value, or user-provided key from the observation
and prediction dictionaries.
"""
obs_mv = cls.extract_mean_or_value(observation, key)
pred_mv = cls.extract_mean_or_value(prediction, key)
return obs_mv, pred_mv | python | def extract_means_or_values(cls, observation, prediction, key=None):
"""Extracts the mean, value, or user-provided key from the observation
and prediction dictionaries.
"""
obs_mv = cls.extract_mean_or_value(observation, key)
pred_mv = cls.extract_mean_or_value(prediction, key)
return obs_mv, pred_mv | [
"def",
"extract_means_or_values",
"(",
"cls",
",",
"observation",
",",
"prediction",
",",
"key",
"=",
"None",
")",
":",
"obs_mv",
"=",
"cls",
".",
"extract_mean_or_value",
"(",
"observation",
",",
"key",
")",
"pred_mv",
"=",
"cls",
".",
"extract_mean_or_value"... | Extracts the mean, value, or user-provided key from the observation
and prediction dictionaries. | [
"Extracts",
"the",
"mean",
"value",
"or",
"user",
"-",
"provided",
"key",
"from",
"the",
"observation",
"and",
"prediction",
"dictionaries",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/base.py#L209-L216 | train | 25,463 |
scidash/sciunit | sciunit/scores/base.py | Score.extract_mean_or_value | def extract_mean_or_value(cls, obs_or_pred, key=None):
"""Extracts the mean, value, or user-provided key from an observation
or prediction dictionary.
"""
result = None
if not isinstance(obs_or_pred, dict):
result = obs_or_pred
else:
keys = ([key] if key is not None else []) + ['mean', 'value']
for k in keys:
if k in obs_or_pred:
result = obs_or_pred[k]
break
if result is None:
raise KeyError(("%s has neither a mean nor a single "
"value" % obs_or_pred))
return result | python | def extract_mean_or_value(cls, obs_or_pred, key=None):
"""Extracts the mean, value, or user-provided key from an observation
or prediction dictionary.
"""
result = None
if not isinstance(obs_or_pred, dict):
result = obs_or_pred
else:
keys = ([key] if key is not None else []) + ['mean', 'value']
for k in keys:
if k in obs_or_pred:
result = obs_or_pred[k]
break
if result is None:
raise KeyError(("%s has neither a mean nor a single "
"value" % obs_or_pred))
return result | [
"def",
"extract_mean_or_value",
"(",
"cls",
",",
"obs_or_pred",
",",
"key",
"=",
"None",
")",
":",
"result",
"=",
"None",
"if",
"not",
"isinstance",
"(",
"obs_or_pred",
",",
"dict",
")",
":",
"result",
"=",
"obs_or_pred",
"else",
":",
"keys",
"=",
"(",
... | Extracts the mean, value, or user-provided key from an observation
or prediction dictionary. | [
"Extracts",
"the",
"mean",
"value",
"or",
"user",
"-",
"provided",
"key",
"from",
"an",
"observation",
"or",
"prediction",
"dictionary",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/base.py#L219-L236 | train | 25,464 |
scidash/sciunit | sciunit/scores/base.py | ErrorScore.summary | def summary(self):
"""Summarize the performance of a model on a test."""
return "== Model %s did not complete test %s due to error '%s'. ==" %\
(str(self.model), str(self.test), str(self.score)) | python | def summary(self):
"""Summarize the performance of a model on a test."""
return "== Model %s did not complete test %s due to error '%s'. ==" %\
(str(self.model), str(self.test), str(self.score)) | [
"def",
"summary",
"(",
"self",
")",
":",
"return",
"\"== Model %s did not complete test %s due to error '%s'. ==\"",
"%",
"(",
"str",
"(",
"self",
".",
"model",
")",
",",
"str",
"(",
"self",
".",
"test",
")",
",",
"str",
"(",
"self",
".",
"score",
")",
")"... | Summarize the performance of a model on a test. | [
"Summarize",
"the",
"performance",
"of",
"a",
"model",
"on",
"a",
"test",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/scores/base.py#L247-L250 | train | 25,465 |
mon/ifstools | ifstools/handlers/TexFolder.py | ImageCanvas.load | def load(self, draw_bbox = False, **kwargs):
''' Makes the canvas.
This could be far speedier if it copied raw pixels, but that would
take far too much time to write vs using Image inbuilts '''
im = Image.new('RGBA', self.img_size)
draw = None
if draw_bbox:
draw = ImageDraw.Draw(im)
for sprite in self.images:
data = sprite.load()
sprite_im = Image.open(BytesIO(data))
size = sprite.imgrect
im.paste(sprite_im, (size[0], size[2]))
if draw_bbox:
draw.rectangle((size[0], size[2], size[1], size[3]), outline='red')
del draw
b = BytesIO()
im.save(b, format = 'PNG')
return b.getvalue() | python | def load(self, draw_bbox = False, **kwargs):
''' Makes the canvas.
This could be far speedier if it copied raw pixels, but that would
take far too much time to write vs using Image inbuilts '''
im = Image.new('RGBA', self.img_size)
draw = None
if draw_bbox:
draw = ImageDraw.Draw(im)
for sprite in self.images:
data = sprite.load()
sprite_im = Image.open(BytesIO(data))
size = sprite.imgrect
im.paste(sprite_im, (size[0], size[2]))
if draw_bbox:
draw.rectangle((size[0], size[2], size[1], size[3]), outline='red')
del draw
b = BytesIO()
im.save(b, format = 'PNG')
return b.getvalue() | [
"def",
"load",
"(",
"self",
",",
"draw_bbox",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"im",
"=",
"Image",
".",
"new",
"(",
"'RGBA'",
",",
"self",
".",
"img_size",
")",
"draw",
"=",
"None",
"if",
"draw_bbox",
":",
"draw",
"=",
"ImageDraw",
... | Makes the canvas.
This could be far speedier if it copied raw pixels, but that would
take far too much time to write vs using Image inbuilts | [
"Makes",
"the",
"canvas",
".",
"This",
"could",
"be",
"far",
"speedier",
"if",
"it",
"copied",
"raw",
"pixels",
"but",
"that",
"would",
"take",
"far",
"too",
"much",
"time",
"to",
"write",
"vs",
"using",
"Image",
"inbuilts"
] | ccd9c1c3632aa22cdcc4e064f17e07803b1d27ba | https://github.com/mon/ifstools/blob/ccd9c1c3632aa22cdcc4e064f17e07803b1d27ba/ifstools/handlers/TexFolder.py#L35-L56 | train | 25,466 |
mon/ifstools | ifstools/handlers/lz77.py | match_window | def match_window(in_data, offset):
'''Find the longest match for the string starting at offset in the preceeding data
'''
window_start = max(offset - WINDOW_MASK, 0)
for n in range(MAX_LEN, THRESHOLD-1, -1):
window_end = min(offset + n, len(in_data))
# we've not got enough data left for a meaningful result
if window_end - offset < THRESHOLD:
return None
str_to_find = in_data[offset:window_end]
idx = in_data.rfind(str_to_find, window_start, window_end-n)
if idx != -1:
code_offset = offset - idx # - 1
code_len = len(str_to_find)
return (code_offset, code_len)
return None | python | def match_window(in_data, offset):
'''Find the longest match for the string starting at offset in the preceeding data
'''
window_start = max(offset - WINDOW_MASK, 0)
for n in range(MAX_LEN, THRESHOLD-1, -1):
window_end = min(offset + n, len(in_data))
# we've not got enough data left for a meaningful result
if window_end - offset < THRESHOLD:
return None
str_to_find = in_data[offset:window_end]
idx = in_data.rfind(str_to_find, window_start, window_end-n)
if idx != -1:
code_offset = offset - idx # - 1
code_len = len(str_to_find)
return (code_offset, code_len)
return None | [
"def",
"match_window",
"(",
"in_data",
",",
"offset",
")",
":",
"window_start",
"=",
"max",
"(",
"offset",
"-",
"WINDOW_MASK",
",",
"0",
")",
"for",
"n",
"in",
"range",
"(",
"MAX_LEN",
",",
"THRESHOLD",
"-",
"1",
",",
"-",
"1",
")",
":",
"window_end"... | Find the longest match for the string starting at offset in the preceeding data | [
"Find",
"the",
"longest",
"match",
"for",
"the",
"string",
"starting",
"at",
"offset",
"in",
"the",
"preceeding",
"data"
] | ccd9c1c3632aa22cdcc4e064f17e07803b1d27ba | https://github.com/mon/ifstools/blob/ccd9c1c3632aa22cdcc4e064f17e07803b1d27ba/ifstools/handlers/lz77.py#L44-L61 | train | 25,467 |
Ch00k/ffmpy | ffmpy.py | _merge_args_opts | def _merge_args_opts(args_opts_dict, **kwargs):
"""Merge options with their corresponding arguments.
Iterates over the dictionary holding arguments (keys) and options (values). Merges each
options string with its corresponding argument.
:param dict args_opts_dict: a dictionary of arguments and options
:param dict kwargs: *input_option* - if specified prepends ``-i`` to input argument
:return: merged list of strings with arguments and their corresponding options
:rtype: list
"""
merged = []
if not args_opts_dict:
return merged
for arg, opt in args_opts_dict.items():
if not _is_sequence(opt):
opt = shlex.split(opt or '')
merged += opt
if not arg:
continue
if 'add_input_option' in kwargs:
merged.append('-i')
merged.append(arg)
return merged | python | def _merge_args_opts(args_opts_dict, **kwargs):
"""Merge options with their corresponding arguments.
Iterates over the dictionary holding arguments (keys) and options (values). Merges each
options string with its corresponding argument.
:param dict args_opts_dict: a dictionary of arguments and options
:param dict kwargs: *input_option* - if specified prepends ``-i`` to input argument
:return: merged list of strings with arguments and their corresponding options
:rtype: list
"""
merged = []
if not args_opts_dict:
return merged
for arg, opt in args_opts_dict.items():
if not _is_sequence(opt):
opt = shlex.split(opt or '')
merged += opt
if not arg:
continue
if 'add_input_option' in kwargs:
merged.append('-i')
merged.append(arg)
return merged | [
"def",
"_merge_args_opts",
"(",
"args_opts_dict",
",",
"*",
"*",
"kwargs",
")",
":",
"merged",
"=",
"[",
"]",
"if",
"not",
"args_opts_dict",
":",
"return",
"merged",
"for",
"arg",
",",
"opt",
"in",
"args_opts_dict",
".",
"items",
"(",
")",
":",
"if",
"... | Merge options with their corresponding arguments.
Iterates over the dictionary holding arguments (keys) and options (values). Merges each
options string with its corresponding argument.
:param dict args_opts_dict: a dictionary of arguments and options
:param dict kwargs: *input_option* - if specified prepends ``-i`` to input argument
:return: merged list of strings with arguments and their corresponding options
:rtype: list | [
"Merge",
"options",
"with",
"their",
"corresponding",
"arguments",
"."
] | 4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75 | https://github.com/Ch00k/ffmpy/blob/4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75/ffmpy.py#L171-L200 | train | 25,468 |
Ch00k/ffmpy | ffmpy.py | FFmpeg.run | def run(self, input_data=None, stdout=None, stderr=None):
"""Execute FFmpeg command line.
``input_data`` can contain input for FFmpeg in case ``pipe`` protocol is used for input.
``stdout`` and ``stderr`` specify where to redirect the ``stdout`` and ``stderr`` of the
process. By default no redirection is done, which means all output goes to running shell
(this mode should normally only be used for debugging purposes). If FFmpeg ``pipe`` protocol
is used for output, ``stdout`` must be redirected to a pipe by passing `subprocess.PIPE` as
``stdout`` argument.
Returns a 2-tuple containing ``stdout`` and ``stderr`` of the process. If there was no
redirection or if the output was redirected to e.g. `os.devnull`, the value returned will
be a tuple of two `None` values, otherwise it will contain the actual ``stdout`` and
``stderr`` data returned by ffmpeg process.
More info about ``pipe`` protocol `here <https://ffmpeg.org/ffmpeg-protocols.html#pipe>`_.
:param str input_data: input data for FFmpeg to deal with (audio, video etc.) as bytes (e.g.
the result of reading a file in binary mode)
:param stdout: redirect FFmpeg ``stdout`` there (default is `None` which means no
redirection)
:param stderr: redirect FFmpeg ``stderr`` there (default is `None` which means no
redirection)
:return: a 2-tuple containing ``stdout`` and ``stderr`` of the process
:rtype: tuple
:raise: `FFRuntimeError` in case FFmpeg command exits with a non-zero code;
`FFExecutableNotFoundError` in case the executable path passed was not valid
"""
try:
self.process = subprocess.Popen(
self._cmd,
stdin=subprocess.PIPE,
stdout=stdout,
stderr=stderr
)
except OSError as e:
if e.errno == errno.ENOENT:
raise FFExecutableNotFoundError("Executable '{0}' not found".format(self.executable))
else:
raise
out = self.process.communicate(input=input_data)
if self.process.returncode != 0:
raise FFRuntimeError(self.cmd, self.process.returncode, out[0], out[1])
return out | python | def run(self, input_data=None, stdout=None, stderr=None):
"""Execute FFmpeg command line.
``input_data`` can contain input for FFmpeg in case ``pipe`` protocol is used for input.
``stdout`` and ``stderr`` specify where to redirect the ``stdout`` and ``stderr`` of the
process. By default no redirection is done, which means all output goes to running shell
(this mode should normally only be used for debugging purposes). If FFmpeg ``pipe`` protocol
is used for output, ``stdout`` must be redirected to a pipe by passing `subprocess.PIPE` as
``stdout`` argument.
Returns a 2-tuple containing ``stdout`` and ``stderr`` of the process. If there was no
redirection or if the output was redirected to e.g. `os.devnull`, the value returned will
be a tuple of two `None` values, otherwise it will contain the actual ``stdout`` and
``stderr`` data returned by ffmpeg process.
More info about ``pipe`` protocol `here <https://ffmpeg.org/ffmpeg-protocols.html#pipe>`_.
:param str input_data: input data for FFmpeg to deal with (audio, video etc.) as bytes (e.g.
the result of reading a file in binary mode)
:param stdout: redirect FFmpeg ``stdout`` there (default is `None` which means no
redirection)
:param stderr: redirect FFmpeg ``stderr`` there (default is `None` which means no
redirection)
:return: a 2-tuple containing ``stdout`` and ``stderr`` of the process
:rtype: tuple
:raise: `FFRuntimeError` in case FFmpeg command exits with a non-zero code;
`FFExecutableNotFoundError` in case the executable path passed was not valid
"""
try:
self.process = subprocess.Popen(
self._cmd,
stdin=subprocess.PIPE,
stdout=stdout,
stderr=stderr
)
except OSError as e:
if e.errno == errno.ENOENT:
raise FFExecutableNotFoundError("Executable '{0}' not found".format(self.executable))
else:
raise
out = self.process.communicate(input=input_data)
if self.process.returncode != 0:
raise FFRuntimeError(self.cmd, self.process.returncode, out[0], out[1])
return out | [
"def",
"run",
"(",
"self",
",",
"input_data",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"_cmd",
",",
"stdin",
"=",
"subproce... | Execute FFmpeg command line.
``input_data`` can contain input for FFmpeg in case ``pipe`` protocol is used for input.
``stdout`` and ``stderr`` specify where to redirect the ``stdout`` and ``stderr`` of the
process. By default no redirection is done, which means all output goes to running shell
(this mode should normally only be used for debugging purposes). If FFmpeg ``pipe`` protocol
is used for output, ``stdout`` must be redirected to a pipe by passing `subprocess.PIPE` as
``stdout`` argument.
Returns a 2-tuple containing ``stdout`` and ``stderr`` of the process. If there was no
redirection or if the output was redirected to e.g. `os.devnull`, the value returned will
be a tuple of two `None` values, otherwise it will contain the actual ``stdout`` and
``stderr`` data returned by ffmpeg process.
More info about ``pipe`` protocol `here <https://ffmpeg.org/ffmpeg-protocols.html#pipe>`_.
:param str input_data: input data for FFmpeg to deal with (audio, video etc.) as bytes (e.g.
the result of reading a file in binary mode)
:param stdout: redirect FFmpeg ``stdout`` there (default is `None` which means no
redirection)
:param stderr: redirect FFmpeg ``stderr`` there (default is `None` which means no
redirection)
:return: a 2-tuple containing ``stdout`` and ``stderr`` of the process
:rtype: tuple
:raise: `FFRuntimeError` in case FFmpeg command exits with a non-zero code;
`FFExecutableNotFoundError` in case the executable path passed was not valid | [
"Execute",
"FFmpeg",
"command",
"line",
"."
] | 4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75 | https://github.com/Ch00k/ffmpy/blob/4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75/ffmpy.py#L62-L107 | train | 25,469 |
click-contrib/sphinx-click | sphinx_click/ext.py | _get_usage | def _get_usage(ctx):
"""Alternative, non-prefixed version of 'get_usage'."""
formatter = ctx.make_formatter()
pieces = ctx.command.collect_usage_pieces(ctx)
formatter.write_usage(ctx.command_path, ' '.join(pieces), prefix='')
return formatter.getvalue().rstrip('\n') | python | def _get_usage(ctx):
"""Alternative, non-prefixed version of 'get_usage'."""
formatter = ctx.make_formatter()
pieces = ctx.command.collect_usage_pieces(ctx)
formatter.write_usage(ctx.command_path, ' '.join(pieces), prefix='')
return formatter.getvalue().rstrip('\n') | [
"def",
"_get_usage",
"(",
"ctx",
")",
":",
"formatter",
"=",
"ctx",
".",
"make_formatter",
"(",
")",
"pieces",
"=",
"ctx",
".",
"command",
".",
"collect_usage_pieces",
"(",
"ctx",
")",
"formatter",
".",
"write_usage",
"(",
"ctx",
".",
"command_path",
",",
... | Alternative, non-prefixed version of 'get_usage'. | [
"Alternative",
"non",
"-",
"prefixed",
"version",
"of",
"get_usage",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L23-L28 | train | 25,470 |
click-contrib/sphinx-click | sphinx_click/ext.py | _get_help_record | def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-separated opts and option arguments surrounded by angle brackets [1].
[1] http://www.sphinx-doc.org/en/stable/domains.html#directive-option
"""
def _write_opts(opts):
rv, _ = click.formatting.join_options(opts)
if not opt.is_flag and not opt.count:
rv += ' <{}>'.format(opt.name)
return rv
rv = [_write_opts(opt.opts)]
if opt.secondary_opts:
rv.append(_write_opts(opt.secondary_opts))
help = opt.help or ''
extra = []
if opt.default is not None and opt.show_default:
extra.append(
'default: %s' % (', '.join('%s' % d for d in opt.default)
if isinstance(opt.default,
(list, tuple)) else opt.default, ))
if opt.required:
extra.append('required')
if extra:
help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))
return ', '.join(rv), help | python | def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-separated opts and option arguments surrounded by angle brackets [1].
[1] http://www.sphinx-doc.org/en/stable/domains.html#directive-option
"""
def _write_opts(opts):
rv, _ = click.formatting.join_options(opts)
if not opt.is_flag and not opt.count:
rv += ' <{}>'.format(opt.name)
return rv
rv = [_write_opts(opt.opts)]
if opt.secondary_opts:
rv.append(_write_opts(opt.secondary_opts))
help = opt.help or ''
extra = []
if opt.default is not None and opt.show_default:
extra.append(
'default: %s' % (', '.join('%s' % d for d in opt.default)
if isinstance(opt.default,
(list, tuple)) else opt.default, ))
if opt.required:
extra.append('required')
if extra:
help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))
return ', '.join(rv), help | [
"def",
"_get_help_record",
"(",
"opt",
")",
":",
"def",
"_write_opts",
"(",
"opts",
")",
":",
"rv",
",",
"_",
"=",
"click",
".",
"formatting",
".",
"join_options",
"(",
"opts",
")",
"if",
"not",
"opt",
".",
"is_flag",
"and",
"not",
"opt",
".",
"count... | Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-separated opts and option arguments surrounded by angle brackets [1].
[1] http://www.sphinx-doc.org/en/stable/domains.html#directive-option | [
"Re",
"-",
"implementation",
"of",
"click",
".",
"Opt",
".",
"get_help_record",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L31-L64 | train | 25,471 |
click-contrib/sphinx-click | sphinx_click/ext.py | _format_description | def _format_description(ctx):
"""Format the description for a given `click.Command`.
We parse this as reStructuredText, allowing users to embed rich
information in their help messages if they so choose.
"""
help_string = ctx.command.help or ctx.command.short_help
if not help_string:
return
bar_enabled = False
for line in statemachine.string2lines(
help_string, tab_width=4, convert_whitespace=True):
if line == '\b':
bar_enabled = True
continue
if line == '':
bar_enabled = False
line = '| ' + line if bar_enabled else line
yield line
yield '' | python | def _format_description(ctx):
"""Format the description for a given `click.Command`.
We parse this as reStructuredText, allowing users to embed rich
information in their help messages if they so choose.
"""
help_string = ctx.command.help or ctx.command.short_help
if not help_string:
return
bar_enabled = False
for line in statemachine.string2lines(
help_string, tab_width=4, convert_whitespace=True):
if line == '\b':
bar_enabled = True
continue
if line == '':
bar_enabled = False
line = '| ' + line if bar_enabled else line
yield line
yield '' | [
"def",
"_format_description",
"(",
"ctx",
")",
":",
"help_string",
"=",
"ctx",
".",
"command",
".",
"help",
"or",
"ctx",
".",
"command",
".",
"short_help",
"if",
"not",
"help_string",
":",
"return",
"bar_enabled",
"=",
"False",
"for",
"line",
"in",
"statem... | Format the description for a given `click.Command`.
We parse this as reStructuredText, allowing users to embed rich
information in their help messages if they so choose. | [
"Format",
"the",
"description",
"for",
"a",
"given",
"click",
".",
"Command",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L67-L87 | train | 25,472 |
click-contrib/sphinx-click | sphinx_click/ext.py | _format_option | def _format_option(opt):
"""Format the output for a `click.Option`."""
opt = _get_help_record(opt)
yield '.. option:: {}'.format(opt[0])
if opt[1]:
yield ''
for line in statemachine.string2lines(
opt[1], tab_width=4, convert_whitespace=True):
yield _indent(line) | python | def _format_option(opt):
"""Format the output for a `click.Option`."""
opt = _get_help_record(opt)
yield '.. option:: {}'.format(opt[0])
if opt[1]:
yield ''
for line in statemachine.string2lines(
opt[1], tab_width=4, convert_whitespace=True):
yield _indent(line) | [
"def",
"_format_option",
"(",
"opt",
")",
":",
"opt",
"=",
"_get_help_record",
"(",
"opt",
")",
"yield",
"'.. option:: {}'",
".",
"format",
"(",
"opt",
"[",
"0",
"]",
")",
"if",
"opt",
"[",
"1",
"]",
":",
"yield",
"''",
"for",
"line",
"in",
"statemac... | Format the output for a `click.Option`. | [
"Format",
"the",
"output",
"for",
"a",
"click",
".",
"Option",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L99-L108 | train | 25,473 |
click-contrib/sphinx-click | sphinx_click/ext.py | _format_options | def _format_options(ctx):
"""Format all `click.Option` for a `click.Command`."""
# the hidden attribute is part of click 7.x only hence use of getattr
params = [
x for x in ctx.command.params
if isinstance(x, click.Option) and not getattr(x, 'hidden', False)
]
for param in params:
for line in _format_option(param):
yield line
yield '' | python | def _format_options(ctx):
"""Format all `click.Option` for a `click.Command`."""
# the hidden attribute is part of click 7.x only hence use of getattr
params = [
x for x in ctx.command.params
if isinstance(x, click.Option) and not getattr(x, 'hidden', False)
]
for param in params:
for line in _format_option(param):
yield line
yield '' | [
"def",
"_format_options",
"(",
"ctx",
")",
":",
"# the hidden attribute is part of click 7.x only hence use of getattr",
"params",
"=",
"[",
"x",
"for",
"x",
"in",
"ctx",
".",
"command",
".",
"params",
"if",
"isinstance",
"(",
"x",
",",
"click",
".",
"Option",
"... | Format all `click.Option` for a `click.Command`. | [
"Format",
"all",
"click",
".",
"Option",
"for",
"a",
"click",
".",
"Command",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L111-L122 | train | 25,474 |
click-contrib/sphinx-click | sphinx_click/ext.py | _format_argument | def _format_argument(arg):
"""Format the output of a `click.Argument`."""
yield '.. option:: {}'.format(arg.human_readable_name)
yield ''
yield _indent('{} argument{}'.format(
'Required' if arg.required else 'Optional',
'(s)' if arg.nargs != 1 else '')) | python | def _format_argument(arg):
"""Format the output of a `click.Argument`."""
yield '.. option:: {}'.format(arg.human_readable_name)
yield ''
yield _indent('{} argument{}'.format(
'Required' if arg.required else 'Optional',
'(s)' if arg.nargs != 1 else '')) | [
"def",
"_format_argument",
"(",
"arg",
")",
":",
"yield",
"'.. option:: {}'",
".",
"format",
"(",
"arg",
".",
"human_readable_name",
")",
"yield",
"''",
"yield",
"_indent",
"(",
"'{} argument{}'",
".",
"format",
"(",
"'Required'",
"if",
"arg",
".",
"required",... | Format the output of a `click.Argument`. | [
"Format",
"the",
"output",
"of",
"a",
"click",
".",
"Argument",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L125-L131 | train | 25,475 |
click-contrib/sphinx-click | sphinx_click/ext.py | _format_arguments | def _format_arguments(ctx):
"""Format all `click.Argument` for a `click.Command`."""
params = [x for x in ctx.command.params if isinstance(x, click.Argument)]
for param in params:
for line in _format_argument(param):
yield line
yield '' | python | def _format_arguments(ctx):
"""Format all `click.Argument` for a `click.Command`."""
params = [x for x in ctx.command.params if isinstance(x, click.Argument)]
for param in params:
for line in _format_argument(param):
yield line
yield '' | [
"def",
"_format_arguments",
"(",
"ctx",
")",
":",
"params",
"=",
"[",
"x",
"for",
"x",
"in",
"ctx",
".",
"command",
".",
"params",
"if",
"isinstance",
"(",
"x",
",",
"click",
".",
"Argument",
")",
"]",
"for",
"param",
"in",
"params",
":",
"for",
"l... | Format all `click.Argument` for a `click.Command`. | [
"Format",
"all",
"click",
".",
"Argument",
"for",
"a",
"click",
".",
"Command",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L134-L141 | train | 25,476 |
click-contrib/sphinx-click | sphinx_click/ext.py | _format_envvar | def _format_envvar(param):
"""Format the envvars of a `click.Option` or `click.Argument`."""
yield '.. envvar:: {}'.format(param.envvar)
yield ' :noindex:'
yield ''
if isinstance(param, click.Argument):
param_ref = param.human_readable_name
else:
# if a user has defined an opt with multiple "aliases", always use the
# first. For example, if '--foo' or '-f' are possible, use '--foo'.
param_ref = param.opts[0]
yield _indent('Provide a default for :option:`{}`'.format(param_ref)) | python | def _format_envvar(param):
"""Format the envvars of a `click.Option` or `click.Argument`."""
yield '.. envvar:: {}'.format(param.envvar)
yield ' :noindex:'
yield ''
if isinstance(param, click.Argument):
param_ref = param.human_readable_name
else:
# if a user has defined an opt with multiple "aliases", always use the
# first. For example, if '--foo' or '-f' are possible, use '--foo'.
param_ref = param.opts[0]
yield _indent('Provide a default for :option:`{}`'.format(param_ref)) | [
"def",
"_format_envvar",
"(",
"param",
")",
":",
"yield",
"'.. envvar:: {}'",
".",
"format",
"(",
"param",
".",
"envvar",
")",
"yield",
"' :noindex:'",
"yield",
"''",
"if",
"isinstance",
"(",
"param",
",",
"click",
".",
"Argument",
")",
":",
"param_ref",
... | Format the envvars of a `click.Option` or `click.Argument`. | [
"Format",
"the",
"envvars",
"of",
"a",
"click",
".",
"Option",
"or",
"click",
".",
"Argument",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L144-L156 | train | 25,477 |
click-contrib/sphinx-click | sphinx_click/ext.py | _format_envvars | def _format_envvars(ctx):
"""Format all envvars for a `click.Command`."""
params = [x for x in ctx.command.params if getattr(x, 'envvar')]
for param in params:
yield '.. _{command_name}-{param_name}-{envvar}:'.format(
command_name=ctx.command_path.replace(' ', '-'),
param_name=param.name,
envvar=param.envvar,
)
yield ''
for line in _format_envvar(param):
yield line
yield '' | python | def _format_envvars(ctx):
"""Format all envvars for a `click.Command`."""
params = [x for x in ctx.command.params if getattr(x, 'envvar')]
for param in params:
yield '.. _{command_name}-{param_name}-{envvar}:'.format(
command_name=ctx.command_path.replace(' ', '-'),
param_name=param.name,
envvar=param.envvar,
)
yield ''
for line in _format_envvar(param):
yield line
yield '' | [
"def",
"_format_envvars",
"(",
"ctx",
")",
":",
"params",
"=",
"[",
"x",
"for",
"x",
"in",
"ctx",
".",
"command",
".",
"params",
"if",
"getattr",
"(",
"x",
",",
"'envvar'",
")",
"]",
"for",
"param",
"in",
"params",
":",
"yield",
"'.. _{command_name}-{p... | Format all envvars for a `click.Command`. | [
"Format",
"all",
"envvars",
"for",
"a",
"click",
".",
"Command",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L159-L172 | train | 25,478 |
click-contrib/sphinx-click | sphinx_click/ext.py | _format_subcommand | def _format_subcommand(command):
"""Format a sub-command of a `click.Command` or `click.Group`."""
yield '.. object:: {}'.format(command.name)
# click 7.0 stopped setting short_help by default
if CLICK_VERSION < (7, 0):
short_help = command.short_help
else:
short_help = command.get_short_help_str()
if short_help:
yield ''
for line in statemachine.string2lines(
short_help, tab_width=4, convert_whitespace=True):
yield _indent(line) | python | def _format_subcommand(command):
"""Format a sub-command of a `click.Command` or `click.Group`."""
yield '.. object:: {}'.format(command.name)
# click 7.0 stopped setting short_help by default
if CLICK_VERSION < (7, 0):
short_help = command.short_help
else:
short_help = command.get_short_help_str()
if short_help:
yield ''
for line in statemachine.string2lines(
short_help, tab_width=4, convert_whitespace=True):
yield _indent(line) | [
"def",
"_format_subcommand",
"(",
"command",
")",
":",
"yield",
"'.. object:: {}'",
".",
"format",
"(",
"command",
".",
"name",
")",
"# click 7.0 stopped setting short_help by default",
"if",
"CLICK_VERSION",
"<",
"(",
"7",
",",
"0",
")",
":",
"short_help",
"=",
... | Format a sub-command of a `click.Command` or `click.Group`. | [
"Format",
"a",
"sub",
"-",
"command",
"of",
"a",
"click",
".",
"Command",
"or",
"click",
".",
"Group",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L175-L189 | train | 25,479 |
click-contrib/sphinx-click | sphinx_click/ext.py | _filter_commands | def _filter_commands(ctx, commands=None):
"""Return list of used commands."""
lookup = getattr(ctx.command, 'commands', {})
if not lookup and isinstance(ctx.command, click.MultiCommand):
lookup = _get_lazyload_commands(ctx.command)
if commands is None:
return sorted(lookup.values(), key=lambda item: item.name)
names = [name.strip() for name in commands.split(',')]
return [lookup[name] for name in names if name in lookup] | python | def _filter_commands(ctx, commands=None):
"""Return list of used commands."""
lookup = getattr(ctx.command, 'commands', {})
if not lookup and isinstance(ctx.command, click.MultiCommand):
lookup = _get_lazyload_commands(ctx.command)
if commands is None:
return sorted(lookup.values(), key=lambda item: item.name)
names = [name.strip() for name in commands.split(',')]
return [lookup[name] for name in names if name in lookup] | [
"def",
"_filter_commands",
"(",
"ctx",
",",
"commands",
"=",
"None",
")",
":",
"lookup",
"=",
"getattr",
"(",
"ctx",
".",
"command",
",",
"'commands'",
",",
"{",
"}",
")",
"if",
"not",
"lookup",
"and",
"isinstance",
"(",
"ctx",
".",
"command",
",",
"... | Return list of used commands. | [
"Return",
"list",
"of",
"used",
"commands",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L200-L210 | train | 25,480 |
click-contrib/sphinx-click | sphinx_click/ext.py | _format_command | def _format_command(ctx, show_nested, commands=None):
"""Format the output of `click.Command`."""
# the hidden attribute is part of click 7.x only hence use of getattr
if getattr(ctx.command, 'hidden', False):
return
# description
for line in _format_description(ctx):
yield line
yield '.. program:: {}'.format(ctx.command_path)
# usage
for line in _format_usage(ctx):
yield line
# options
lines = list(_format_options(ctx))
if lines:
# we use rubric to provide some separation without exploding the table
# of contents
yield '.. rubric:: Options'
yield ''
for line in lines:
yield line
# arguments
lines = list(_format_arguments(ctx))
if lines:
yield '.. rubric:: Arguments'
yield ''
for line in lines:
yield line
# environment variables
lines = list(_format_envvars(ctx))
if lines:
yield '.. rubric:: Environment variables'
yield ''
for line in lines:
yield line
# if we're nesting commands, we need to do this slightly differently
if show_nested:
return
commands = _filter_commands(ctx, commands)
if commands:
yield '.. rubric:: Commands'
yield ''
for command in commands:
# Don't show hidden subcommands
if CLICK_VERSION >= (7, 0):
if command.hidden:
continue
for line in _format_subcommand(command):
yield line
yield '' | python | def _format_command(ctx, show_nested, commands=None):
"""Format the output of `click.Command`."""
# the hidden attribute is part of click 7.x only hence use of getattr
if getattr(ctx.command, 'hidden', False):
return
# description
for line in _format_description(ctx):
yield line
yield '.. program:: {}'.format(ctx.command_path)
# usage
for line in _format_usage(ctx):
yield line
# options
lines = list(_format_options(ctx))
if lines:
# we use rubric to provide some separation without exploding the table
# of contents
yield '.. rubric:: Options'
yield ''
for line in lines:
yield line
# arguments
lines = list(_format_arguments(ctx))
if lines:
yield '.. rubric:: Arguments'
yield ''
for line in lines:
yield line
# environment variables
lines = list(_format_envvars(ctx))
if lines:
yield '.. rubric:: Environment variables'
yield ''
for line in lines:
yield line
# if we're nesting commands, we need to do this slightly differently
if show_nested:
return
commands = _filter_commands(ctx, commands)
if commands:
yield '.. rubric:: Commands'
yield ''
for command in commands:
# Don't show hidden subcommands
if CLICK_VERSION >= (7, 0):
if command.hidden:
continue
for line in _format_subcommand(command):
yield line
yield '' | [
"def",
"_format_command",
"(",
"ctx",
",",
"show_nested",
",",
"commands",
"=",
"None",
")",
":",
"# the hidden attribute is part of click 7.x only hence use of getattr",
"if",
"getattr",
"(",
"ctx",
".",
"command",
",",
"'hidden'",
",",
"False",
")",
":",
"return",... | Format the output of `click.Command`. | [
"Format",
"the",
"output",
"of",
"click",
".",
"Command",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L213-L281 | train | 25,481 |
click-contrib/sphinx-click | sphinx_click/ext.py | ClickDirective._load_module | def _load_module(self, module_path):
"""Load the module."""
# __import__ will fail on unicode,
# so we ensure module path is a string here.
module_path = str(module_path)
try:
module_name, attr_name = module_path.split(':', 1)
except ValueError: # noqa
raise self.error(
'"{}" is not of format "module:parser"'.format(module_path))
try:
mod = __import__(module_name, globals(), locals(), [attr_name])
except (Exception, SystemExit) as exc: # noqa
err_msg = 'Failed to import "{}" from "{}". '.format(
attr_name, module_name)
if isinstance(exc, SystemExit):
err_msg += 'The module appeared to call sys.exit()'
else:
err_msg += 'The following exception was raised:\n{}'.format(
traceback.format_exc())
raise self.error(err_msg)
if not hasattr(mod, attr_name):
raise self.error('Module "{}" has no attribute "{}"'.format(
module_name, attr_name))
parser = getattr(mod, attr_name)
if not isinstance(parser, click.BaseCommand):
raise self.error('"{}" of type "{}" is not derived from '
'"click.BaseCommand"'.format(
type(parser), module_path))
return parser | python | def _load_module(self, module_path):
"""Load the module."""
# __import__ will fail on unicode,
# so we ensure module path is a string here.
module_path = str(module_path)
try:
module_name, attr_name = module_path.split(':', 1)
except ValueError: # noqa
raise self.error(
'"{}" is not of format "module:parser"'.format(module_path))
try:
mod = __import__(module_name, globals(), locals(), [attr_name])
except (Exception, SystemExit) as exc: # noqa
err_msg = 'Failed to import "{}" from "{}". '.format(
attr_name, module_name)
if isinstance(exc, SystemExit):
err_msg += 'The module appeared to call sys.exit()'
else:
err_msg += 'The following exception was raised:\n{}'.format(
traceback.format_exc())
raise self.error(err_msg)
if not hasattr(mod, attr_name):
raise self.error('Module "{}" has no attribute "{}"'.format(
module_name, attr_name))
parser = getattr(mod, attr_name)
if not isinstance(parser, click.BaseCommand):
raise self.error('"{}" of type "{}" is not derived from '
'"click.BaseCommand"'.format(
type(parser), module_path))
return parser | [
"def",
"_load_module",
"(",
"self",
",",
"module_path",
")",
":",
"# __import__ will fail on unicode,",
"# so we ensure module path is a string here.",
"module_path",
"=",
"str",
"(",
"module_path",
")",
"try",
":",
"module_name",
",",
"attr_name",
"=",
"module_path",
"... | Load the module. | [
"Load",
"the",
"module",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L294-L329 | train | 25,482 |
joferkington/mpldatacursor | mpldatacursor/datacursor.py | DataCursor._show_annotation_box | def _show_annotation_box(self, event):
"""Update an existing box or create an annotation box for an event."""
ax = event.artist.axes
# Get the pre-created annotation box for the axes or create a new one.
if self.display != 'multiple':
annotation = self.annotations[ax]
elif event.mouseevent in self.annotations:
# Avoid creating multiple datacursors for the same click event
# when several artists are selected.
annotation = self.annotations[event.mouseevent]
else:
annotation = self.annotate(ax, **self._annotation_kwargs)
self.annotations[event.mouseevent] = annotation
if self.display == 'single':
# Hide any other annotation boxes...
for ann in self.annotations.values():
ann.set_visible(False)
self.update(event, annotation) | python | def _show_annotation_box(self, event):
"""Update an existing box or create an annotation box for an event."""
ax = event.artist.axes
# Get the pre-created annotation box for the axes or create a new one.
if self.display != 'multiple':
annotation = self.annotations[ax]
elif event.mouseevent in self.annotations:
# Avoid creating multiple datacursors for the same click event
# when several artists are selected.
annotation = self.annotations[event.mouseevent]
else:
annotation = self.annotate(ax, **self._annotation_kwargs)
self.annotations[event.mouseevent] = annotation
if self.display == 'single':
# Hide any other annotation boxes...
for ann in self.annotations.values():
ann.set_visible(False)
self.update(event, annotation) | [
"def",
"_show_annotation_box",
"(",
"self",
",",
"event",
")",
":",
"ax",
"=",
"event",
".",
"artist",
".",
"axes",
"# Get the pre-created annotation box for the axes or create a new one.",
"if",
"self",
".",
"display",
"!=",
"'multiple'",
":",
"annotation",
"=",
"s... | Update an existing box or create an annotation box for an event. | [
"Update",
"an",
"existing",
"box",
"or",
"create",
"an",
"annotation",
"box",
"for",
"an",
"event",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L256-L275 | train | 25,483 |
joferkington/mpldatacursor | mpldatacursor/datacursor.py | DataCursor.event_info | def event_info(self, event):
"""Get a dict of info for the artist selected by "event"."""
def default_func(event):
return {}
registry = {
AxesImage : [pick_info.image_props],
PathCollection : [pick_info.scatter_props, self._contour_info,
pick_info.collection_props],
Line2D : [pick_info.line_props, pick_info.errorbar_props],
LineCollection : [pick_info.collection_props,
self._contour_info,
pick_info.errorbar_props],
PatchCollection : [pick_info.collection_props,
self._contour_info],
PolyCollection : [pick_info.collection_props,
pick_info.scatter_props],
QuadMesh : [pick_info.collection_props],
Rectangle : [pick_info.rectangle_props],
}
x, y = event.mouseevent.xdata, event.mouseevent.ydata
props = dict(x=x, y=y, label=event.artist.get_label(), event=event)
props['ind'] = getattr(event, 'ind', None)
props['point_label'] = self._point_label(event)
funcs = registry.get(type(event.artist), [default_func])
# 3D artist don't share inheritance. Fall back to naming convention.
if '3D' in type(event.artist).__name__:
funcs += [pick_info.three_dim_props]
for func in funcs:
props.update(func(event))
return props | python | def event_info(self, event):
"""Get a dict of info for the artist selected by "event"."""
def default_func(event):
return {}
registry = {
AxesImage : [pick_info.image_props],
PathCollection : [pick_info.scatter_props, self._contour_info,
pick_info.collection_props],
Line2D : [pick_info.line_props, pick_info.errorbar_props],
LineCollection : [pick_info.collection_props,
self._contour_info,
pick_info.errorbar_props],
PatchCollection : [pick_info.collection_props,
self._contour_info],
PolyCollection : [pick_info.collection_props,
pick_info.scatter_props],
QuadMesh : [pick_info.collection_props],
Rectangle : [pick_info.rectangle_props],
}
x, y = event.mouseevent.xdata, event.mouseevent.ydata
props = dict(x=x, y=y, label=event.artist.get_label(), event=event)
props['ind'] = getattr(event, 'ind', None)
props['point_label'] = self._point_label(event)
funcs = registry.get(type(event.artist), [default_func])
# 3D artist don't share inheritance. Fall back to naming convention.
if '3D' in type(event.artist).__name__:
funcs += [pick_info.three_dim_props]
for func in funcs:
props.update(func(event))
return props | [
"def",
"event_info",
"(",
"self",
",",
"event",
")",
":",
"def",
"default_func",
"(",
"event",
")",
":",
"return",
"{",
"}",
"registry",
"=",
"{",
"AxesImage",
":",
"[",
"pick_info",
".",
"image_props",
"]",
",",
"PathCollection",
":",
"[",
"pick_info",
... | Get a dict of info for the artist selected by "event". | [
"Get",
"a",
"dict",
"of",
"info",
"for",
"the",
"artist",
"selected",
"by",
"event",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L277-L310 | train | 25,484 |
joferkington/mpldatacursor | mpldatacursor/datacursor.py | DataCursor._formatter | def _formatter(self, x=None, y=None, z=None, s=None, label=None, **kwargs):
"""
Default formatter function, if no `formatter` kwarg is specified. Takes
information about the pick event as a series of kwargs and returns the
string to be displayed.
"""
def is_date(axis):
fmt = axis.get_major_formatter()
return (isinstance(fmt, mdates.DateFormatter)
or isinstance(fmt, mdates.AutoDateFormatter))
def format_date(num):
if num is not None:
return mdates.num2date(num).strftime(self.date_format)
ax = kwargs['event'].artist.axes
# Display x and y with range-specific formatting
if is_date(ax.xaxis):
x = format_date(x)
else:
limits = ax.get_xlim()
x = self._format_coord(x, limits)
kwargs['xerror'] = self._format_coord(kwargs.get('xerror'), limits)
if is_date(ax.yaxis):
y = format_date(y)
else:
limits = ax.get_ylim()
y = self._format_coord(y, limits)
kwargs['yerror'] = self._format_coord(kwargs.get('yerror'), limits)
output = []
for key, val in zip(['x', 'y', 'z', 's'], [x, y, z, s]):
if val is not None:
try:
output.append(u'{key}: {val:0.3g}'.format(key=key, val=val))
except ValueError:
# X & Y will be strings at this point.
# For masked arrays, etc, "z" and s values may be a string
output.append(u'{key}: {val}'.format(key=key, val=val))
# label may be None or an empty string (for an un-labeled AxesImage)...
# Un-labeled Line2D's will have labels that start with an underscore
if label and not label.startswith('_'):
output.append(u'Label: {}'.format(label))
if kwargs.get(u'point_label', None) is not None:
output.append(u'Point: ' + u', '.join(kwargs['point_label']))
for arg in ['xerror', 'yerror']:
val = kwargs.get(arg, None)
if val is not None:
output.append(u'{}: {}'.format(arg, val))
return u'\n'.join(output) | python | def _formatter(self, x=None, y=None, z=None, s=None, label=None, **kwargs):
"""
Default formatter function, if no `formatter` kwarg is specified. Takes
information about the pick event as a series of kwargs and returns the
string to be displayed.
"""
def is_date(axis):
fmt = axis.get_major_formatter()
return (isinstance(fmt, mdates.DateFormatter)
or isinstance(fmt, mdates.AutoDateFormatter))
def format_date(num):
if num is not None:
return mdates.num2date(num).strftime(self.date_format)
ax = kwargs['event'].artist.axes
# Display x and y with range-specific formatting
if is_date(ax.xaxis):
x = format_date(x)
else:
limits = ax.get_xlim()
x = self._format_coord(x, limits)
kwargs['xerror'] = self._format_coord(kwargs.get('xerror'), limits)
if is_date(ax.yaxis):
y = format_date(y)
else:
limits = ax.get_ylim()
y = self._format_coord(y, limits)
kwargs['yerror'] = self._format_coord(kwargs.get('yerror'), limits)
output = []
for key, val in zip(['x', 'y', 'z', 's'], [x, y, z, s]):
if val is not None:
try:
output.append(u'{key}: {val:0.3g}'.format(key=key, val=val))
except ValueError:
# X & Y will be strings at this point.
# For masked arrays, etc, "z" and s values may be a string
output.append(u'{key}: {val}'.format(key=key, val=val))
# label may be None or an empty string (for an un-labeled AxesImage)...
# Un-labeled Line2D's will have labels that start with an underscore
if label and not label.startswith('_'):
output.append(u'Label: {}'.format(label))
if kwargs.get(u'point_label', None) is not None:
output.append(u'Point: ' + u', '.join(kwargs['point_label']))
for arg in ['xerror', 'yerror']:
val = kwargs.get(arg, None)
if val is not None:
output.append(u'{}: {}'.format(arg, val))
return u'\n'.join(output) | [
"def",
"_formatter",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"z",
"=",
"None",
",",
"s",
"=",
"None",
",",
"label",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"is_date",
"(",
"axis",
")",
":",
"fmt",
"=",
... | Default formatter function, if no `formatter` kwarg is specified. Takes
information about the pick event as a series of kwargs and returns the
string to be displayed. | [
"Default",
"formatter",
"function",
"if",
"no",
"formatter",
"kwarg",
"is",
"specified",
".",
"Takes",
"information",
"about",
"the",
"pick",
"event",
"as",
"a",
"series",
"of",
"kwargs",
"and",
"returns",
"the",
"string",
"to",
"be",
"displayed",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L327-L381 | train | 25,485 |
joferkington/mpldatacursor | mpldatacursor/datacursor.py | DataCursor._format_coord | def _format_coord(self, x, limits):
"""
Handles display-range-specific formatting for the x and y coords.
Parameters
----------
x : number
The number to be formatted
limits : 2-item sequence
The min and max of the current display limits for the axis.
"""
if x is None:
return None
formatter = self._mplformatter
# Trick the formatter into thinking we have an axes
# The 7 tick locations is arbitrary but gives a reasonable detail level
formatter.locs = np.linspace(limits[0], limits[1], 7)
formatter._set_format(*limits)
formatter._set_orderOfMagnitude(abs(np.diff(limits)))
return formatter.pprint_val(x) | python | def _format_coord(self, x, limits):
"""
Handles display-range-specific formatting for the x and y coords.
Parameters
----------
x : number
The number to be formatted
limits : 2-item sequence
The min and max of the current display limits for the axis.
"""
if x is None:
return None
formatter = self._mplformatter
# Trick the formatter into thinking we have an axes
# The 7 tick locations is arbitrary but gives a reasonable detail level
formatter.locs = np.linspace(limits[0], limits[1], 7)
formatter._set_format(*limits)
formatter._set_orderOfMagnitude(abs(np.diff(limits)))
return formatter.pprint_val(x) | [
"def",
"_format_coord",
"(",
"self",
",",
"x",
",",
"limits",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"None",
"formatter",
"=",
"self",
".",
"_mplformatter",
"# Trick the formatter into thinking we have an axes",
"# The 7 tick locations is arbitrary but gives ... | Handles display-range-specific formatting for the x and y coords.
Parameters
----------
x : number
The number to be formatted
limits : 2-item sequence
The min and max of the current display limits for the axis. | [
"Handles",
"display",
"-",
"range",
"-",
"specific",
"formatting",
"for",
"the",
"x",
"and",
"y",
"coords",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L383-L403 | train | 25,486 |
joferkington/mpldatacursor | mpldatacursor/datacursor.py | DataCursor._hide_box | def _hide_box(self, annotation):
"""Remove a specific annotation box."""
annotation.set_visible(False)
if self.display == 'multiple':
annotation.axes.figure.texts.remove(annotation)
# Remove the annotation from self.annotations.
lookup = dict((self.annotations[k], k) for k in self.annotations)
del self.annotations[lookup[annotation]]
annotation.figure.canvas.draw() | python | def _hide_box(self, annotation):
"""Remove a specific annotation box."""
annotation.set_visible(False)
if self.display == 'multiple':
annotation.axes.figure.texts.remove(annotation)
# Remove the annotation from self.annotations.
lookup = dict((self.annotations[k], k) for k in self.annotations)
del self.annotations[lookup[annotation]]
annotation.figure.canvas.draw() | [
"def",
"_hide_box",
"(",
"self",
",",
"annotation",
")",
":",
"annotation",
".",
"set_visible",
"(",
"False",
")",
"if",
"self",
".",
"display",
"==",
"'multiple'",
":",
"annotation",
".",
"axes",
".",
"figure",
".",
"texts",
".",
"remove",
"(",
"annotat... | Remove a specific annotation box. | [
"Remove",
"a",
"specific",
"annotation",
"box",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L487-L497 | train | 25,487 |
joferkington/mpldatacursor | mpldatacursor/datacursor.py | DataCursor.enable | def enable(self):
"""Connects callbacks and makes artists pickable. If the datacursor has
already been enabled, this function has no effect."""
def connect(fig):
if self.hover:
event = 'motion_notify_event'
else:
event = 'button_press_event'
cids = [fig.canvas.mpl_connect(event, self._select)]
# None of this should be necessary. Workaround for a bug in some
# mpl versions
try:
proxy = fig.canvas.callbacks.BoundMethodProxy(self)
fig.canvas.callbacks.callbacks[event][cids[-1]] = proxy
except AttributeError:
# In some versions of mpl, BoundMethodProxy doesn't exist...
# See: https://github.com/joferkington/mpldatacursor/issues/2
pass
return cids
if not getattr(self, '_enabled', False):
self._cids = [(fig, connect(fig)) for fig in self.figures]
self._enabled = True
try:
# Newer versions of MPL use set_pickradius
for artist in self.artists:
artist.set_pickradius(self.tolerance)
except AttributeError:
# Older versions of MPL control pick radius through set_picker
for artist in self.artists:
artist.set_picker(self.tolerance)
return self | python | def enable(self):
"""Connects callbacks and makes artists pickable. If the datacursor has
already been enabled, this function has no effect."""
def connect(fig):
if self.hover:
event = 'motion_notify_event'
else:
event = 'button_press_event'
cids = [fig.canvas.mpl_connect(event, self._select)]
# None of this should be necessary. Workaround for a bug in some
# mpl versions
try:
proxy = fig.canvas.callbacks.BoundMethodProxy(self)
fig.canvas.callbacks.callbacks[event][cids[-1]] = proxy
except AttributeError:
# In some versions of mpl, BoundMethodProxy doesn't exist...
# See: https://github.com/joferkington/mpldatacursor/issues/2
pass
return cids
if not getattr(self, '_enabled', False):
self._cids = [(fig, connect(fig)) for fig in self.figures]
self._enabled = True
try:
# Newer versions of MPL use set_pickradius
for artist in self.artists:
artist.set_pickradius(self.tolerance)
except AttributeError:
# Older versions of MPL control pick radius through set_picker
for artist in self.artists:
artist.set_picker(self.tolerance)
return self | [
"def",
"enable",
"(",
"self",
")",
":",
"def",
"connect",
"(",
"fig",
")",
":",
"if",
"self",
".",
"hover",
":",
"event",
"=",
"'motion_notify_event'",
"else",
":",
"event",
"=",
"'button_press_event'",
"cids",
"=",
"[",
"fig",
".",
"canvas",
".",
"mpl... | Connects callbacks and makes artists pickable. If the datacursor has
already been enabled, this function has no effect. | [
"Connects",
"callbacks",
"and",
"makes",
"artists",
"pickable",
".",
"If",
"the",
"datacursor",
"has",
"already",
"been",
"enabled",
"this",
"function",
"has",
"no",
"effect",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L513-L546 | train | 25,488 |
joferkington/mpldatacursor | mpldatacursor/datacursor.py | DataCursor._increment_index | def _increment_index(self, di=1):
"""
Move the most recently displayed annotation to the next item in the
series, if possible. If ``di`` is -1, move it to the previous item.
"""
if self._last_event is None:
return
if not hasattr(self._last_event, 'ind'):
return
event = self._last_event
xy = pick_info.get_xy(event.artist)
if xy is not None:
x, y = xy
i = (event.ind[0] + di) % len(x)
event.ind = [i]
event.mouseevent.xdata = x[i]
event.mouseevent.ydata = y[i]
self.update(event, self._last_annotation) | python | def _increment_index(self, di=1):
"""
Move the most recently displayed annotation to the next item in the
series, if possible. If ``di`` is -1, move it to the previous item.
"""
if self._last_event is None:
return
if not hasattr(self._last_event, 'ind'):
return
event = self._last_event
xy = pick_info.get_xy(event.artist)
if xy is not None:
x, y = xy
i = (event.ind[0] + di) % len(x)
event.ind = [i]
event.mouseevent.xdata = x[i]
event.mouseevent.ydata = y[i]
self.update(event, self._last_annotation) | [
"def",
"_increment_index",
"(",
"self",
",",
"di",
"=",
"1",
")",
":",
"if",
"self",
".",
"_last_event",
"is",
"None",
":",
"return",
"if",
"not",
"hasattr",
"(",
"self",
".",
"_last_event",
",",
"'ind'",
")",
":",
"return",
"event",
"=",
"self",
"."... | Move the most recently displayed annotation to the next item in the
series, if possible. If ``di`` is -1, move it to the previous item. | [
"Move",
"the",
"most",
"recently",
"displayed",
"annotation",
"to",
"the",
"next",
"item",
"in",
"the",
"series",
"if",
"possible",
".",
"If",
"di",
"is",
"-",
"1",
"move",
"it",
"to",
"the",
"previous",
"item",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L635-L656 | train | 25,489 |
joferkington/mpldatacursor | mpldatacursor/datacursor.py | HighlightingDataCursor.show_highlight | def show_highlight(self, artist):
"""Show or create a highlight for a givent artist."""
# This is a separate method to make subclassing easier.
if artist in self.highlights:
self.highlights[artist].set_visible(True)
else:
self.highlights[artist] = self.create_highlight(artist)
return self.highlights[artist] | python | def show_highlight(self, artist):
"""Show or create a highlight for a givent artist."""
# This is a separate method to make subclassing easier.
if artist in self.highlights:
self.highlights[artist].set_visible(True)
else:
self.highlights[artist] = self.create_highlight(artist)
return self.highlights[artist] | [
"def",
"show_highlight",
"(",
"self",
",",
"artist",
")",
":",
"# This is a separate method to make subclassing easier.",
"if",
"artist",
"in",
"self",
".",
"highlights",
":",
"self",
".",
"highlights",
"[",
"artist",
"]",
".",
"set_visible",
"(",
"True",
")",
"... | Show or create a highlight for a givent artist. | [
"Show",
"or",
"create",
"a",
"highlight",
"for",
"a",
"givent",
"artist",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L755-L762 | train | 25,490 |
joferkington/mpldatacursor | mpldatacursor/datacursor.py | HighlightingDataCursor.create_highlight | def create_highlight(self, artist):
"""Create a new highlight for the given artist."""
highlight = copy.copy(artist)
highlight.set(color=self.highlight_color, mec=self.highlight_color,
lw=self.highlight_width, mew=self.highlight_width)
artist.axes.add_artist(highlight)
return highlight | python | def create_highlight(self, artist):
"""Create a new highlight for the given artist."""
highlight = copy.copy(artist)
highlight.set(color=self.highlight_color, mec=self.highlight_color,
lw=self.highlight_width, mew=self.highlight_width)
artist.axes.add_artist(highlight)
return highlight | [
"def",
"create_highlight",
"(",
"self",
",",
"artist",
")",
":",
"highlight",
"=",
"copy",
".",
"copy",
"(",
"artist",
")",
"highlight",
".",
"set",
"(",
"color",
"=",
"self",
".",
"highlight_color",
",",
"mec",
"=",
"self",
".",
"highlight_color",
",",
... | Create a new highlight for the given artist. | [
"Create",
"a",
"new",
"highlight",
"for",
"the",
"given",
"artist",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/datacursor.py#L764-L770 | train | 25,491 |
joferkington/mpldatacursor | mpldatacursor/pick_info.py | _coords2index | def _coords2index(im, x, y, inverted=False):
"""
Converts data coordinates to index coordinates of the array.
Parameters
-----------
im : An AxesImage instance
The image artist to operation on
x : number
The x-coordinate in data coordinates.
y : number
The y-coordinate in data coordinates.
inverted : bool, optional
If True, convert index to data coordinates instead of data coordinates
to index.
Returns
--------
i, j : Index coordinates of the array associated with the image.
"""
xmin, xmax, ymin, ymax = im.get_extent()
if im.origin == 'upper':
ymin, ymax = ymax, ymin
data_extent = mtransforms.Bbox([[ymin, xmin], [ymax, xmax]])
array_extent = mtransforms.Bbox([[0, 0], im.get_array().shape[:2]])
trans = mtransforms.BboxTransformFrom(data_extent) +\
mtransforms.BboxTransformTo(array_extent)
if inverted:
trans = trans.inverted()
return trans.transform_point([y,x]).astype(int) | python | def _coords2index(im, x, y, inverted=False):
"""
Converts data coordinates to index coordinates of the array.
Parameters
-----------
im : An AxesImage instance
The image artist to operation on
x : number
The x-coordinate in data coordinates.
y : number
The y-coordinate in data coordinates.
inverted : bool, optional
If True, convert index to data coordinates instead of data coordinates
to index.
Returns
--------
i, j : Index coordinates of the array associated with the image.
"""
xmin, xmax, ymin, ymax = im.get_extent()
if im.origin == 'upper':
ymin, ymax = ymax, ymin
data_extent = mtransforms.Bbox([[ymin, xmin], [ymax, xmax]])
array_extent = mtransforms.Bbox([[0, 0], im.get_array().shape[:2]])
trans = mtransforms.BboxTransformFrom(data_extent) +\
mtransforms.BboxTransformTo(array_extent)
if inverted:
trans = trans.inverted()
return trans.transform_point([y,x]).astype(int) | [
"def",
"_coords2index",
"(",
"im",
",",
"x",
",",
"y",
",",
"inverted",
"=",
"False",
")",
":",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"=",
"im",
".",
"get_extent",
"(",
")",
"if",
"im",
".",
"origin",
"==",
"'upper'",
":",
"ymin",
",",
... | Converts data coordinates to index coordinates of the array.
Parameters
-----------
im : An AxesImage instance
The image artist to operation on
x : number
The x-coordinate in data coordinates.
y : number
The y-coordinate in data coordinates.
inverted : bool, optional
If True, convert index to data coordinates instead of data coordinates
to index.
Returns
--------
i, j : Index coordinates of the array associated with the image. | [
"Converts",
"data",
"coordinates",
"to",
"index",
"coordinates",
"of",
"the",
"array",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L28-L59 | train | 25,492 |
joferkington/mpldatacursor | mpldatacursor/pick_info.py | _interleave | def _interleave(a, b):
"""Interleave arrays a and b; b may have multiple columns and must be
shorter by 1.
"""
b = np.column_stack([b]) # Turn b into a column array.
nx, ny = b.shape
c = np.zeros((nx + 1, ny + 1))
c[:, 0] = a
c[:-1, 1:] = b
return c.ravel()[:-(c.shape[1] - 1)] | python | def _interleave(a, b):
"""Interleave arrays a and b; b may have multiple columns and must be
shorter by 1.
"""
b = np.column_stack([b]) # Turn b into a column array.
nx, ny = b.shape
c = np.zeros((nx + 1, ny + 1))
c[:, 0] = a
c[:-1, 1:] = b
return c.ravel()[:-(c.shape[1] - 1)] | [
"def",
"_interleave",
"(",
"a",
",",
"b",
")",
":",
"b",
"=",
"np",
".",
"column_stack",
"(",
"[",
"b",
"]",
")",
"# Turn b into a column array.",
"nx",
",",
"ny",
"=",
"b",
".",
"shape",
"c",
"=",
"np",
".",
"zeros",
"(",
"(",
"nx",
"+",
"1",
... | Interleave arrays a and b; b may have multiple columns and must be
shorter by 1. | [
"Interleave",
"arrays",
"a",
"and",
"b",
";",
"b",
"may",
"have",
"multiple",
"columns",
"and",
"must",
"be",
"shorter",
"by",
"1",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L148-L157 | train | 25,493 |
joferkington/mpldatacursor | mpldatacursor/pick_info.py | three_dim_props | def three_dim_props(event):
"""
Get information for a pick event on a 3D artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`x`: The estimated x-value of the click on the artist
`y`: The estimated y-value of the click on the artist
`z`: The estimated z-value of the click on the artist
Notes
-----
Based on mpl_toolkits.axes3d.Axes3D.format_coord
Many thanks to Ben Root for pointing this out!
"""
ax = event.artist.axes
if ax.M is None:
return {}
xd, yd = event.mouseevent.xdata, event.mouseevent.ydata
p = (xd, yd)
edges = ax.tunit_edges()
ldists = [(mplot3d.proj3d.line2d_seg_dist(p0, p1, p), i) for \
i, (p0, p1) in enumerate(edges)]
ldists.sort()
# nearest edge
edgei = ldists[0][1]
p0, p1 = edges[edgei]
# scale the z value to match
x0, y0, z0 = p0
x1, y1, z1 = p1
d0 = np.hypot(x0-xd, y0-yd)
d1 = np.hypot(x1-xd, y1-yd)
dt = d0+d1
z = d1/dt * z0 + d0/dt * z1
x, y, z = mplot3d.proj3d.inv_transform(xd, yd, z, ax.M)
return dict(x=x, y=y, z=z) | python | def three_dim_props(event):
"""
Get information for a pick event on a 3D artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`x`: The estimated x-value of the click on the artist
`y`: The estimated y-value of the click on the artist
`z`: The estimated z-value of the click on the artist
Notes
-----
Based on mpl_toolkits.axes3d.Axes3D.format_coord
Many thanks to Ben Root for pointing this out!
"""
ax = event.artist.axes
if ax.M is None:
return {}
xd, yd = event.mouseevent.xdata, event.mouseevent.ydata
p = (xd, yd)
edges = ax.tunit_edges()
ldists = [(mplot3d.proj3d.line2d_seg_dist(p0, p1, p), i) for \
i, (p0, p1) in enumerate(edges)]
ldists.sort()
# nearest edge
edgei = ldists[0][1]
p0, p1 = edges[edgei]
# scale the z value to match
x0, y0, z0 = p0
x1, y1, z1 = p1
d0 = np.hypot(x0-xd, y0-yd)
d1 = np.hypot(x1-xd, y1-yd)
dt = d0+d1
z = d1/dt * z0 + d0/dt * z1
x, y, z = mplot3d.proj3d.inv_transform(xd, yd, z, ax.M)
return dict(x=x, y=y, z=z) | [
"def",
"three_dim_props",
"(",
"event",
")",
":",
"ax",
"=",
"event",
".",
"artist",
".",
"axes",
"if",
"ax",
".",
"M",
"is",
"None",
":",
"return",
"{",
"}",
"xd",
",",
"yd",
"=",
"event",
".",
"mouseevent",
".",
"xdata",
",",
"event",
".",
"mou... | Get information for a pick event on a 3D artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`x`: The estimated x-value of the click on the artist
`y`: The estimated y-value of the click on the artist
`z`: The estimated z-value of the click on the artist
Notes
-----
Based on mpl_toolkits.axes3d.Axes3D.format_coord
Many thanks to Ben Root for pointing this out! | [
"Get",
"information",
"for",
"a",
"pick",
"event",
"on",
"a",
"3D",
"artist",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L268-L314 | train | 25,494 |
joferkington/mpldatacursor | mpldatacursor/pick_info.py | rectangle_props | def rectangle_props(event):
"""
Returns the width, height, left, and bottom of a rectangle artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`width` : The width of the rectangle
`height` : The height of the rectangle
`left` : The minimum x-coordinate of the rectangle
`right` : The maximum x-coordinate of the rectangle
`bottom` : The minimum y-coordinate of the rectangle
`top` : The maximum y-coordinate of the rectangle
`xcenter` : The mean x-coordinate of the rectangle
`ycenter` : The mean y-coordinate of the rectangle
`label` : The label for the rectangle or None
"""
artist = event.artist
width, height = artist.get_width(), artist.get_height()
left, bottom = artist.xy
right, top = left + width, bottom + height
xcenter = left + 0.5 * width
ycenter = bottom + 0.5 * height
label = artist.get_label()
if label is None or label.startswith('_nolegend'):
try:
label = artist._mpldatacursor_label
except AttributeError:
label = None
return dict(width=width, height=height, left=left, bottom=bottom,
label=label, right=right, top=top,
xcenter=xcenter, ycenter=ycenter) | python | def rectangle_props(event):
"""
Returns the width, height, left, and bottom of a rectangle artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`width` : The width of the rectangle
`height` : The height of the rectangle
`left` : The minimum x-coordinate of the rectangle
`right` : The maximum x-coordinate of the rectangle
`bottom` : The minimum y-coordinate of the rectangle
`top` : The maximum y-coordinate of the rectangle
`xcenter` : The mean x-coordinate of the rectangle
`ycenter` : The mean y-coordinate of the rectangle
`label` : The label for the rectangle or None
"""
artist = event.artist
width, height = artist.get_width(), artist.get_height()
left, bottom = artist.xy
right, top = left + width, bottom + height
xcenter = left + 0.5 * width
ycenter = bottom + 0.5 * height
label = artist.get_label()
if label is None or label.startswith('_nolegend'):
try:
label = artist._mpldatacursor_label
except AttributeError:
label = None
return dict(width=width, height=height, left=left, bottom=bottom,
label=label, right=right, top=top,
xcenter=xcenter, ycenter=ycenter) | [
"def",
"rectangle_props",
"(",
"event",
")",
":",
"artist",
"=",
"event",
".",
"artist",
"width",
",",
"height",
"=",
"artist",
".",
"get_width",
"(",
")",
",",
"artist",
".",
"get_height",
"(",
")",
"left",
",",
"bottom",
"=",
"artist",
".",
"xy",
"... | Returns the width, height, left, and bottom of a rectangle artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`width` : The width of the rectangle
`height` : The height of the rectangle
`left` : The minimum x-coordinate of the rectangle
`right` : The maximum x-coordinate of the rectangle
`bottom` : The minimum y-coordinate of the rectangle
`top` : The maximum y-coordinate of the rectangle
`xcenter` : The mean x-coordinate of the rectangle
`ycenter` : The mean y-coordinate of the rectangle
`label` : The label for the rectangle or None | [
"Returns",
"the",
"width",
"height",
"left",
"and",
"bottom",
"of",
"a",
"rectangle",
"artist",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L316-L354 | train | 25,495 |
joferkington/mpldatacursor | mpldatacursor/pick_info.py | get_xy | def get_xy(artist):
"""
Attempts to get the x,y data for individual items subitems of the artist.
Returns None if this is not possible.
At present, this only supports Line2D's and basic collections.
"""
xy = None
if hasattr(artist, 'get_offsets'):
xy = artist.get_offsets().T
elif hasattr(artist, 'get_xydata'):
xy = artist.get_xydata().T
return xy | python | def get_xy(artist):
"""
Attempts to get the x,y data for individual items subitems of the artist.
Returns None if this is not possible.
At present, this only supports Line2D's and basic collections.
"""
xy = None
if hasattr(artist, 'get_offsets'):
xy = artist.get_offsets().T
elif hasattr(artist, 'get_xydata'):
xy = artist.get_xydata().T
return xy | [
"def",
"get_xy",
"(",
"artist",
")",
":",
"xy",
"=",
"None",
"if",
"hasattr",
"(",
"artist",
",",
"'get_offsets'",
")",
":",
"xy",
"=",
"artist",
".",
"get_offsets",
"(",
")",
".",
"T",
"elif",
"hasattr",
"(",
"artist",
",",
"'get_xydata'",
")",
":",... | Attempts to get the x,y data for individual items subitems of the artist.
Returns None if this is not possible.
At present, this only supports Line2D's and basic collections. | [
"Attempts",
"to",
"get",
"the",
"x",
"y",
"data",
"for",
"individual",
"items",
"subitems",
"of",
"the",
"artist",
".",
"Returns",
"None",
"if",
"this",
"is",
"not",
"possible",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L356-L370 | train | 25,496 |
joferkington/mpldatacursor | mpldatacursor/convenience.py | datacursor | def datacursor(artists=None, axes=None, **kwargs):
"""
Create an interactive data cursor for the specified artists or specified
axes. The data cursor displays information about a selected artist in a
"popup" annotation box.
If a specific sequence of artists is given, only the specified artists will
be interactively selectable. Otherwise, all manually-plotted artists in
*axes* will be used (*axes* defaults to all axes in all figures).
Parameters
-----------
artists : a matplotlib artist or sequence of artists, optional
The artists to make selectable and display information for. If this is
not specified, then all manually plotted artists in `axes` will be
used.
axes : a matplotlib axes of sequence of axes, optional
The axes to selected artists from if a sequence of artists is not
specified. If `axes` is not specified, then all available axes in all
figures will be used.
tolerance : number, optional
The radius (in points) that the mouse click must be within to select
the artist. Default: 5 points.
formatter : callable, optional
A function that accepts arbitrary kwargs and returns a string that will
be displayed with annotate. Often, it is convienent to pass in the
format method of a template string, e.g.
``formatter="{label}".format``.
Keyword arguments passed in to the `formatter` function:
`x`, `y` : floats
The x and y data coordinates of the clicked point
`event` : a matplotlib ``PickEvent``
The pick event that was fired (note that the selected
artist can be accessed through ``event.artist``).
`label` : string or None
The legend label of the selected artist.
`ind` : list of ints or None
If the artist has "subitems" (e.g. points in a scatter or
line plot), this will be a list of the item(s) that were
clicked on. If the artist does not have "subitems", this
will be None. Note that this is always a list, even when
a single item is selected.
Some selected artists may supply additional keyword arguments that
are not always present, for example:
`z` : number
The "z" (usually color or array) value, if present. For an
``AxesImage`` (as created by ``imshow``), this will be the
uninterpolated array value at the point clicked. For a
``PathCollection`` (as created by ``scatter``) this will be the
"c" value if an array was passed to "c".
`i`, `j` : ints
The row, column indicies of the selected point for an
``AxesImage`` (as created by ``imshow``)
`s` : number
The size of the selected item in a ``PathCollection`` if a size
array is specified.
`c` : number
The array value displayed as color for a ``PathCollection``
if a "c" array is specified (identical to "z").
`point_label` : list
If `point_labels` is given when the data cursor is initialized
and the artist has "subitems", this will be a list of the items
of `point_labels` that correspond to the selected artists.
Note that this is always a list, even when a single artist is
selected.
`width`, `height`, `top`, `bottom` : numbers
The parameters for ``Rectangle`` artists (e.g. bar plots).
point_labels : sequence or dict, optional
For artists with "subitems" (e.g. Line2D's), the item(s) of
`point_labels` corresponding to the selected "subitems" of the artist
will be passed into the formatter function as the "point_label" kwarg.
If a single sequence is given, it will be used for all artists with
"subitems". Alternatively, a dict of artist:sequence pairs may be given
to match an artist to the correct series of point labels.
display : {"one-per-axes", "single", "multiple"}, optional
Controls whether more than one annotation box will be shown.
Default: "one-per-axes"
draggable : boolean, optional
Controls whether or not the annotation box will be interactively
draggable to a new location after being displayed. Defaults to False.
hover : boolean, optional
If True, the datacursor will "pop up" when the mouse hovers over an
artist. Defaults to False. Enabling hover also sets
`display="single"` and `draggable=False`.
props_override : function, optional
If specified, this function customizes the parameters passed into the
formatter function and the x, y location that the datacursor "pop up"
"points" to. This is often useful to make the annotation "point" to a
specific side or corner of an artist, regardless of the position
clicked. The function is passed the same kwargs as the `formatter`
function and is expected to return a dict with at least the keys "x"
and "y" (and probably several others).
Expected call signature: `props_dict = props_override(**kwargs)`
keybindings : boolean or dict, optional
By default, the keys "d" and "t" will be bound to deleting/hiding all
annotation boxes and toggling interactivity for datacursors,
respectively. If keybindings is False, the ability to hide/toggle
datacursors interactively will be disabled. Alternatively, a dict of
the form {'hide':'somekey', 'toggle':'somekey'} may specified to
customize the keyboard shortcuts.
date_format : string, optional
The strftime-style formatting string for dates. Used only if the x or y
axes have been set to display dates. Defaults to "%x %X".
display_button: int, optional
The mouse button that will triggers displaying an annotation box.
Defaults to 1, for left-clicking. (Common options are 1:left-click,
2:middle-click, 3:right-click)
hide_button: int or None, optional
The mouse button that triggers hiding the selected annotation box.
Defaults to 3, for right-clicking. (Common options are 1:left-click,
2:middle-click, 3:right-click, None:hiding disabled)
keep_inside : boolean, optional
Whether or not to adjust the x,y offset to keep the text box inside the
figure. This option has no effect on draggable datacursors. Defaults to
True. Note: Currently disabled on OSX and NbAgg/notebook backends.
**kwargs : additional keyword arguments, optional
Additional keyword arguments are passed on to annotate.
Returns
-------
dc : A ``mpldatacursor.DataCursor`` instance
"""
def plotted_artists(ax):
artists = (ax.lines + ax.patches + ax.collections
+ ax.images + ax.containers)
return artists
# If no axes are specified, get all axes.
if axes is None:
managers = pylab_helpers.Gcf.get_all_fig_managers()
figs = [manager.canvas.figure for manager in managers]
axes = [ax for fig in figs for ax in fig.axes]
if not cbook.iterable(axes):
axes = [axes]
# If no artists are specified, get all manually plotted artists in all of
# the specified axes.
if artists is None:
artists = [artist for ax in axes for artist in plotted_artists(ax)]
return DataCursor(artists, **kwargs) | python | def datacursor(artists=None, axes=None, **kwargs):
"""
Create an interactive data cursor for the specified artists or specified
axes. The data cursor displays information about a selected artist in a
"popup" annotation box.
If a specific sequence of artists is given, only the specified artists will
be interactively selectable. Otherwise, all manually-plotted artists in
*axes* will be used (*axes* defaults to all axes in all figures).
Parameters
-----------
artists : a matplotlib artist or sequence of artists, optional
The artists to make selectable and display information for. If this is
not specified, then all manually plotted artists in `axes` will be
used.
axes : a matplotlib axes of sequence of axes, optional
The axes to selected artists from if a sequence of artists is not
specified. If `axes` is not specified, then all available axes in all
figures will be used.
tolerance : number, optional
The radius (in points) that the mouse click must be within to select
the artist. Default: 5 points.
formatter : callable, optional
A function that accepts arbitrary kwargs and returns a string that will
be displayed with annotate. Often, it is convienent to pass in the
format method of a template string, e.g.
``formatter="{label}".format``.
Keyword arguments passed in to the `formatter` function:
`x`, `y` : floats
The x and y data coordinates of the clicked point
`event` : a matplotlib ``PickEvent``
The pick event that was fired (note that the selected
artist can be accessed through ``event.artist``).
`label` : string or None
The legend label of the selected artist.
`ind` : list of ints or None
If the artist has "subitems" (e.g. points in a scatter or
line plot), this will be a list of the item(s) that were
clicked on. If the artist does not have "subitems", this
will be None. Note that this is always a list, even when
a single item is selected.
Some selected artists may supply additional keyword arguments that
are not always present, for example:
`z` : number
The "z" (usually color or array) value, if present. For an
``AxesImage`` (as created by ``imshow``), this will be the
uninterpolated array value at the point clicked. For a
``PathCollection`` (as created by ``scatter``) this will be the
"c" value if an array was passed to "c".
`i`, `j` : ints
The row, column indicies of the selected point for an
``AxesImage`` (as created by ``imshow``)
`s` : number
The size of the selected item in a ``PathCollection`` if a size
array is specified.
`c` : number
The array value displayed as color for a ``PathCollection``
if a "c" array is specified (identical to "z").
`point_label` : list
If `point_labels` is given when the data cursor is initialized
and the artist has "subitems", this will be a list of the items
of `point_labels` that correspond to the selected artists.
Note that this is always a list, even when a single artist is
selected.
`width`, `height`, `top`, `bottom` : numbers
The parameters for ``Rectangle`` artists (e.g. bar plots).
point_labels : sequence or dict, optional
For artists with "subitems" (e.g. Line2D's), the item(s) of
`point_labels` corresponding to the selected "subitems" of the artist
will be passed into the formatter function as the "point_label" kwarg.
If a single sequence is given, it will be used for all artists with
"subitems". Alternatively, a dict of artist:sequence pairs may be given
to match an artist to the correct series of point labels.
display : {"one-per-axes", "single", "multiple"}, optional
Controls whether more than one annotation box will be shown.
Default: "one-per-axes"
draggable : boolean, optional
Controls whether or not the annotation box will be interactively
draggable to a new location after being displayed. Defaults to False.
hover : boolean, optional
If True, the datacursor will "pop up" when the mouse hovers over an
artist. Defaults to False. Enabling hover also sets
`display="single"` and `draggable=False`.
props_override : function, optional
If specified, this function customizes the parameters passed into the
formatter function and the x, y location that the datacursor "pop up"
"points" to. This is often useful to make the annotation "point" to a
specific side or corner of an artist, regardless of the position
clicked. The function is passed the same kwargs as the `formatter`
function and is expected to return a dict with at least the keys "x"
and "y" (and probably several others).
Expected call signature: `props_dict = props_override(**kwargs)`
keybindings : boolean or dict, optional
By default, the keys "d" and "t" will be bound to deleting/hiding all
annotation boxes and toggling interactivity for datacursors,
respectively. If keybindings is False, the ability to hide/toggle
datacursors interactively will be disabled. Alternatively, a dict of
the form {'hide':'somekey', 'toggle':'somekey'} may specified to
customize the keyboard shortcuts.
date_format : string, optional
The strftime-style formatting string for dates. Used only if the x or y
axes have been set to display dates. Defaults to "%x %X".
display_button: int, optional
The mouse button that will triggers displaying an annotation box.
Defaults to 1, for left-clicking. (Common options are 1:left-click,
2:middle-click, 3:right-click)
hide_button: int or None, optional
The mouse button that triggers hiding the selected annotation box.
Defaults to 3, for right-clicking. (Common options are 1:left-click,
2:middle-click, 3:right-click, None:hiding disabled)
keep_inside : boolean, optional
Whether or not to adjust the x,y offset to keep the text box inside the
figure. This option has no effect on draggable datacursors. Defaults to
True. Note: Currently disabled on OSX and NbAgg/notebook backends.
**kwargs : additional keyword arguments, optional
Additional keyword arguments are passed on to annotate.
Returns
-------
dc : A ``mpldatacursor.DataCursor`` instance
"""
def plotted_artists(ax):
artists = (ax.lines + ax.patches + ax.collections
+ ax.images + ax.containers)
return artists
# If no axes are specified, get all axes.
if axes is None:
managers = pylab_helpers.Gcf.get_all_fig_managers()
figs = [manager.canvas.figure for manager in managers]
axes = [ax for fig in figs for ax in fig.axes]
if not cbook.iterable(axes):
axes = [axes]
# If no artists are specified, get all manually plotted artists in all of
# the specified axes.
if artists is None:
artists = [artist for ax in axes for artist in plotted_artists(ax)]
return DataCursor(artists, **kwargs) | [
"def",
"datacursor",
"(",
"artists",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"plotted_artists",
"(",
"ax",
")",
":",
"artists",
"=",
"(",
"ax",
".",
"lines",
"+",
"ax",
".",
"patches",
"+",
"ax",
".",
"col... | Create an interactive data cursor for the specified artists or specified
axes. The data cursor displays information about a selected artist in a
"popup" annotation box.
If a specific sequence of artists is given, only the specified artists will
be interactively selectable. Otherwise, all manually-plotted artists in
*axes* will be used (*axes* defaults to all axes in all figures).
Parameters
-----------
artists : a matplotlib artist or sequence of artists, optional
The artists to make selectable and display information for. If this is
not specified, then all manually plotted artists in `axes` will be
used.
axes : a matplotlib axes of sequence of axes, optional
The axes to selected artists from if a sequence of artists is not
specified. If `axes` is not specified, then all available axes in all
figures will be used.
tolerance : number, optional
The radius (in points) that the mouse click must be within to select
the artist. Default: 5 points.
formatter : callable, optional
A function that accepts arbitrary kwargs and returns a string that will
be displayed with annotate. Often, it is convienent to pass in the
format method of a template string, e.g.
``formatter="{label}".format``.
Keyword arguments passed in to the `formatter` function:
`x`, `y` : floats
The x and y data coordinates of the clicked point
`event` : a matplotlib ``PickEvent``
The pick event that was fired (note that the selected
artist can be accessed through ``event.artist``).
`label` : string or None
The legend label of the selected artist.
`ind` : list of ints or None
If the artist has "subitems" (e.g. points in a scatter or
line plot), this will be a list of the item(s) that were
clicked on. If the artist does not have "subitems", this
will be None. Note that this is always a list, even when
a single item is selected.
Some selected artists may supply additional keyword arguments that
are not always present, for example:
`z` : number
The "z" (usually color or array) value, if present. For an
``AxesImage`` (as created by ``imshow``), this will be the
uninterpolated array value at the point clicked. For a
``PathCollection`` (as created by ``scatter``) this will be the
"c" value if an array was passed to "c".
`i`, `j` : ints
The row, column indicies of the selected point for an
``AxesImage`` (as created by ``imshow``)
`s` : number
The size of the selected item in a ``PathCollection`` if a size
array is specified.
`c` : number
The array value displayed as color for a ``PathCollection``
if a "c" array is specified (identical to "z").
`point_label` : list
If `point_labels` is given when the data cursor is initialized
and the artist has "subitems", this will be a list of the items
of `point_labels` that correspond to the selected artists.
Note that this is always a list, even when a single artist is
selected.
`width`, `height`, `top`, `bottom` : numbers
The parameters for ``Rectangle`` artists (e.g. bar plots).
point_labels : sequence or dict, optional
For artists with "subitems" (e.g. Line2D's), the item(s) of
`point_labels` corresponding to the selected "subitems" of the artist
will be passed into the formatter function as the "point_label" kwarg.
If a single sequence is given, it will be used for all artists with
"subitems". Alternatively, a dict of artist:sequence pairs may be given
to match an artist to the correct series of point labels.
display : {"one-per-axes", "single", "multiple"}, optional
Controls whether more than one annotation box will be shown.
Default: "one-per-axes"
draggable : boolean, optional
Controls whether or not the annotation box will be interactively
draggable to a new location after being displayed. Defaults to False.
hover : boolean, optional
If True, the datacursor will "pop up" when the mouse hovers over an
artist. Defaults to False. Enabling hover also sets
`display="single"` and `draggable=False`.
props_override : function, optional
If specified, this function customizes the parameters passed into the
formatter function and the x, y location that the datacursor "pop up"
"points" to. This is often useful to make the annotation "point" to a
specific side or corner of an artist, regardless of the position
clicked. The function is passed the same kwargs as the `formatter`
function and is expected to return a dict with at least the keys "x"
and "y" (and probably several others).
Expected call signature: `props_dict = props_override(**kwargs)`
keybindings : boolean or dict, optional
By default, the keys "d" and "t" will be bound to deleting/hiding all
annotation boxes and toggling interactivity for datacursors,
respectively. If keybindings is False, the ability to hide/toggle
datacursors interactively will be disabled. Alternatively, a dict of
the form {'hide':'somekey', 'toggle':'somekey'} may specified to
customize the keyboard shortcuts.
date_format : string, optional
The strftime-style formatting string for dates. Used only if the x or y
axes have been set to display dates. Defaults to "%x %X".
display_button: int, optional
The mouse button that will triggers displaying an annotation box.
Defaults to 1, for left-clicking. (Common options are 1:left-click,
2:middle-click, 3:right-click)
hide_button: int or None, optional
The mouse button that triggers hiding the selected annotation box.
Defaults to 3, for right-clicking. (Common options are 1:left-click,
2:middle-click, 3:right-click, None:hiding disabled)
keep_inside : boolean, optional
Whether or not to adjust the x,y offset to keep the text box inside the
figure. This option has no effect on draggable datacursors. Defaults to
True. Note: Currently disabled on OSX and NbAgg/notebook backends.
**kwargs : additional keyword arguments, optional
Additional keyword arguments are passed on to annotate.
Returns
-------
dc : A ``mpldatacursor.DataCursor`` instance | [
"Create",
"an",
"interactive",
"data",
"cursor",
"for",
"the",
"specified",
"artists",
"or",
"specified",
"axes",
".",
"The",
"data",
"cursor",
"displays",
"information",
"about",
"a",
"selected",
"artist",
"in",
"a",
"popup",
"annotation",
"box",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/convenience.py#L27-L168 | train | 25,497 |
ChristianKuehnel/btlewrap | btlewrap/pygatt.py | wrap_exception | def wrap_exception(func: Callable) -> Callable:
"""Decorator to wrap pygatt exceptions into BluetoothBackendException."""
try:
# only do the wrapping if pygatt is installed.
# otherwise it's pointless anyway
from pygatt.backends.bgapi.exceptions import BGAPIError
from pygatt.exceptions import NotConnectedError
except ImportError:
return func
def _func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except BGAPIError as exception:
raise BluetoothBackendException() from exception
except NotConnectedError as exception:
raise BluetoothBackendException() from exception
return _func_wrapper | python | def wrap_exception(func: Callable) -> Callable:
"""Decorator to wrap pygatt exceptions into BluetoothBackendException."""
try:
# only do the wrapping if pygatt is installed.
# otherwise it's pointless anyway
from pygatt.backends.bgapi.exceptions import BGAPIError
from pygatt.exceptions import NotConnectedError
except ImportError:
return func
def _func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except BGAPIError as exception:
raise BluetoothBackendException() from exception
except NotConnectedError as exception:
raise BluetoothBackendException() from exception
return _func_wrapper | [
"def",
"wrap_exception",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"try",
":",
"# only do the wrapping if pygatt is installed.",
"# otherwise it's pointless anyway",
"from",
"pygatt",
".",
"backends",
".",
"bgapi",
".",
"exceptions",
"import",
"BGAPIErro... | Decorator to wrap pygatt exceptions into BluetoothBackendException. | [
"Decorator",
"to",
"wrap",
"pygatt",
"exceptions",
"into",
"BluetoothBackendException",
"."
] | 1b7aec934529dcf03f5ecdccd0b09c25c389974f | https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/pygatt.py#L9-L27 | train | 25,498 |
ChristianKuehnel/btlewrap | btlewrap/pygatt.py | PygattBackend.write_handle | def write_handle(self, handle: int, value: bytes):
"""Write a handle to the device."""
if not self.is_connected():
raise BluetoothBackendException('Not connected to device!')
self._device.char_write_handle(handle, value, True)
return True | python | def write_handle(self, handle: int, value: bytes):
"""Write a handle to the device."""
if not self.is_connected():
raise BluetoothBackendException('Not connected to device!')
self._device.char_write_handle(handle, value, True)
return True | [
"def",
"write_handle",
"(",
"self",
",",
"handle",
":",
"int",
",",
"value",
":",
"bytes",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
":",
"raise",
"BluetoothBackendException",
"(",
"'Not connected to device!'",
")",
"self",
".",
"_device"... | Write a handle to the device. | [
"Write",
"a",
"handle",
"to",
"the",
"device",
"."
] | 1b7aec934529dcf03f5ecdccd0b09c25c389974f | https://github.com/ChristianKuehnel/btlewrap/blob/1b7aec934529dcf03f5ecdccd0b09c25c389974f/btlewrap/pygatt.py#L81-L86 | train | 25,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.