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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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).... | 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).... | [
"def",
"check_int",
"(",
"val",
")",
":",
"r",
"if",
"not",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"float",
",",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid input type.'",
")",
"if",
... | 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
... | [
"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 |
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(dt... | 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(dt... | [
"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 |
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.n... | 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.n... | [
"def",
"positive",
"(",
"data",
")",
":",
"r",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"int",
",",
"float",
",",
"list",
",",
"tuple",
",",
"np",
".",
"ndarray",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Invalid data type, input must be `int`... | 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 p... | [
"r",
"Positivity",
"operator"
] | 019b189cb897cbb4d210c44a100daaa08468830c | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/signal/positivity.py#L15-L78 | train |
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 |
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 |
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:
... | 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:
... | [
"def",
"to_html",
"(",
"self",
",",
"show_mean",
"=",
"None",
",",
"sortable",
"=",
"None",
",",
"colorize",
"=",
"True",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"show_mean",
"is",
"None",
":",
"show_mean",
"=",
"self",
".",
"show_mean... | 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 |
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 |
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 |
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 == Di... | 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 == Di... | [
"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 |
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 sk... | 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 sk... | [
"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 |
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 de... | 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 de... | [
"def",
"method_cache",
"(",
"by",
"=",
"'value'",
",",
"method",
"=",
"'run'",
")",
":",
"def",
"decorate_",
"(",
"func",
")",
":",
"def",
"decorate",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"model",
"=",
"args",
"[",
"0",
"]",
"assert",
... | 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 |
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:
... | 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:
... | [
"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 |
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... | 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... | [
"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 |
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:
impor... | 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:
impor... | [
"def",
"fix_display",
"(",
"self",
")",
":",
"try",
":",
"tkinter",
".",
"Tk",
"(",
")",
"except",
"(",
"tkinter",
".",
"TclError",
",",
"NameError",
")",
":",
"try",
":",
"import",
"matplotlib",
"as",
"mpl",
"except",
"ImportError",
":",
"pass",
"else... | 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 |
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 |
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 = Exe... | 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 = Exe... | [
"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 |
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 |
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(nam... | 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(nam... | [
"def",
"convert_notebook",
"(",
"self",
",",
"name",
")",
":",
"exporter",
"=",
"nbconvert",
".",
"exporters",
".",
"python",
".",
"PythonExporter",
"(",
")",
"relative_path",
"=",
"self",
".",
"convert_path",
"(",
"name",
")",
"file_path",
"=",
"self",
".... | 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 |
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",
")",
"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 |
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)
... | 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)
... | [
"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 |
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 |
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 = [... | 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 = [... | [
"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 |
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 = u... | 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 = u... | [
"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 |
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 |
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 |
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:
... | 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:
... | [
"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 |
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', '').
... | 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', '').
... | [
"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 |
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, matc... | 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, matc... | [
"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 |
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 .... | 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 .... | [
"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 |
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()
... | 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()
... | [
"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 |
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 = c... | 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 = c... | [
"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 |
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_H... | 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_H... | [
"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 |
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')
... | 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')
... | [
"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 |
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_n... | 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_n... | [
"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 |
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('mis... | 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('mis... | [
"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 |
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.pa... | 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.pa... | [
"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 |
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... | 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... | [
"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 |
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 |
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:
sy... | 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:
sy... | [
"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 |
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:
... | 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:
... | [
"def",
"get_repo",
"(",
"self",
",",
"cached",
"=",
"True",
")",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"self",
".",
"__module__",
"]",
"if",
"hasattr",
"(",
"self",
".",
"__class__",
",",
"'_repo'",
")",
"and",
"cached",
":",
"repo",
"=",
... | 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 |
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 = ... | 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 = ... | [
"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 |
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.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.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 |
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 |
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_u... | 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_u... | [
"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 |
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 |
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...
... | 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...
... | [
"def",
"compute",
"(",
"cls",
",",
"observation",
",",
"prediction",
")",
":",
"assert",
"isinstance",
"(",
"observation",
",",
"dict",
")",
"try",
":",
"p_value",
"=",
"prediction",
"[",
"'mean'",
"]",
"except",
"(",
"TypeError",
",",
"KeyError",
",",
"... | 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 |
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 |
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 =... | 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 =... | [
"def",
"compute",
"(",
"cls",
",",
"observation",
",",
"prediction",
")",
":",
"assert",
"isinstance",
"(",
"observation",
",",
"dict",
")",
"assert",
"isinstance",
"(",
"prediction",
",",
"dict",
")",
"p_mean",
"=",
"prediction",
"[",
"'mean'",
"]",
"p_st... | 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 |
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(observa... | 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(observa... | [
"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 |
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",
")",
":",
"value",
"=",
"(",
"(",
"observation",
"-",
"prediction",
")",
"**",
"2",
")",
".",
"sum",
"(",
")",
"score",
"=",
"FloatScore",
"(",
"value",
")",
"return",
"score"
] | 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 |
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 |
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.it... | 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.it... | [
"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 |
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)
... | 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)
... | [
"def",
"init_backend",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"model",
".",
"attrs",
"=",
"{",
"}",
"self",
".",
"use_memory_cache",
"=",
"kwargs",
".",
"get",
"(",
"'use_memory_cache'",
",",
"True",
")",
"if",
"se... | Initialize the backend. | [
"Initialize",
"the",
"backend",
"."
] | 41b2e38c45c0776727ab1f281a572b65be19cea1 | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/sciunit/models/backends.py#L33-L44 | train |
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.mkdtem... | 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.mkdtem... | [
"def",
"init_disk_cache",
"(",
"self",
")",
":",
"try",
":",
"path",
"=",
"self",
".",
"disk_cache_location",
"os",
".",
"remove",
"(",
"path",
")",
"except",
"Exception",
":",
"pass",
"self",
".",
"disk_cache_location",
"=",
"os",
".",
"path",
".",
"joi... | 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 |
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 |
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... | 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... | [
"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 |
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 |
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... | 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... | [
"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 |
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
... | 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
... | [
"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 |
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 |
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)
... | 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)
... | [
"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 |
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 i... | 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 i... | [
"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 |
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 |
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)
... | 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)
... | [
"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 |
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]... | 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]... | [
"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 |
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 |
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:
... | 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:
... | [
"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 |
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... | 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... | [
"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 |
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... | 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... | [
"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",
"not",
... | 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 ... | [
"Merge",
"options",
"with",
"their",
"corresponding",
"arguments",
"."
] | 4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75 | https://github.com/Ch00k/ffmpy/blob/4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75/ffmpy.py#L171-L200 | train |
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... | 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... | [
"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... | [
"Execute",
"FFmpeg",
"command",
"line",
"."
] | 4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75 | https://github.com/Ch00k/ffmpy/blob/4ed3ab7ce1c1c2e7181c03278b2311fd407cfc75/ffmpy.py#L62-L107 | train |
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 |
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-... | 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-... | [
"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 argument... | [
"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 |
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:
ret... | 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:
ret... | [
"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 |
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(li... | 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(li... | [
"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 |
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:
... | 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:
... | [
"def",
"_format_options",
"(",
"ctx",
")",
":",
"params",
"=",
"[",
"x",
"for",
"x",
"in",
"ctx",
".",
"command",
".",
"params",
"if",
"isinstance",
"(",
"x",
",",
"click",
".",
"Option",
")",
"and",
"not",
"getattr",
"(",
"x",
",",
"'hidden'",
","... | 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 |
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 |
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 |
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 ... | 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 ... | [
"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 |
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_na... | 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_na... | [
"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 |
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_... | 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_... | [
"def",
"_format_subcommand",
"(",
"command",
")",
":",
"yield",
"'.. object:: {}'",
".",
"format",
"(",
"command",
".",
"name",
")",
"if",
"CLICK_VERSION",
"<",
"(",
"7",
",",
"0",
")",
":",
"short_help",
"=",
"command",
".",
"short_help",
"else",
":",
"... | 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 |
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... | 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... | [
"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 |
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
... | 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
... | [
"def",
"_format_command",
"(",
"ctx",
",",
"show_nested",
",",
"commands",
"=",
"None",
")",
":",
"if",
"getattr",
"(",
"ctx",
".",
"command",
",",
"'hidden'",
",",
"False",
")",
":",
"return",
"for",
"line",
"in",
"_format_description",
"(",
"ctx",
")",... | 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 |
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
... | 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
... | [
"def",
"_load_module",
"(",
"self",
",",
"module_path",
")",
":",
"module_path",
"=",
"str",
"(",
"module_path",
")",
"try",
":",
"module_name",
",",
"attr_name",
"=",
"module_path",
".",
"split",
"(",
"':'",
",",
"1",
")",
"except",
"ValueError",
":",
"... | Load the module. | [
"Load",
"the",
"module",
"."
] | ec76d15697ec80e51486a6e3daa0aec60b04870f | https://github.com/click-contrib/sphinx-click/blob/ec76d15697ec80e51486a6e3daa0aec60b04870f/sphinx_click/ext.py#L294-L329 | train |
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]
... | 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]
... | [
"def",
"_show_annotation_box",
"(",
"self",
",",
"event",
")",
":",
"ax",
"=",
"event",
".",
"artist",
".",
"axes",
"if",
"self",
".",
"display",
"!=",
"'multiple'",
":",
"annotation",
"=",
"self",
".",
"annotations",
"[",
"ax",
"]",
"elif",
"event",
"... | 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 |
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,
... | 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,
... | [
"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 |
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):
... | 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):
... | [
"def",
"_formatter",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"z",
"=",
"None",
",",
"s",
"=",
"None",
",",
"label",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"def",
"is_date",
"(",
"axis",
")",
":",
"fmt",
"=",
"axis... | 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 |
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 ax... | 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 ax... | [
"def",
"_format_coord",
"(",
"self",
",",
"x",
",",
"limits",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"None",
"formatter",
"=",
"self",
".",
"_mplformatter",
"formatter",
".",
"locs",
"=",
"np",
".",
"linspace",
"(",
"limits",
"[",
"0",
"]"... | 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 |
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.annotation... | 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.annotation... | [
"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 |
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... | 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... | [
"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 |
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'):
... | 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'):
... | [
"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 |
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_high... | 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_high... | [
"def",
"show_highlight",
"(",
"self",
",",
"artist",
")",
":",
"if",
"artist",
"in",
"self",
".",
"highlights",
":",
"self",
".",
"highlights",
"[",
"artist",
"]",
".",
"set_visible",
"(",
"True",
")",
"else",
":",
"self",
".",
"highlights",
"[",
"arti... | 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 |
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(highlig... | 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(highlig... | [
"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 |
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-coordina... | 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-coordina... | [
"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
... | [
"Converts",
"data",
"coordinates",
"to",
"index",
"coordinates",
"of",
"the",
"array",
"."
] | 7dabc589ed02c35ac5d89de5931f91e0323aa795 | https://github.com/joferkington/mpldatacursor/blob/7dabc589ed02c35ac5d89de5931f91e0323aa795/mpldatacursor/pick_info.py#L28-L59 | train |
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",
"]",
")",
"nx",
",",
"ny",
"=",
"b",
".",
"shape",
"c",
"=",
"np",
".",
"zeros",
"(",
"(",
"nx",
"+",
"1",
",",
"ny",
"+",
"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 |
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-valu... | 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-valu... | [
"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`... | [
"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 |
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... | 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... | [
"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 mini... | [
"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 |
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
el... | 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
el... | [
"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 |
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... | 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... | [
"def",
"datacursor",
"(",
"artists",
"=",
"None",
",",
"axes",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"def",
"plotted_artists",
"(",
"ax",
")",
":",
"artists",
"=",
"(",
"ax",
".",
"lines",
"+",
"ax",
".",
"patches",
"+",
"ax",
".",
"collectio... | 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-plot... | [
"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 |
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.exce... | 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.exce... | [
"def",
"wrap_exception",
"(",
"func",
":",
"Callable",
")",
"->",
"Callable",
":",
"try",
":",
"from",
"pygatt",
".",
"backends",
".",
"bgapi",
".",
"exceptions",
"import",
"BGAPIError",
"from",
"pygatt",
".",
"exceptions",
"import",
"NotConnectedError",
"exce... | 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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.