Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
as_market_time
(year, month, day, hour=0, minute=0, second=0)
Creates a timestamp in market time.
Creates a timestamp in market time.
def as_market_time(year, month, day, hour=0, minute=0, second=0): """Creates a timestamp in market time.""" market_time = datetime(year, month, day, hour, minute, second) return MARKET_TIMEZONE.localize(market_time)
[ "def", "as_market_time", "(", "year", ",", "month", ",", "day", ",", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ")", ":", "market_time", "=", "datetime", "(", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ...
[ 19, 0 ]
[ 23, 48 ]
python
en
['en', 'en', 'en']
True
GetIncludedBuildFiles
(build_file_path, aux_data, included=None)
Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merg...
Return a list of all build files included into build_file_path.
def GetIncludedBuildFiles(build_file_path, aux_data, included=None): """Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were incl...
[ "def", "GetIncludedBuildFiles", "(", "build_file_path", ",", "aux_data", ",", "included", "=", "None", ")", ":", "if", "included", "==", "None", ":", "included", "=", "[", "]", "if", "build_file_path", "in", "included", ":", "return", "included", "included", ...
[ 142, 0 ]
[ 172, 17 ]
python
en
['en', 'en', 'en']
True
CheckedEval
(file_contents)
Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is.
Return the eval of a gyp file.
def CheckedEval(file_contents): """Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is. """ ast = compiler.parse(file_contents) assert isinstance(ast, Module) c1 = ast.getChildren() asse...
[ "def", "CheckedEval", "(", "file_contents", ")", ":", "ast", "=", "compiler", ".", "parse", "(", "file_contents", ")", "assert", "isinstance", "(", "ast", ",", "Module", ")", "c1", "=", "ast", ".", "getChildren", "(", ")", "assert", "c1", "[", "0", "]"...
[ 175, 0 ]
[ 193, 29 ]
python
en
['en', 'en', 'en']
True
CallLoadTargetBuildFile
(global_flags, build_file_path, variables, includes, depth, check, generator_input_info)
Wrapper around LoadTargetBuildFile for parallel processing. This wrapper is used when LoadTargetBuildFile is executed in a worker process.
Wrapper around LoadTargetBuildFile for parallel processing.
def CallLoadTargetBuildFile(global_flags, build_file_path, variables, includes, depth, check, generator_input_info): """Wrapper around LoadTargetBuildFile for parallel processing. This wrapper is used when LoadTargetBuildFile is...
[ "def", "CallLoadTargetBuildFile", "(", "global_flags", ",", "build_file_path", ",", "variables", ",", "includes", ",", "depth", ",", "check", ",", "generator_input_info", ")", ":", "try", ":", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "signal...
[ 483, 0 ]
[ 525, 15 ]
python
en
['en', 'en', 'en']
True
IsStrCanonicalInt
(string)
Returns True if |string| is in its canonical integer form. The canonical form is such that str(int(string)) == string.
Returns True if |string| is in its canonical integer form.
def IsStrCanonicalInt(string): """Returns True if |string| is in its canonical integer form. The canonical form is such that str(int(string)) == string. """ if type(string) is str: # This function is called a lot so for maximum performance, avoid # involving regexps which would otherwise make the code ...
[ "def", "IsStrCanonicalInt", "(", "string", ")", ":", "if", "type", "(", "string", ")", "is", "str", ":", "# This function is called a lot so for maximum performance, avoid", "# involving regexps which would otherwise make the code much", "# shorter. Regexps would need twice the time ...
[ 652, 0 ]
[ 671, 14 ]
python
en
['en', 'en', 'en']
True
EvalCondition
(condition, conditions_key, phase, variables, build_file)
Returns the dict that should be used or None if the result was that nothing should be used.
Returns the dict that should be used or None if the result was that nothing should be used.
def EvalCondition(condition, conditions_key, phase, variables, build_file): """Returns the dict that should be used or None if the result was that nothing should be used.""" if type(condition) is not list: raise GypError(conditions_key + ' must be a list') if len(condition) < 2: # It's possible that con...
[ "def", "EvalCondition", "(", "condition", ",", "conditions_key", ",", "phase", ",", "variables", ",", "build_file", ")", ":", "if", "type", "(", "condition", ")", "is", "not", "list", ":", "raise", "GypError", "(", "conditions_key", "+", "' must be a list'", ...
[ 1040, 0 ]
[ 1072, 15 ]
python
en
['en', 'en', 'en']
True
EvalSingleCondition
( cond_expr, true_dict, false_dict, phase, variables, build_file)
Returns true_dict if cond_expr evaluates to true, and false_dict otherwise.
Returns true_dict if cond_expr evaluates to true, and false_dict otherwise.
def EvalSingleCondition( cond_expr, true_dict, false_dict, phase, variables, build_file): """Returns true_dict if cond_expr evaluates to true, and false_dict otherwise.""" # Do expansions on the condition itself. Since the conditon can naturally # contain variable references without needing to resort to GY...
[ "def", "EvalSingleCondition", "(", "cond_expr", ",", "true_dict", ",", "false_dict", ",", "phase", ",", "variables", ",", "build_file", ")", ":", "# Do expansions on the condition itself. Since the conditon can naturally", "# contain variable references without needing to resort t...
[ 1075, 0 ]
[ 1108, 21 ]
python
en
['en', 'pt', 'en']
True
ProcessVariablesAndConditionsInDict
(the_dict, phase, variables_in, build_file, the_dict_key=None)
Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function.
Handle all variable and command expansion and conditional evaluation.
def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in, build_file, the_dict_key=None): """Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. ...
[ "def", "ProcessVariablesAndConditionsInDict", "(", "the_dict", ",", "phase", ",", "variables_in", ",", "build_file", ",", "the_dict_key", "=", "None", ")", ":", "# Make a copy of the variables_in dict that can be modified during the", "# loading of automatics and the loading of the...
[ 1193, 0 ]
[ 1302, 36 ]
python
en
['en', 'en', 'en']
True
BuildTargetsDict
(data)
Builds a dict mapping fully-qualified target names to their target dicts. |data| is a dict mapping loaded build files by pathname relative to the current directory. Values in |data| are build file contents. For each |data| value with a "targets" key, the value of the "targets" key is taken as a list containi...
Builds a dict mapping fully-qualified target names to their target dicts.
def BuildTargetsDict(data): """Builds a dict mapping fully-qualified target names to their target dicts. |data| is a dict mapping loaded build files by pathname relative to the current directory. Values in |data| are build file contents. For each |data| value with a "targets" key, the value of the "targets" ...
[ "def", "BuildTargetsDict", "(", "data", ")", ":", "targets", "=", "{", "}", "for", "build_file", "in", "data", "[", "'target_build_files'", "]", ":", "for", "target", "in", "data", "[", "build_file", "]", ".", "get", "(", "'targets'", ",", "[", "]", ")...
[ 1339, 0 ]
[ 1362, 16 ]
python
en
['en', 'en', 'en']
True
QualifyDependencies
(targets)
Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-q...
Make dependency links fully-qualified relative to the current directory.
def QualifyDependencies(targets): """Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will ...
[ "def", "QualifyDependencies", "(", "targets", ")", ":", "all_dependency_sections", "=", "[", "dep", "+", "op", "for", "dep", "in", "dependency_sections", "for", "op", "in", "(", "''", ",", "'!'", ",", "'/'", ")", "]", "for", "target", ",", "target_dict", ...
[ 1365, 0 ]
[ 1401, 71 ]
python
en
['en', 'en', 'en']
True
ExpandWildcardDependencies
(targets, data)
Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access t...
Expands dependencies specified as build_file:*.
def ExpandWildcardDependencies(targets, data): """Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target...
[ "def", "ExpandWildcardDependencies", "(", "targets", ",", "data", ")", ":", "for", "target", ",", "target_dict", "in", "targets", ".", "iteritems", "(", ")", ":", "toolset", "=", "target_dict", "[", "'toolset'", "]", "target_build_file", "=", "gyp", ".", "co...
[ 1404, 0 ]
[ 1470, 25 ]
python
en
['en', 'en', 'en']
True
Unify
(l)
Removes duplicate elements from l, keeping the first element.
Removes duplicate elements from l, keeping the first element.
def Unify(l): """Removes duplicate elements from l, keeping the first element.""" seen = {} return [seen.setdefault(e, e) for e in l if e not in seen]
[ "def", "Unify", "(", "l", ")", ":", "seen", "=", "{", "}", "return", "[", "seen", ".", "setdefault", "(", "e", ",", "e", ")", "for", "e", "in", "l", "if", "e", "not", "in", "seen", "]" ]
[ 1473, 0 ]
[ 1476, 60 ]
python
en
['en', 'en', 'en']
True
RemoveDuplicateDependencies
(targets)
Makes sure every dependency appears only once in all targets's dependency lists.
Makes sure every dependency appears only once in all targets's dependency lists.
def RemoveDuplicateDependencies(targets): """Makes sure every dependency appears only once in all targets's dependency lists.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: ...
[ "def", "RemoveDuplicateDependencies", "(", "targets", ")", ":", "for", "target_name", ",", "target_dict", "in", "targets", ".", "iteritems", "(", ")", ":", "for", "dependency_key", "in", "dependency_sections", ":", "dependencies", "=", "target_dict", ".", "get", ...
[ 1479, 0 ]
[ 1486, 57 ]
python
en
['en', 'en', 'en']
True
Filter
(l, item)
Removes item from l.
Removes item from l.
def Filter(l, item): """Removes item from l.""" res = {} return [res.setdefault(e, e) for e in l if e != item]
[ "def", "Filter", "(", "l", ",", "item", ")", ":", "res", "=", "{", "}", "return", "[", "res", ".", "setdefault", "(", "e", ",", "e", ")", "for", "e", "in", "l", "if", "e", "!=", "item", "]" ]
[ 1489, 0 ]
[ 1492, 55 ]
python
en
['en', 'en', 'en']
True
RemoveSelfDependencies
(targets)
Remove self dependencies from targets that have the prune_self_dependency variable set.
Remove self dependencies from targets that have the prune_self_dependency variable set.
def RemoveSelfDependencies(targets): """Remove self dependencies from targets that have the prune_self_dependency variable set.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: ...
[ "def", "RemoveSelfDependencies", "(", "targets", ")", ":", "for", "target_name", ",", "target_dict", "in", "targets", ".", "iteritems", "(", ")", ":", "for", "dependency_key", "in", "dependency_sections", ":", "dependencies", "=", "target_dict", ".", "get", "(",...
[ 1495, 0 ]
[ 1505, 77 ]
python
en
['en', 'en', 'en']
True
RemoveLinkDependenciesFromNoneTargets
(targets)
Remove dependencies having the 'link_dependency' attribute from the 'none' targets.
Remove dependencies having the 'link_dependency' attribute from the 'none' targets.
def RemoveLinkDependenciesFromNoneTargets(targets): """Remove dependencies having the 'link_dependency' attribute from the 'none' targets.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if depend...
[ "def", "RemoveLinkDependenciesFromNoneTargets", "(", "targets", ")", ":", "for", "target_name", ",", "target_dict", "in", "targets", ".", "iteritems", "(", ")", ":", "for", "dependency_key", "in", "dependency_sections", ":", "dependencies", "=", "target_dict", ".", ...
[ 1508, 0 ]
[ 1519, 56 ]
python
en
['en', 'en', 'en']
True
ProcessListFiltersInDict
(name, the_dict)
Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" lis...
Process regular expression and exclusion-based filters on lists.
def ProcessListFiltersInDict(name, the_dict): """Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Remov...
[ "def", "ProcessListFiltersInDict", "(", "name", ",", "the_dict", ")", ":", "# Look through the dictionary for any lists whose keys end in \"!\" or \"/\".", "# These are lists that will be treated as exclude lists and regular", "# expression-based exclude/include lists. Collect the lists that ar...
[ 2318, 0 ]
[ 2473, 42 ]
python
en
['en', 'en', 'en']
True
ParallelState.LoadTargetBuildFileCallback
(self, result)
Handle the results of running LoadTargetBuildFile in another process.
Handle the results of running LoadTargetBuildFile in another process.
def LoadTargetBuildFileCallback(self, result): """Handle the results of running LoadTargetBuildFile in another process. """ self.condition.acquire() if not result: self.error = True self.condition.notify() self.condition.release() return (build_file_path0, build_file_data0, d...
[ "def", "LoadTargetBuildFileCallback", "(", "self", ",", "result", ")", ":", "self", ".", "condition", ".", "acquire", "(", ")", "if", "not", "result", ":", "self", ".", "error", "=", "True", "self", ".", "condition", ".", "notify", "(", ")", "self", "....
[ 559, 2 ]
[ 577, 28 ]
python
en
['en', 'en', 'en']
True
DependencyGraphNode.FindCycles
(self)
Returns a list of cycles in the graph, where each cycle is its own list.
Returns a list of cycles in the graph, where each cycle is its own list.
def FindCycles(self): """ Returns a list of cycles in the graph, where each cycle is its own list. """ results = [] visited = set() def Visit(node, path): for child in node.dependents: if child in path: results.append([child] + path[:path.index(child) + 1]) elif ...
[ "def", "FindCycles", "(", "self", ")", ":", "results", "=", "[", "]", "visited", "=", "set", "(", ")", "def", "Visit", "(", "node", ",", "path", ")", ":", "for", "child", "in", "node", ".", "dependents", ":", "if", "child", "in", "path", ":", "re...
[ 1587, 2 ]
[ 1605, 18 ]
python
en
['en', 'error', 'th']
False
DependencyGraphNode.DirectDependencies
(self, dependencies=None)
Returns a list of just direct dependencies.
Returns a list of just direct dependencies.
def DirectDependencies(self, dependencies=None): """Returns a list of just direct dependencies.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependen...
[ "def", "DirectDependencies", "(", "self", ",", "dependencies", "=", "None", ")", ":", "if", "dependencies", "==", "None", ":", "dependencies", "=", "[", "]", "for", "dependency", "in", "self", ".", "dependencies", ":", "# Check for None, corresponding to the root ...
[ 1607, 2 ]
[ 1617, 23 ]
python
en
['en', 'en', 'en']
True
DependencyGraphNode._AddImportedDependencies
(self, targets, dependencies=None)
Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that ...
Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings.
def _AddImportedDependencies(self, targets, dependencies=None): """Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies|...
[ "def", "_AddImportedDependencies", "(", "self", ",", "targets", ",", "dependencies", "=", "None", ")", ":", "if", "dependencies", "==", "None", ":", "dependencies", "=", "[", "]", "index", "=", "0", "while", "index", "<", "len", "(", "dependencies", ")", ...
[ 1619, 2 ]
[ 1658, 23 ]
python
en
['en', 'en', 'en']
True
DependencyGraphNode.DirectAndImportedDependencies
(self, targets, dependencies=None)
Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for.
Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for.
def DirectAndImportedDependencies(self, targets, dependencies=None): """Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for. """ dependencies = self.DirectDependencies(dependencies) ...
[ "def", "DirectAndImportedDependencies", "(", "self", ",", "targets", ",", "dependencies", "=", "None", ")", ":", "dependencies", "=", "self", ".", "DirectDependencies", "(", "dependencies", ")", "return", "self", ".", "_AddImportedDependencies", "(", "targets", ",...
[ 1660, 2 ]
[ 1667, 63 ]
python
en
['en', 'en', 'en']
True
DependencyGraphNode.DeepDependencies
(self, dependencies=None)
Returns an OrderedSet of all of a target's dependencies, recursively.
Returns an OrderedSet of all of a target's dependencies, recursively.
def DeepDependencies(self, dependencies=None): """Returns an OrderedSet of all of a target's dependencies, recursively.""" if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() for dependency in self....
[ "def", "DeepDependencies", "(", "self", ",", "dependencies", "=", "None", ")", ":", "if", "dependencies", "is", "None", ":", "# Using a list to get ordered output and a set to do fast \"is it", "# already added\" checks.", "dependencies", "=", "OrderedSet", "(", ")", "for...
[ 1669, 2 ]
[ 1684, 23 ]
python
en
['en', 'en', 'en']
True
DependencyGraphNode._LinkDependenciesInternal
(self, targets, include_shared_libraries, dependencies=None, initial=True)
Returns an OrderedSet of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will ...
Returns an OrderedSet of dependency targets that are linked into this target.
def _LinkDependenciesInternal(self, targets, include_shared_libraries, dependencies=None, initial=True): """Returns an OrderedSet of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outsid...
[ "def", "_LinkDependenciesInternal", "(", "self", ",", "targets", ",", "include_shared_libraries", ",", "dependencies", "=", "None", ",", "initial", "=", "True", ")", ":", "if", "dependencies", "is", "None", ":", "# Using a list to get ordered output and a set to do fast...
[ 1686, 2 ]
[ 1770, 23 ]
python
en
['en', 'en', 'en']
True
DependencyGraphNode.DependenciesForLinkSettings
(self, targets)
Returns a list of dependency targets whose link_settings should be merged into this target.
Returns a list of dependency targets whose link_settings should be merged into this target.
def DependenciesForLinkSettings(self, targets): """ Returns a list of dependency targets whose link_settings should be merged into this target. """ # TODO(sbaig) Currently, chrome depends on the bug that shared libraries' # link_settings are propagated. So for now, we will allow it, unless the...
[ "def", "DependenciesForLinkSettings", "(", "self", ",", "targets", ")", ":", "# TODO(sbaig) Currently, chrome depends on the bug that shared libraries'", "# link_settings are propagated. So for now, we will allow it, unless the", "# 'allow_sharedlib_linksettings_propagation' flag is explicitly ...
[ 1772, 2 ]
[ 1784, 76 ]
python
en
['en', 'error', 'th']
False
DependencyGraphNode.DependenciesToLinkAgainst
(self, targets)
Returns a list of dependency targets that are linked into this target.
Returns a list of dependency targets that are linked into this target.
def DependenciesToLinkAgainst(self, targets): """ Returns a list of dependency targets that are linked into this target. """ return self._LinkDependenciesInternal(targets, True)
[ "def", "DependenciesToLinkAgainst", "(", "self", ",", "targets", ")", ":", "return", "self", ".", "_LinkDependenciesInternal", "(", "targets", ",", "True", ")" ]
[ 1786, 2 ]
[ 1790, 56 ]
python
en
['en', 'error', 'th']
False
get_bin_intervals
(data, num_bins)
Returns bin intervals for 1D data. Parameters ---------- data: np.ndarray A 1D NumPy array of values to get bin intervals for. num_bins: int The number of bins to create. Returns ------- bin_intervals: np.ndarray of shape (num_bins, 2) A 2D NumPy array of bin i...
Returns bin intervals for 1D data.
def get_bin_intervals(data, num_bins): """ Returns bin intervals for 1D data. Parameters ---------- data: np.ndarray A 1D NumPy array of values to get bin intervals for. num_bins: int The number of bins to create. Returns ------- bin_intervals: np.ndarray of shape (...
[ "def", "get_bin_intervals", "(", "data", ",", "num_bins", ")", ":", "# Transition points between bins.", "bin_trans", "=", "np", ".", "linspace", "(", "data", "[", "0", "]", ",", "data", "[", "-", "1", "]", ",", "num_bins", "+", "1", ",", "endpoint", "="...
[ 6, 0 ]
[ 29, 24 ]
python
en
['en', 'error', 'th']
False
xr_scale_res
(dataset, x_coord='longitude', y_coord='latitude', frac_res=None, abs_res=None)
Scales the resolution of an `xarray.Dataset` or `xarray.DataArray` to a fraction of its original resolution or an absolute resolution. Parameters ---------- dataset: xarray.Dataset or xarray.DataArray The Dataset or DataArray to reduce the resolution of. x_coord, y_coord: str N...
Scales the resolution of an `xarray.Dataset` or `xarray.DataArray` to a fraction of its original resolution or an absolute resolution.
def xr_scale_res(dataset, x_coord='longitude', y_coord='latitude', frac_res=None, abs_res=None): """ Scales the resolution of an `xarray.Dataset` or `xarray.DataArray` to a fraction of its original resolution or an absolute resolution. Parameters ---------- dataset: xarray.Data...
[ "def", "xr_scale_res", "(", "dataset", ",", "x_coord", "=", "'longitude'", ",", "y_coord", "=", "'latitude'", ",", "frac_res", "=", "None", ",", "abs_res", "=", "None", ")", ":", "assert", "frac_res", "is", "not", "None", "or", "abs_res", "is", "not", "N...
[ 32, 0 ]
[ 70, 74 ]
python
en
['en', 'error', 'th']
False
xr_sel_time_by_bin
(dataset, num_bins, time_coord='time')
Selects time coordinates by nearest neighbors of the means of bins. This is useful for plotting data with high variance in temporal spacing between acquisitions. Parameters ---------- dataset: xarray.Dataset or xarray.DataArray The Dataset or DataArray to aggregate by binning. ...
Selects time coordinates by nearest neighbors of the means of bins. This is useful for plotting data with high variance in temporal spacing between acquisitions.
def xr_sel_time_by_bin(dataset, num_bins, time_coord='time'): """ Selects time coordinates by nearest neighbors of the means of bins. This is useful for plotting data with high variance in temporal spacing between acquisitions. Parameters ---------- dataset: xarray.Dataset or xarray.DataArr...
[ "def", "xr_sel_time_by_bin", "(", "dataset", ",", "num_bins", ",", "time_coord", "=", "'time'", ")", ":", "return", "xr_interp", "(", "dataset", ",", "{", "time_coord", ":", "(", "'bin'", ",", "{", "'num'", ":", "num_bins", "}", ")", "}", ")" ]
[ 73, 0 ]
[ 94, 71 ]
python
en
['en', 'error', 'th']
False
xr_interp
(dataset, interp_config)
Interpolates an `xarray.Dataset` or `xarray.DataArray`. This is often done to match dimensions between xarray objects or downsample to reduce memory consumption. First, coordinates are interpolated according to `interp_config`. Then the data values for those interpolated coordinates are obtained ...
Interpolates an `xarray.Dataset` or `xarray.DataArray`. This is often done to match dimensions between xarray objects or downsample to reduce memory consumption.
def xr_interp(dataset, interp_config): """ Interpolates an `xarray.Dataset` or `xarray.DataArray`. This is often done to match dimensions between xarray objects or downsample to reduce memory consumption. First, coordinates are interpolated according to `interp_config`. Then the data values for...
[ "def", "xr_interp", "(", "dataset", ",", "interp_config", ")", ":", "# Create the new coordinates.", "new_coords", "=", "{", "}", "for", "dim", ",", "(", "interp_type", ",", "interp_kwargs", ")", "in", "interp_config", ".", "items", "(", ")", ":", "# Determine...
[ 97, 0 ]
[ 169, 22 ]
python
en
['en', 'error', 'th']
False
column_reflection_fallback
( selectable: Select, dialect: Dialect, sqlalchemy_engine: Engine )
If we can't reflect the table, use a query to at least get column names.
If we can't reflect the table, use a query to at least get column names.
def column_reflection_fallback( selectable: Select, dialect: Dialect, sqlalchemy_engine: Engine ) -> List[Dict[str, str]]: """If we can't reflect the table, use a query to at least get column names.""" col_info_dict_list: List[Dict[str, str]] if dialect.name.lower() == "mssql": # Get column name...
[ "def", "column_reflection_fallback", "(", "selectable", ":", "Select", ",", "dialect", ":", "Dialect", ",", "sqlalchemy_engine", ":", "Engine", ")", "->", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", ":", "col_info_dict_list", ":", "List", "[", "...
[ 242, 0 ]
[ 288, 29 ]
python
en
['en', 'en', 'en']
True
validate_distribution_parameters
(distribution, params)
Ensures that necessary parameters for a distribution are present and that all parameters are sensical. If parameters necessary to construct a distribution are missing or invalid, this function raises ValueError\ with an informative description. Note that 'loc' and 'scale' are optional arguments, and that...
Ensures that necessary parameters for a distribution are present and that all parameters are sensical.
def validate_distribution_parameters(distribution, params): """Ensures that necessary parameters for a distribution are present and that all parameters are sensical. If parameters necessary to construct a distribution are missing or invalid, this function raises ValueError\ with an informative descri...
[ "def", "validate_distribution_parameters", "(", "distribution", ",", "params", ")", ":", "norm_msg", "=", "(", "\"norm distributions require 0 parameters and optionally 'mean', 'std_dev'.\"", ")", "beta_msg", "=", "\"beta distributions require 2 positive parameters 'alpha', 'beta' and ...
[ 358, 0 ]
[ 497, 10 ]
python
en
['en', 'en', 'en']
True
_scipy_distribution_positional_args_from_dict
(distribution, params)
Helper function that returns positional arguments for a scipy distribution using a dict of parameters. See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\ to see an example of scipy's positional arguments. This function returns the arguments s...
Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
def _scipy_distribution_positional_args_from_dict(distribution, params): """Helper function that returns positional arguments for a scipy distribution using a dict of parameters. See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\ to see a...
[ "def", "_scipy_distribution_positional_args_from_dict", "(", "distribution", ",", "params", ")", ":", "params", "[", "\"loc\"", "]", "=", "params", ".", "get", "(", "\"loc\"", ",", "0", ")", "if", "\"scale\"", "not", "in", "params", ":", "params", "[", "\"sc...
[ 500, 0 ]
[ 535, 45 ]
python
en
['en', 'en', 'en']
True
is_valid_continuous_partition_object
(partition_object)
Tests whether a given object is a valid continuous partition object. See :ref:`partition_object`. :param partition_object: The partition_object to evaluate :return: Boolean
Tests whether a given object is a valid continuous partition object. See :ref:`partition_object`.
def is_valid_continuous_partition_object(partition_object): """Tests whether a given object is a valid continuous partition object. See :ref:`partition_object`. :param partition_object: The partition_object to evaluate :return: Boolean """ if ( (partition_object is None) or ("weight...
[ "def", "is_valid_continuous_partition_object", "(", "partition_object", ")", ":", "if", "(", "(", "partition_object", "is", "None", ")", "or", "(", "\"weights\"", "not", "in", "partition_object", ")", "or", "(", "\"bins\"", "not", "in", "partition_object", ")", ...
[ 538, 0 ]
[ 567, 5 ]
python
en
['en', 'en', 'en']
True
test_graceful_failure_with_no_internet
()
Test that having usage statistics enabled does not negatively impact kill signals or cause loss of queued usage statistics.
Test that having usage statistics enabled does not negatively impact kill signals or cause loss of queued usage statistics.
def test_graceful_failure_with_no_internet(): """Test that having usage statistics enabled does not negatively impact kill signals or cause loss of queued usage statistics.""" # Execute process that initializes data context # NOTE - JPC - 20200227 - this is crazy long (not because of logging I think, but w...
[ "def", "test_graceful_failure_with_no_internet", "(", ")", ":", "# Execute process that initializes data context", "# NOTE - JPC - 20200227 - this is crazy long (not because of logging I think, but worth revisiting)", "acceptable_startup_time", "=", "6", "acceptable_shutdown_time", "=", "1",...
[ 144, 0 ]
[ 179, 38 ]
python
en
['en', 'en', 'en']
True
get_base_href_html
(full_url)
The base href line tells the html what the base page really is. This is important when trying to open the page outside it's home.
The base href line tells the html what the base page really is. This is important when trying to open the page outside it's home.
def get_base_href_html(full_url): ''' The base href line tells the html what the base page really is. This is important when trying to open the page outside it's home. ''' base_url = get_base_url(full_url) return '<base href="%s">' % base_url
[ "def", "get_base_href_html", "(", "full_url", ")", ":", "base_url", "=", "get_base_url", "(", "full_url", ")", "return", "'<base href=\"%s\">'", "%", "base_url" ]
[ 96, 0 ]
[ 100, 40 ]
python
en
['en', 'en', 'en']
True
get_html_source_with_base_href
(driver, page_source)
Combines the domain base href with the html source. This is needed for the page html to render correctly.
Combines the domain base href with the html source. This is needed for the page html to render correctly.
def get_html_source_with_base_href(driver, page_source): ''' Combines the domain base href with the html source. This is needed for the page html to render correctly. ''' last_page = get_last_page(driver) if '://' in last_page: base_href_html = get_base_href_html(last_page) return '%...
[ "def", "get_html_source_with_base_href", "(", "driver", ",", "page_source", ")", ":", "last_page", "=", "get_last_page", "(", "driver", ")", "if", "'://'", "in", "last_page", ":", "base_href_html", "=", "get_base_href_html", "(", "last_page", ")", "return", "'%s\\...
[ 103, 0 ]
[ 110, 13 ]
python
en
['en', 'en', 'en']
True
archive_logs_if_set
(log_path, archive_logs=False)
Handle Logging
Handle Logging
def archive_logs_if_set(log_path, archive_logs=False): """ Handle Logging """ arg_join = " ".join(sys.argv) if ("-n" in sys.argv) or ("-n=" in arg_join) or (arg_join == "-c"): return # Skip if multithreaded if log_path.endswith("/"): log_path = log_path[:-1] if not os.path.exists(lo...
[ "def", "archive_logs_if_set", "(", "log_path", ",", "archive_logs", "=", "False", ")", ":", "arg_join", "=", "\" \"", ".", "join", "(", "sys", ".", "argv", ")", "if", "(", "\"-n\"", "in", "sys", ".", "argv", ")", "or", "(", "\"-n=\"", "in", "arg_join",...
[ 127, 0 ]
[ 152, 49 ]
python
en
['it', 'ja', 'en']
False
log_folder_setup
(log_path, archive_logs=False)
Handle Logging
Handle Logging
def log_folder_setup(log_path, archive_logs=False): """ Handle Logging """ if log_path.endswith("/"): log_path = log_path[:-1] if not os.path.exists(log_path): try: os.makedirs(log_path) except Exception: pass # Should only be reachable during multi-threaded ...
[ "def", "log_folder_setup", "(", "log_path", ",", "archive_logs", "=", "False", ")", ":", "if", "log_path", ".", "endswith", "(", "\"/\"", ")", ":", "log_path", "=", "log_path", "[", ":", "-", "1", "]", "if", "not", "os", ".", "path", ".", "exists", "...
[ 155, 0 ]
[ 189, 48 ]
python
en
['it', 'ja', 'en']
False
Benchmark.hash
(self, val: str)
Used only for testing purposes.
Used only for testing purposes.
def hash(self, val: str): """ Used only for testing purposes. """ self._hash_value = val
[ "def", "hash", "(", "self", ",", "val", ":", "str", ")", ":", "self", ".", "_hash_value", "=", "val" ]
[ 136, 4 ]
[ 140, 30 ]
python
en
['en', 'error', 'th']
False
IR.agent_init
(self, aconf: Config)
Initialize as the Intercept Agent, if we're doing that. THIS WHOLE METHOD NEEDS TO GO AWAY: instead, just configure the agent with CRDs as usual. However, that's just too painful to contemplate without `edgectl inject-agent`. :param aconf: Config to work with :return: None ...
Initialize as the Intercept Agent, if we're doing that.
def agent_init(self, aconf: Config) -> None: """ Initialize as the Intercept Agent, if we're doing that. THIS WHOLE METHOD NEEDS TO GO AWAY: instead, just configure the agent with CRDs as usual. However, that's just too painful to contemplate without `edgectl inject-agent`. :pa...
[ "def", "agent_init", "(", "self", ",", "aconf", ":", "Config", ")", "->", "None", ":", "# Intercept stuff is an Edge Stack thing.", "if", "not", "(", "self", ".", "edge_stack_allowed", "and", "self", ".", "agent_active", ")", ":", "self", ".", "logger", ".", ...
[ 392, 4 ]
[ 478, 44 ]
python
en
['en', 'error', 'th']
False
IR.cache_fetch
(self, key: str)
Fetch a key from our cache. If we get anything, make sure that its IR pointer is set back to us -- since the cache can easily outlive the IR, chances are pretty high that the object might've originally been part of a different IR. Yes, this implies that trying to use the cache ...
Fetch a key from our cache. If we get anything, make sure that its IR pointer is set back to us -- since the cache can easily outlive the IR, chances are pretty high that the object might've originally been part of a different IR.
def cache_fetch(self, key: str) -> Optional[IRResource]: """ Fetch a key from our cache. If we get anything, make sure that its IR pointer is set back to us -- since the cache can easily outlive the IR, chances are pretty high that the object might've originally been part of a di...
[ "def", "cache_fetch", "(", "self", ",", "key", ":", "str", ")", "->", "Optional", "[", "IRResource", "]", ":", "rsrc", "=", "self", ".", "cache", "[", "key", "]", "# Did we get anything?", "if", "rsrc", "is", "not", "None", ":", "# By definition, anything ...
[ 548, 4 ]
[ 570, 19 ]
python
en
['en', 'error', 'th']
False
IR.cache_add
(self, rsrc: IRResource)
Add an IRResource to our cache. Mostly this is here to let mypy check that everything cached by the IR layer is an IRResource.
Add an IRResource to our cache. Mostly this is here to let mypy check that everything cached by the IR layer is an IRResource.
def cache_add(self, rsrc: IRResource) -> None: """ Add an IRResource to our cache. Mostly this is here to let mypy check that everything cached by the IR layer is an IRResource. """ self.cache.add(rsrc)
[ "def", "cache_add", "(", "self", ",", "rsrc", ":", "IRResource", ")", "->", "None", ":", "self", ".", "cache", ".", "add", "(", "rsrc", ")" ]
[ 572, 4 ]
[ 577, 28 ]
python
en
['en', 'error', 'th']
False
IR.cache_link
(self, owner: IRResource, owned: IRResource)
Link two IRResources in our cache. Mostly this is here to let mypy check that everything linked by the IR layer is an IRResource.
Link two IRResources in our cache. Mostly this is here to let mypy check that everything linked by the IR layer is an IRResource.
def cache_link(self, owner: IRResource, owned: IRResource) -> None: """ Link two IRResources in our cache. Mostly this is here to let mypy check that everything linked by the IR layer is an IRResource. """ self.cache.link(owner, owned)
[ "def", "cache_link", "(", "self", ",", "owner", ":", "IRResource", ",", "owned", ":", "IRResource", ")", "->", "None", ":", "self", ".", "cache", ".", "link", "(", "owner", ",", "owned", ")" ]
[ 579, 4 ]
[ 584, 37 ]
python
en
['en', 'error', 'th']
False
_check_valid_s3_path
( path: str, )
Performs a basic check for validity of the S3 path
Performs a basic check for validity of the S3 path
def _check_valid_s3_path( path: str, ) -> None: """Performs a basic check for validity of the S3 path""" bad_chars = [c for c in INVALID_S3_CHARS if c in path] if len(bad_chars) > 0: msg = ( f"The parsed S3 path={path} contains the invalid characters {bad_chars}." "Please...
[ "def", "_check_valid_s3_path", "(", "path", ":", "str", ",", ")", "->", "None", ":", "bad_chars", "=", "[", "c", "for", "c", "in", "INVALID_S3_CHARS", "if", "c", "in", "path", "]", "if", "len", "(", "bad_chars", ")", ">", "0", ":", "msg", "=", "(",...
[ 145, 0 ]
[ 157, 30 ]
python
en
['en', 'en', 'en']
True
InferredAssetS3DataConnector.__init__
( self, name: str, datasource_name: str, bucket: str, execution_engine: Optional[ExecutionEngine] = None, default_regex: Optional[dict] = None, sorters: Optional[list] = None, prefix: Optional[str] = "", delimiter: Optional[str] = "/", max_...
InferredAssetS3DataConnector for connecting to S3. Args: name (str): required name for data_connector datasource_name (str): required name for datasource bucket (str): bucket for S3 execution_engine (ExecutionEngine): optional reference to ExecutionEngin...
InferredAssetS3DataConnector for connecting to S3.
def __init__( self, name: str, datasource_name: str, bucket: str, execution_engine: Optional[ExecutionEngine] = None, default_regex: Optional[dict] = None, sorters: Optional[list] = None, prefix: Optional[str] = "", delimiter: Optional[str] = "/", ...
[ "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "datasource_name", ":", "str", ",", "bucket", ":", "str", ",", "execution_engine", ":", "Optional", "[", "ExecutionEngine", "]", "=", "None", ",", "default_regex", ":", "Optional", "[", "dict", ...
[ 37, 4 ]
[ 91, 13 ]
python
en
['en', 'error', 'th']
False
InferredAssetS3DataConnector.build_batch_spec
(self, batch_definition: BatchDefinition)
Build BatchSpec from batch_definition by calling DataConnector's build_batch_spec function. Args: batch_definition (BatchDefinition): to be used to build batch_spec Returns: BatchSpec built from batch_definition
Build BatchSpec from batch_definition by calling DataConnector's build_batch_spec function.
def build_batch_spec(self, batch_definition: BatchDefinition) -> S3BatchSpec: """ Build BatchSpec from batch_definition by calling DataConnector's build_batch_spec function. Args: batch_definition (BatchDefinition): to be used to build batch_spec Returns: BatchS...
[ "def", "build_batch_spec", "(", "self", ",", "batch_definition", ":", "BatchDefinition", ")", "->", "S3BatchSpec", ":", "batch_spec", ":", "PathBatchSpec", "=", "super", "(", ")", ".", "build_batch_spec", "(", "batch_definition", "=", "batch_definition", ")", "ret...
[ 93, 4 ]
[ 106, 38 ]
python
en
['en', 'error', 'th']
False
InferredAssetS3DataConnector._get_data_reference_list
( self, data_asset_name: Optional[str] = None )
List objects in the underlying data store to create a list of data_references. This method is used to refresh the cache.
List objects in the underlying data store to create a list of data_references.
def _get_data_reference_list( self, data_asset_name: Optional[str] = None ) -> List[str]: """ List objects in the underlying data store to create a list of data_references. This method is used to refresh the cache. """ query_options: dict = { "Bucket": se...
[ "def", "_get_data_reference_list", "(", "self", ",", "data_asset_name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "List", "[", "str", "]", ":", "query_options", ":", "dict", "=", "{", "\"Bucket\"", ":", "self", ".", "_bucket", ",", "\"Pre...
[ 108, 4 ]
[ 132, 24 ]
python
en
['en', 'error', 'th']
False
initialized_project
(mock_webbrowser, monkeypatch, tmp_path_factory)
This is an initialized project through the CLI.
This is an initialized project through the CLI.
def initialized_project(mock_webbrowser, monkeypatch, tmp_path_factory): """This is an initialized project through the CLI.""" project_dir = str(tmp_path_factory.mktemp("my_rad_project")) os.makedirs(os.path.join(project_dir, "data")) data_folder_path = os.path.join(project_dir, "data") data_path = ...
[ "def", "initialized_project", "(", "mock_webbrowser", ",", "monkeypatch", ",", "tmp_path_factory", ")", ":", "project_dir", "=", "str", "(", "tmp_path_factory", ".", "mktemp", "(", "\"my_rad_project\"", ")", ")", "os", ".", "makedirs", "(", "os", ".", "path", ...
[ 281, 0 ]
[ 308, 22 ]
python
en
['en', 'en', 'en']
True
load_data
(data, features, transformations={})
Load data and set the feature matrix and label vector. Args: data (pandas.DataFrame): total input data features (list of str): column names to be used in the inference model transformation (dict of (str, func)): transformations to be applied to features Returns: X (numpy.matrix...
Load data and set the feature matrix and label vector.
def load_data(data, features, transformations={}): """Load data and set the feature matrix and label vector. Args: data (pandas.DataFrame): total input data features (list of str): column names to be used in the inference model transformation (dict of (str, func)): transformations to be...
[ "def", "load_data", "(", "data", ",", "features", ",", "transformations", "=", "{", "}", ")", ":", "df", "=", "data", "[", "features", "]", ".", "copy", "(", ")", "bool_cols", "=", "[", "col", "for", "col", "in", "df", ".", "columns", "if", "df", ...
[ 220, 0 ]
[ 250, 12 ]
python
en
['en', 'en', 'en']
True
LabelEncoder.__init__
(self, min_obs=10)
Initialize the LabelEncoder class object. Args: min_obs (int): minimum number of observation to assign a label.
Initialize the LabelEncoder class object.
def __init__(self, min_obs=10): """Initialize the LabelEncoder class object. Args: min_obs (int): minimum number of observation to assign a label. """ self.min_obs = min_obs
[ "def", "__init__", "(", "self", ",", "min_obs", "=", "10", ")", ":", "self", ".", "min_obs", "=", "min_obs" ]
[ 24, 4 ]
[ 31, 30 ]
python
en
['en', 'en', 'en']
True
LabelEncoder._get_label_encoder_and_max
(self, x)
Return a mapping from values and its maximum of a column to integer labels. Args: x (pandas.Series): a categorical column to encode. Returns: label_encoder (dict): mapping from values of features to integers max_label (int): maximum label
Return a mapping from values and its maximum of a column to integer labels.
def _get_label_encoder_and_max(self, x): """Return a mapping from values and its maximum of a column to integer labels. Args: x (pandas.Series): a categorical column to encode. Returns: label_encoder (dict): mapping from values of features to integers max_la...
[ "def", "_get_label_encoder_and_max", "(", "self", ",", "x", ")", ":", "# NaN cannot be used as a key for dict. So replace it with a random integer.", "label_count", "=", "x", ".", "fillna", "(", "NAN_INT", ")", ".", "value_counts", "(", ")", "n_uniq", "=", "label_count"...
[ 36, 4 ]
[ 63, 39 ]
python
en
['en', 'en', 'en']
True
LabelEncoder._transform_col
(self, x, i)
Encode one categorical column into labels. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: x (pandas.Series): a column with labels.
Encode one categorical column into labels.
def _transform_col(self, x, i): """Encode one categorical column into labels. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: x (pandas.Series): a column with labels. """ return x.fillna(NAN_INT).map(sel...
[ "def", "_transform_col", "(", "self", ",", "x", ",", "i", ")", ":", "return", "x", ".", "fillna", "(", "NAN_INT", ")", ".", "map", "(", "self", ".", "label_encoders", "[", "i", "]", ")", ".", "fillna", "(", "0", ")" ]
[ 65, 4 ]
[ 75, 70 ]
python
en
['it', 'en', 'en']
True
LabelEncoder.transform
(self, X)
Encode categorical columns into label encoded columns Args: X (pandas.DataFrame): categorical columns to encode Returns: X (pandas.DataFrame): label encoded columns
Encode categorical columns into label encoded columns
def transform(self, X): """Encode categorical columns into label encoded columns Args: X (pandas.DataFrame): categorical columns to encode Returns: X (pandas.DataFrame): label encoded columns """ for i, col in enumerate(X.columns): X.loc[:, ...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "for", "i", ",", "col", "in", "enumerate", "(", "X", ".", "columns", ")", ":", "X", ".", "loc", "[", ":", ",", "col", "]", "=", "self", ".", "_transform_col", "(", "X", "[", "col", "]", ","...
[ 87, 4 ]
[ 100, 16 ]
python
en
['en', 'en', 'en']
True
LabelEncoder.fit_transform
(self, X, y=None)
Encode categorical columns into label encoded columns Args: X (pandas.DataFrame): categorical columns to encode Returns: X (pandas.DataFrame): label encoded columns
Encode categorical columns into label encoded columns
def fit_transform(self, X, y=None): """Encode categorical columns into label encoded columns Args: X (pandas.DataFrame): categorical columns to encode Returns: X (pandas.DataFrame): label encoded columns """ self.label_encoders = [None] * X.shape[1] ...
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "self", ".", "label_encoders", "=", "[", "None", "]", "*", "X", ".", "shape", "[", "1", "]", "self", ".", "label_maxes", "=", "[", "None", "]", "*", "X", ".", "shap...
[ 102, 4 ]
[ 121, 16 ]
python
en
['en', 'en', 'en']
True
OneHotEncoder.__init__
(self, min_obs=10)
Initialize the OneHotEncoder class object. Args: min_obs (int): minimum number of observation to create a dummy variable
Initialize the OneHotEncoder class object.
def __init__(self, min_obs=10): """Initialize the OneHotEncoder class object. Args: min_obs (int): minimum number of observation to create a dummy variable """ self.min_obs = min_obs self.label_encoder = LabelEncoder(min_obs)
[ "def", "__init__", "(", "self", ",", "min_obs", "=", "10", ")", ":", "self", ".", "min_obs", "=", "min_obs", "self", ".", "label_encoder", "=", "LabelEncoder", "(", "min_obs", ")" ]
[ 135, 4 ]
[ 143, 50 ]
python
en
['en', 'en', 'en']
True
OneHotEncoder._transform_col
(self, x, i)
Encode one categorical column into sparse matrix with one-hot-encoding. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: X (scipy.sparse.coo_matrix): sparse matrix encoding a categorical ...
Encode one categorical column into sparse matrix with one-hot-encoding.
def _transform_col(self, x, i): """Encode one categorical column into sparse matrix with one-hot-encoding. Args: x (pandas.Series): a categorical column to encode i (int): column index Returns: X (scipy.sparse.coo_matrix): sparse matrix encoding a categorica...
[ "def", "_transform_col", "(", "self", ",", "x", ",", "i", ")", ":", "labels", "=", "self", ".", "label_encoder", ".", "_transform_col", "(", "x", ",", "i", ")", "label_max", "=", "self", ".", "label_encoder", ".", "label_maxes", "[", "i", "]", "# build...
[ 148, 4 ]
[ 173, 23 ]
python
en
['en', 'en', 'en']
True
OneHotEncoder.transform
(self, X)
Encode categorical columns into sparse matrix with one-hot-encoding. Args: X (pandas.DataFrame): categorical columns to encode Returns: X_new (scipy.sparse.coo_matrix): sparse matrix encoding categorical variables into dummy variable...
Encode categorical columns into sparse matrix with one-hot-encoding.
def transform(self, X): """Encode categorical columns into sparse matrix with one-hot-encoding. Args: X (pandas.DataFrame): categorical columns to encode Returns: X_new (scipy.sparse.coo_matrix): sparse matrix encoding categorical ...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "for", "i", ",", "col", "in", "enumerate", "(", "X", ".", "columns", ")", ":", "X_col", "=", "self", ".", "_transform_col", "(", "X", "[", "col", "]", ",", "i", ")", "if", "X_col", "is", "not...
[ 180, 4 ]
[ 203, 20 ]
python
en
['en', 'en', 'en']
True
OneHotEncoder.fit_transform
(self, X, y=None)
Encode categorical columns into sparse matrix with one-hot-encoding. Args: X (pandas.DataFrame): categorical columns to encode Returns: sparse matrix encoding categorical variables into dummy variables
Encode categorical columns into sparse matrix with one-hot-encoding.
def fit_transform(self, X, y=None): """Encode categorical columns into sparse matrix with one-hot-encoding. Args: X (pandas.DataFrame): categorical columns to encode Returns: sparse matrix encoding categorical variables into dummy variables """ self.lab...
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "self", ".", "label_encoder", ".", "fit", "(", "X", ")", "return", "self", ".", "transform", "(", "X", ")" ]
[ 205, 4 ]
[ 217, 32 ]
python
en
['en', 'en', 'en']
True
convert_to_dtype
(data, dtype)
A utility function converting xarray, pandas, or NumPy data to a given dtype. Parameters ---------- data: xarray.Dataset, xarray.DataArray, pandas.Series, pandas.DataFrame, or numpy.ndarray dtype: str or numpy.dtype A string denoting a Python datatype name (e.g. int, float) or...
A utility function converting xarray, pandas, or NumPy data to a given dtype.
def convert_to_dtype(data, dtype): """ A utility function converting xarray, pandas, or NumPy data to a given dtype. Parameters ---------- data: xarray.Dataset, xarray.DataArray, pandas.Series, pandas.DataFrame, or numpy.ndarray dtype: str or numpy.dtype A string denoting a...
[ "def", "convert_to_dtype", "(", "data", ",", "dtype", ")", ":", "if", "dtype", "is", "None", ":", "# Don't convert the data type.", "return", "data", "return", "data", ".", "astype", "(", "dtype", ")" ]
[ 44, 0 ]
[ 58, 29 ]
python
en
['en', 'error', 'th']
False
create_mosaic
(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, **kwargs)
Creates a most-recent-to-oldest mosaic of the input dataset. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain: coordinates: time, latitude, longitude variables: variables to be mosaicked (e.g. red, green, and blue bands) ...
Creates a most-recent-to-oldest mosaic of the input dataset.
def create_mosaic(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, **kwargs): """ Creates a most-recent-to-oldest mosaic of the input dataset. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain: c...
[ "def", "create_mosaic", "(", "dataset_in", ",", "clean_mask", "=", "None", ",", "no_data", "=", "-", "9999", ",", "dtype", "=", "None", ",", "intermediate_product", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dataset_in", "=", "dataset_in", ".", "co...
[ 65, 0 ]
[ 127, 22 ]
python
en
['en', 'error', 'th']
False
create_mean_mosaic
(dataset_in, clean_mask=None, no_data=-9999, dtype=None, **kwargs)
Method for calculating the mean pixel value for a given dataset. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain: coordinates: time, latitude, longitude variables: variables to be mosaicked (e.g. red, green, and blue bands...
Method for calculating the mean pixel value for a given dataset.
def create_mean_mosaic(dataset_in, clean_mask=None, no_data=-9999, dtype=None, **kwargs): """ Method for calculating the mean pixel value for a given dataset. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain: coordinates: time, ...
[ "def", "create_mean_mosaic", "(", "dataset_in", ",", "clean_mask", "=", "None", ",", "no_data", "=", "-", "9999", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Default to masking nothing.", "if", "clean_mask", "is", "None", ":", "clean_mas...
[ 129, 0 ]
[ 171, 22 ]
python
en
['en', 'error', 'th']
False
create_median_mosaic
(dataset_in, clean_mask=None, no_data=-9999, dtype=None, **kwargs)
Method for calculating the median pixel value for a given dataset. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain: coordinates: time, latitude, longitude variables: variables to be mosaicked (e.g. red, green, and blue ban...
Method for calculating the median pixel value for a given dataset.
def create_median_mosaic(dataset_in, clean_mask=None, no_data=-9999, dtype=None, **kwargs): """ Method for calculating the median pixel value for a given dataset. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain: coordinates: ti...
[ "def", "create_median_mosaic", "(", "dataset_in", ",", "clean_mask", "=", "None", ",", "no_data", "=", "-", "9999", ",", "dtype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Default to masking nothing.", "if", "clean_mask", "is", "None", ":", "clean_m...
[ 174, 0 ]
[ 216, 22 ]
python
en
['en', 'error', 'th']
False
create_max_ndvi_mosaic
(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, **kwargs)
Method for calculating the pixel value for the max ndvi value. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain: coordinates: time, latitude, longitude variables: variables to be mosaicked (e.g. red, green, and blue bands) ...
Method for calculating the pixel value for the max ndvi value.
def create_max_ndvi_mosaic(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, **kwargs): """ Method for calculating the pixel value for the max ndvi value. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain...
[ "def", "create_max_ndvi_mosaic", "(", "dataset_in", ",", "clean_mask", "=", "None", ",", "no_data", "=", "-", "9999", ",", "dtype", "=", "None", ",", "intermediate_product", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dataset_in", "=", "dataset_in", "...
[ 219, 0 ]
[ 280, 22 ]
python
en
['en', 'error', 'th']
False
create_min_ndvi_mosaic
(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, **kwargs)
Method for calculating the pixel value for the min ndvi value. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain: coordinates: time, latitude, longitude variables: variables to be mosaicked (e.g. red, green, and blue bands) ...
Method for calculating the pixel value for the min ndvi value.
def create_min_ndvi_mosaic(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, **kwargs): """ Method for calculating the pixel value for the min ndvi value. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain...
[ "def", "create_min_ndvi_mosaic", "(", "dataset_in", ",", "clean_mask", "=", "None", ",", "no_data", "=", "-", "9999", ",", "dtype", "=", "None", ",", "intermediate_product", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dataset_in", "=", "dataset_in", "...
[ 283, 0 ]
[ 345, 22 ]
python
en
['en', 'error', 'th']
False
unpack_bits
(land_cover_endcoding, data_array, cover_type)
Description: Unpack bits for end of ls7 and ls8 functions ----- Input: land_cover_encoding(dict hash table) land cover endcoding provided by ls7 or ls8 data_array( xarray DataArray) cover_type(String) type of cover Output: unpacked DataArray
Description: Unpack bits for end of ls7 and ls8 functions ----- Input: land_cover_encoding(dict hash table) land cover endcoding provided by ls7 or ls8 data_array( xarray DataArray) cover_type(String) type of cover Output: unpacked DataArray
def unpack_bits(land_cover_endcoding, data_array, cover_type): """ Description: Unpack bits for end of ls7 and ls8 functions ----- Input: land_cover_encoding(dict hash table) land cover endcoding provided by ls7 or ls8 data_array( xarray DataArray) cover_type(String) type of cover Output: ...
[ "def", "unpack_bits", "(", "land_cover_endcoding", ",", "data_array", ",", "cover_type", ")", ":", "boolean_mask", "=", "np", ".", "isin", "(", "data_array", ".", "values", ",", "land_cover_endcoding", "[", "cover_type", "]", ")", "return", "xr", ".", "DataArr...
[ 347, 0 ]
[ 364, 49 ]
python
en
['en', 'error', 'th']
False
create_hdmedians_multiple_band_mosaic
(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, operation="median", ...
Calculates the geomedian or geomedoid using a multi-band processing method. Parameters ---------- dataset_in: xarray.Dataset A dataset retrieved from the Data Cube; should contain: coordinates: time, latitude, longitude (in that order) variables: variables to be mosaicked (e.g....
Calculates the geomedian or geomedoid using a multi-band processing method.
def create_hdmedians_multiple_band_mosaic(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, ...
[ "def", "create_hdmedians_multiple_band_mosaic", "(", "dataset_in", ",", "clean_mask", "=", "None", ",", "no_data", "=", "-", "9999", ",", "dtype", "=", "None", ",", "intermediate_product", "=", "None", ",", "operation", "=", "\"median\"", ",", "*", "*", "kwarg...
[ 412, 0 ]
[ 486, 22 ]
python
en
['en', 'error', 'th']
False
restore_or_convert_dtypes
(dtype_for_all, band_list, dataset_in_dtypes, dataset_out, no_data)
Restores original datatypes to data variables in Datasets output by mosaic functions. Parameters ---------- dtype_for_all: str or numpy.dtype A string denoting a Python datatype name (e.g. int, float) or a NumPy dtype (e.g. np.int16, np.float32) to convert the data to. band_lis...
Restores original datatypes to data variables in Datasets output by mosaic functions.
def restore_or_convert_dtypes(dtype_for_all, band_list, dataset_in_dtypes, dataset_out, no_data): """ Restores original datatypes to data variables in Datasets output by mosaic functions. Parameters ---------- dtype_for_all: str or numpy.dtype A string denoting a Python datatype name (e...
[ "def", "restore_or_convert_dtypes", "(", "dtype_for_all", ",", "band_list", ",", "dataset_in_dtypes", ",", "dataset_out", ",", "no_data", ")", ":", "if", "dtype_for_all", "is", "not", "None", ":", "# Integer types can't represent nan.", "if", "np", ".", "issubdtype", ...
[ 488, 0 ]
[ 521, 22 ]
python
en
['en', 'error', 'th']
False
CalculateGeneratorInputInfo
(params)
Calculate the generator specific info that gets fed to input (called by gyp).
Calculate the generator specific info that gets fed to input (called by gyp).
def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) if generator_flags.get('adjust_static_libraries', False): global generator_wants_static_library_dependencies_adjusted generator...
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "if", "generator_flags", ".", "get", "(", "'adjust_static_libraries'", ",", "False", ")", ":", "global", ...
[ 53, 0 ]
[ 71, 3 ]
python
en
['en', 'en', 'en']
True
features
(image, channel, levels=9, start_size=(dim_rows, dim_cols), )
Extracts features by down-scaling the image levels times, transforms the image by applying the function channel to each scaled version and computing the difference between the scaled, transformed versions. image : the image channel : a function which transforms the image into another image of ...
Extracts features by down-scaling the image levels times, transforms the image by applying the function channel to each scaled version and computing the difference between the scaled, transformed versions. image : the image channel : a function which transforms the image into another image of ...
def features(image, channel, levels=9, start_size=(dim_rows, dim_cols), ): #def features(image, channel, levels=9, start_size=(1983, 1088), ): """ Extracts features by down-scaling the image levels times, transforms the image by applying the function channel to each scaled version and computing the difference be...
[ "def", "features", "(", "image", ",", "channel", ",", "levels", "=", "9", ",", "start_size", "=", "(", "dim_rows", ",", "dim_cols", ")", ",", ")", ":", "#def features(image, channel, levels=9, start_size=(1983, 1088), ):", "image", "=", "channel", "(", "image", ...
[ 23, 0 ]
[ 61, 16 ]
python
en
['en', 'error', 'th']
False
intensity
(image)
Converts a color image into grayscale. Used as `channel' argument to function `features'
Converts a color image into grayscale. Used as `channel' argument to function `features'
def intensity(image): """ Converts a color image into grayscale. Used as `channel' argument to function `features' """ return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
[ "def", "intensity", "(", "image", ")", ":", "return", "cv2", ".", "cvtColor", "(", "image", ",", "cv2", ".", "COLOR_RGB2GRAY", ")" ]
[ 63, 0 ]
[ 68, 47 ]
python
en
['en', 'error', 'th']
False
makeGaborFilter
(dims, lambd, theta, psi, sigma, gamma)
Creates a Gabor filter (an array) with parameters labmbd, theta, psi, sigma, and gamma of size dims. Returns a function which can be passed to `features' as `channel' argument. In some versions of OpenCV, sizes greater than (11,11) will lead to segfaults (see http://code.opencv.org/issues/2644).
Creates a Gabor filter (an array) with parameters labmbd, theta, psi, sigma, and gamma of size dims. Returns a function which can be passed to `features' as `channel' argument. In some versions of OpenCV, sizes greater than (11,11) will lead to segfaults (see http://code.opencv.org/issues/2644).
def makeGaborFilter(dims, lambd, theta, psi, sigma, gamma): """ Creates a Gabor filter (an array) with parameters labmbd, theta, psi, sigma, and gamma of size dims. Returns a function which can be passed to `features' as `channel' argument. In some versions of OpenCV, sizes greater than (11,11) will lead to...
[ "def", "makeGaborFilter", "(", "dims", ",", "lambd", ",", "theta", ",", "psi", ",", "sigma", ",", "gamma", ")", ":", "def", "xpf", "(", "i", ",", "j", ")", ":", "return", "i", "*", "math", ".", "cos", "(", "theta", ")", "+", "j", "*", "math", ...
[ 70, 0 ]
[ 95, 17 ]
python
en
['en', 'error', 'th']
False
intensityConspicuity
(image)
Creates the conspicuity map for the channel `intensity'.
Creates the conspicuity map for the channel `intensity'.
def intensityConspicuity(image): """ Creates the conspicuity map for the channel `intensity'. """ fs = features(image = im, channel = intensity) return sumNormalizedFeatures(fs)
[ "def", "intensityConspicuity", "(", "image", ")", ":", "fs", "=", "features", "(", "image", "=", "im", ",", "channel", "=", "intensity", ")", "return", "sumNormalizedFeatures", "(", "fs", ")" ]
[ 97, 0 ]
[ 102, 33 ]
python
en
['en', 'error', 'th']
False
gaborConspicuity
(image, steps)
Creates the conspicuity map for the channel `orientations'.
Creates the conspicuity map for the channel `orientations'.
def gaborConspicuity(image, steps): """ Creates the conspicuity map for the channel `orientations'. """ # gaborConspicuity_ = numpy.zeros((1088, 1983), numpy.uint8) gaborConspicuity_ = numpy.zeros((dim_cols, dim_rows), numpy.uint8) for step in range(steps): theta = step * (math.pi/steps) gaborFilter = makeGa...
[ "def", "gaborConspicuity", "(", "image", ",", "steps", ")", ":", "# gaborConspicuity_ = numpy.zeros((1088, 1983), numpy.uint8)", "gaborConspicuity_", "=", "numpy", ".", "zeros", "(", "(", "dim_cols", ",", "dim_rows", ")", ",", "numpy", ".", "uint8", ")", "for", "s...
[ 104, 0 ]
[ 117, 25 ]
python
en
['en', 'error', 'th']
False
rgConspicuity
(image)
Creates the conspicuity map for the sub channel `red-green conspicuity'. of the color channel.
Creates the conspicuity map for the sub channel `red-green conspicuity'. of the color channel.
def rgConspicuity(image): """ Creates the conspicuity map for the sub channel `red-green conspicuity'. of the color channel. """ def rg(image): r,g,_,__ = cv2.split(image) return cv2.absdiff(r,g) fs = features(image = image, channel = rg) return sumNormalizedFeatures(fs)
[ "def", "rgConspicuity", "(", "image", ")", ":", "def", "rg", "(", "image", ")", ":", "r", ",", "g", ",", "_", ",", "__", "=", "cv2", ".", "split", "(", "image", ")", "return", "cv2", ".", "absdiff", "(", "r", ",", "g", ")", "fs", "=", "featur...
[ 119, 0 ]
[ 128, 33 ]
python
en
['en', 'error', 'th']
False
byConspicuity
(image)
Creates the conspicuity map for the sub channel `blue-yellow conspicuity'. of the color channel.
Creates the conspicuity map for the sub channel `blue-yellow conspicuity'. of the color channel.
def byConspicuity(image): """ Creates the conspicuity map for the sub channel `blue-yellow conspicuity'. of the color channel. """ def by(image): _,__,b,y = cv2.split(image) return cv2.absdiff(b,y) fs = features(image = image, channel = by) return sumNormalizedFeatures(fs)
[ "def", "byConspicuity", "(", "image", ")", ":", "def", "by", "(", "image", ")", ":", "_", ",", "__", ",", "b", ",", "y", "=", "cv2", ".", "split", "(", "image", ")", "return", "cv2", ".", "absdiff", "(", "b", ",", "y", ")", "fs", "=", "featur...
[ 130, 0 ]
[ 139, 33 ]
python
en
['en', 'error', 'th']
False
sumNormalizedFeatures
(features, levels=9, startSize=(dim_rows*8, dim_cols*8))
Normalizes the feature maps in argument features and combines them into one. Arguments: features : list of feature maps (images) levels : the levels of the Gaussian pyramid used to calculate the feature maps. startSize : the base size of the Gaussian pyramit used to calculate the feature ma...
Normalizes the feature maps in argument features and combines them into one. Arguments: features : list of feature maps (images) levels : the levels of the Gaussian pyramid used to calculate the feature maps. startSize : the base size of the Gaussian pyramit used to calculate the feature ma...
def sumNormalizedFeatures(features, levels=9, startSize=(dim_rows*8, dim_cols*8)): # def sumNormalizedFeatures(features, levels=9, startSize=(1983*8, 1088*8)): """ Normalizes the feature maps in argument features and combines them into one. Arguments: features : list of feature maps (images) levels : the le...
[ "def", "sumNormalizedFeatures", "(", "features", ",", "levels", "=", "9", ",", "startSize", "=", "(", "dim_rows", "*", "8", ",", "dim_cols", "*", "8", ")", ")", ":", "# def sumNormalizedFeatures(features, levels=9, startSize=(1983*8, 1088*8)):", "commonWidth", "=", ...
[ 141, 0 ]
[ 162, 13 ]
python
en
['en', 'error', 'th']
False
N
(image)
Normalization parameter as per Itti et al. (1998). returns a normalized feature map image.
Normalization parameter as per Itti et al. (1998). returns a normalized feature map image.
def N(image): """ Normalization parameter as per Itti et al. (1998). returns a normalized feature map image. """ M = 8. # an arbitrary global maximum to which the image is scaled. # (When saving saliency maps as images, pixel values may become # too large or too small for the chosen image format depending ...
[ "def", "N", "(", "image", ")", ":", "M", "=", "8.", "# an arbitrary global maximum to which the image is scaled.", "# (When saving saliency maps as images, pixel values may become", "# too large or too small for the chosen image format depending", "# on this constant)", "image", "=", "...
[ 164, 0 ]
[ 182, 27 ]
python
en
['en', 'error', 'th']
False
makeNormalizedColorChannels
(image, thresholdRatio=10.)
Creates a version of the (3-channel color) input image in which each of the (4) channels is normalized. Implements color opponencies as per Itti et al. (1998). Arguments: image : input image (3 color channels) thresholdRatio : the threshold below which to set all color values to zero. Return...
Creates a version of the (3-channel color) input image in which each of the (4) channels is normalized. Implements color opponencies as per Itti et al. (1998). Arguments: image : input image (3 color channels) thresholdRatio : the threshold below which to set all color values to zero. Return...
def makeNormalizedColorChannels(image, thresholdRatio=10.): """ Creates a version of the (3-channel color) input image in which each of the (4) channels is normalized. Implements color opponencies as per Itti et al. (1998). Arguments: image : input image (3 color channels) thresholdRatio : the thresho...
[ "def", "makeNormalizedColorChannels", "(", "image", ",", "thresholdRatio", "=", "10.", ")", ":", "intens", "=", "intensity", "(", "image", ")", "threshold", "=", "intens", ".", "max", "(", ")", "/", "thresholdRatio", "logger", ".", "debug", "(", "\"Threshold...
[ 184, 0 ]
[ 216, 13 ]
python
en
['en', 'error', 'th']
False
markMaxima
(saliency)
Mark the maxima in a saliency map (a gray-scale image).
Mark the maxima in a saliency map (a gray-scale image).
def markMaxima(saliency): """ Mark the maxima in a saliency map (a gray-scale image). """ maxima = maximum_filter(saliency, size=(5, 5)) maxima = numpy.array(saliency == maxima, dtype=numpy.float64) * 255 g = cv2.max(saliency, maxima) r = saliency b = saliency marked = cv2.merge((b,g,r)) return marked
[ "def", "markMaxima", "(", "saliency", ")", ":", "maxima", "=", "maximum_filter", "(", "saliency", ",", "size", "=", "(", "5", ",", "5", ")", ")", "maxima", "=", "numpy", ".", "array", "(", "saliency", "==", "maxima", ",", "dtype", "=", "numpy", ".", ...
[ 218, 0 ]
[ 228, 14 ]
python
en
['en', 'error', 'th']
False
uplift_tree_string
(decisionTree, x_names)
Convert the tree to string for print. Args ---- decisionTree : object object of DecisionTree class x_names : list List of feature names Returns ------- A string representation of the tree.
Convert the tree to string for print.
def uplift_tree_string(decisionTree, x_names): ''' Convert the tree to string for print. Args ---- decisionTree : object object of DecisionTree class x_names : list List of feature names Returns ------- A string representation of the tree. ''' # Column He...
[ "def", "uplift_tree_string", "(", "decisionTree", ",", "x_names", ")", ":", "# Column Heading", "dcHeadings", "=", "{", "}", "for", "i", ",", "szY", "in", "enumerate", "(", "x_names", "+", "[", "'treatment_group_key'", "]", ")", ":", "szCol", "=", "'Column %...
[ 10, 0 ]
[ 49, 33 ]
python
en
['en', 'error', 'th']
False
uplift_tree_plot
(decisionTree, x_names)
Convert the tree to dot graph for plots. Args ---- decisionTree : object object of DecisionTree class x_names : list List of feature names Returns ------- Dot class representing the tree graph.
Convert the tree to dot graph for plots.
def uplift_tree_plot(decisionTree, x_names): ''' Convert the tree to dot graph for plots. Args ---- decisionTree : object object of DecisionTree class x_names : list List of feature names Returns ------- Dot class representing the tree graph. ''' # Column...
[ "def", "uplift_tree_plot", "(", "decisionTree", ",", "x_names", ")", ":", "# Column Heading", "dcHeadings", "=", "{", "}", "for", "i", ",", "szY", "in", "enumerate", "(", "x_names", "+", "[", "'treatment_group_key'", "]", ")", ":", "szCol", "=", "'Column %d'...
[ 52, 0 ]
[ 188, 16 ]
python
en
['en', 'error', 'th']
False
ColumnRuleFollowers._helper
(x, rule)
Helper function since Python doesn't like multiline functions
Helper function since Python doesn't like multiline functions
def _helper(x, rule): """Helper function since Python doesn't like multiline functions""" strings = {} ldict = {} names = "" if x is None: x = "" if not isinstance(x, str): raise TypeError( "Column values must be strings in order to...
[ "def", "_helper", "(", "x", ",", "rule", ")", ":", "strings", "=", "{", "}", "ldict", "=", "{", "}", "names", "=", "\"\"", "if", "x", "is", "None", ":", "x", "=", "\"\"", "if", "not", "isinstance", "(", "x", ",", "str", ")", ":", "raise", "Ty...
[ 62, 4 ]
[ 84, 30 ]
python
en
['en', 'en', 'en']
True
reverse_array_dict
(dictionary)
Returns a reversed version a dictionary of keys to list-like objects. Each value in each list-like becomes a key in the returned dictionary mapping to its key in the provided dictionary.
Returns a reversed version a dictionary of keys to list-like objects. Each value in each list-like becomes a key in the returned dictionary mapping to its key in the provided dictionary.
def reverse_array_dict(dictionary): """ Returns a reversed version a dictionary of keys to list-like objects. Each value in each list-like becomes a key in the returned dictionary mapping to its key in the provided dictionary. """ return_dict = {} for label, values in dictionary.items(): ...
[ "def", "reverse_array_dict", "(", "dictionary", ")", ":", "return_dict", "=", "{", "}", "for", "label", ",", "values", "in", "dictionary", ".", "items", "(", ")", ":", "for", "value", "in", "values", ":", "return_dict", "[", "value", "]", "=", "label", ...
[ 35, 0 ]
[ 44, 22 ]
python
en
['en', 'error', 'th']
False
list_prod
(lst)
Takes the product of elements in a list.
Takes the product of elements in a list.
def list_prod(lst): """Takes the product of elements in a list.""" return functools.reduce(operator.mul, lst)
[ "def", "list_prod", "(", "lst", ")", ":", "return", "functools", ".", "reduce", "(", "operator", ".", "mul", ",", "lst", ")" ]
[ 46, 0 ]
[ 48, 46 ]
python
en
['en', 'en', 'en']
True
check_for_float
(array)
Check if a NumPy array-like contains floats. Parameters ---------- array : numpy.ndarray or convertible The array to check.
Check if a NumPy array-like contains floats.
def check_for_float(array): """ Check if a NumPy array-like contains floats. Parameters ---------- array : numpy.ndarray or convertible The array to check. """ try: return array.dtype.kind == 'f' except AttributeError: # in case it's not a numpy array it will pro...
[ "def", "check_for_float", "(", "array", ")", ":", "try", ":", "return", "array", ".", "dtype", ".", "kind", "==", "'f'", "except", "AttributeError", ":", "# in case it's not a numpy array it will probably have no dtype.", "return", "np", ".", "asarray", "(", "array"...
[ 50, 0 ]
[ 63, 68 ]
python
en
['en', 'error', 'th']
False
create_cfmask_clean_mask
(cfmask)
Description: Create a clean mask for clear land/water pixels, i.e. mask out shadow, snow, cloud, and no data ----- Input: cfmask (xarray) - cf_mask from the ledaps products Output: clean_mask (boolean numpy array) - clear land/water mask
Description: Create a clean mask for clear land/water pixels, i.e. mask out shadow, snow, cloud, and no data ----- Input: cfmask (xarray) - cf_mask from the ledaps products Output: clean_mask (boolean numpy array) - clear land/water mask
def create_cfmask_clean_mask(cfmask): """ Description: Create a clean mask for clear land/water pixels, i.e. mask out shadow, snow, cloud, and no data ----- Input: cfmask (xarray) - cf_mask from the ledaps products Output: clean_mask (boolean numpy array) - clear land/water m...
[ "def", "create_cfmask_clean_mask", "(", "cfmask", ")", ":", "#########################", "# cfmask values: #", "# 0 - clear #", "# 1 - water #", "# 2 - cloud shadow #", "# 3 - snow #", "# 4 - cloud #", "# 255 - fill #"...
[ 65, 0 ]
[ 88, 28 ]
python
en
['en', 'error', 'th']
False
create_default_clean_mask
(dataset_in)
Description: Creates a data mask that masks nothing. ----- Inputs: dataset_in (xarray.Dataset) - dataset retrieved from the Data Cube. Throws: ValueError - if dataset_in is an empty xarray.Dataset.
Description: Creates a data mask that masks nothing. ----- Inputs: dataset_in (xarray.Dataset) - dataset retrieved from the Data Cube. Throws: ValueError - if dataset_in is an empty xarray.Dataset.
def create_default_clean_mask(dataset_in): """ Description: Creates a data mask that masks nothing. ----- Inputs: dataset_in (xarray.Dataset) - dataset retrieved from the Data Cube. Throws: ValueError - if dataset_in is an empty xarray.Dataset. """ data_vars = dataset...
[ "def", "create_default_clean_mask", "(", "dataset_in", ")", ":", "data_vars", "=", "dataset_in", ".", "data_vars", "if", "len", "(", "data_vars", ")", "!=", "0", ":", "first_data_var", "=", "next", "(", "iter", "(", "data_vars", ")", ")", "clean_mask", "=", ...
[ 90, 0 ]
[ 106, 53 ]
python
en
['en', 'error', 'th']
False
get_spatial_ref
(crs)
Description: Get the spatial reference of a given crs ----- Input: crs (datacube.model.CRS) - Example: CRS('EPSG:4326') Output: ref (str) - spatial reference of given crs
Description: Get the spatial reference of a given crs ----- Input: crs (datacube.model.CRS) - Example: CRS('EPSG:4326') Output: ref (str) - spatial reference of given crs
def get_spatial_ref(crs): """ Description: Get the spatial reference of a given crs ----- Input: crs (datacube.model.CRS) - Example: CRS('EPSG:4326') Output: ref (str) - spatial reference of given crs """ crs_str = str(crs) epsg_code = int(crs_str.split(':')[1]) re...
[ "def", "get_spatial_ref", "(", "crs", ")", ":", "crs_str", "=", "str", "(", "crs", ")", "epsg_code", "=", "int", "(", "crs_str", ".", "split", "(", "':'", ")", "[", "1", "]", ")", "ref", "=", "osr", ".", "SpatialReference", "(", ")", "ref", ".", ...
[ 108, 0 ]
[ 123, 19 ]
python
en
['en', 'error', 'th']
False
get_spatial_ref
(crs)
Description: Get the spatial reference of a given crs ----- Input: crs (datacube.model.CRS) - Example: CRS('EPSG:4326') Output: ref (str) - spatial reference of given crs
Description: Get the spatial reference of a given crs ----- Input: crs (datacube.model.CRS) - Example: CRS('EPSG:4326') Output: ref (str) - spatial reference of given crs
def get_spatial_ref(crs): """ Description: Get the spatial reference of a given crs ----- Input: crs (datacube.model.CRS) - Example: CRS('EPSG:4326') Output: ref (str) - spatial reference of given crs """ crs_str = str(crs) epsg_code = int(crs_str.split(':')[1]) re...
[ "def", "get_spatial_ref", "(", "crs", ")", ":", "crs_str", "=", "str", "(", "crs", ")", "epsg_code", "=", "int", "(", "crs_str", ".", "split", "(", "':'", ")", "[", "1", "]", ")", "ref", "=", "osr", ".", "SpatialReference", "(", ")", "ref", ".", ...
[ 126, 0 ]
[ 141, 19 ]
python
en
['en', 'error', 'th']
False
perform_timeseries_analysis
(dataset_in, band_name, intermediate_product=None, no_data=-9999, operation="mean")
Description: ----- Input: dataset_in (xarray.DataSet) - dataset with one variable to perform timeseries on band_name: name of the band to create stats for. intermediate_product: result of this function for previous data, to be combined here Output: dataset_out (xarray.DataSet) ...
Description:
def perform_timeseries_analysis(dataset_in, band_name, intermediate_product=None, no_data=-9999, operation="mean"): """ Description: ----- Input: dataset_in (xarray.DataSet) - dataset with one variable to perform timeseries on band_name: name of the band to create stats for. intermedi...
[ "def", "perform_timeseries_analysis", "(", "dataset_in", ",", "band_name", ",", "intermediate_product", "=", "None", ",", "no_data", "=", "-", "9999", ",", "operation", "=", "\"mean\"", ")", ":", "assert", "operation", "in", "[", "'mean'", ",", "'max'", ",", ...
[ 144, 0 ]
[ 192, 22 ]
python
en
['en', 'error', 'th']
False
nan_to_num
(data, number)
Converts all nan values in `data` to `number`. Parameters ---------- data: xarray.Dataset or xarray.DataArray
Converts all nan values in `data` to `number`.
def nan_to_num(data, number): """ Converts all nan values in `data` to `number`. Parameters ---------- data: xarray.Dataset or xarray.DataArray """ if isinstance(data, xr.Dataset): for key in list(data.data_vars): data[key].values[np.isnan(data[key].values)] = number ...
[ "def", "nan_to_num", "(", "data", ",", "number", ")", ":", "if", "isinstance", "(", "data", ",", "xr", ".", "Dataset", ")", ":", "for", "key", "in", "list", "(", "data", ".", "data_vars", ")", ":", "data", "[", "key", "]", ".", "values", "[", "np...
[ 195, 0 ]
[ 207, 51 ]
python
en
['en', 'error', 'th']
False
clear_attrs
(dataset)
Clear out all attributes on an xarray dataset to write to disk.
Clear out all attributes on an xarray dataset to write to disk.
def clear_attrs(dataset): """Clear out all attributes on an xarray dataset to write to disk.""" dataset.attrs = collections.OrderedDict() for band in dataset.data_vars: dataset[band].attrs = collections.OrderedDict()
[ "def", "clear_attrs", "(", "dataset", ")", ":", "dataset", ".", "attrs", "=", "collections", ".", "OrderedDict", "(", ")", "for", "band", "in", "dataset", ".", "data_vars", ":", "dataset", "[", "band", "]", ".", "attrs", "=", "collections", ".", "Ordered...
[ 210, 0 ]
[ 214, 55 ]
python
en
['en', 'en', 'en']
True
create_bit_mask
(data_array, valid_bits, no_data=-9999)
Create a boolean bit mask from a list of valid bits Args: data_array: xarray data array to extract bit information for. valid_bits: array of ints representing what bits should be considered valid. no_data: no_data value for the data array. Returns: Boolean mask signifying valid...
Create a boolean bit mask from a list of valid bits
def create_bit_mask(data_array, valid_bits, no_data=-9999): """Create a boolean bit mask from a list of valid bits Args: data_array: xarray data array to extract bit information for. valid_bits: array of ints representing what bits should be considered valid. no_data: no_data value for ...
[ "def", "create_bit_mask", "(", "data_array", ",", "valid_bits", ",", "no_data", "=", "-", "9999", ")", ":", "assert", "isinstance", "(", "valid_bits", ",", "list", ")", "and", "isinstance", "(", "valid_bits", "[", "0", "]", ",", "int", ")", ",", "\"Valid...
[ 217, 0 ]
[ 233, 28 ]
python
en
['en', 'en', 'en']
True
add_timestamp_data_to_xr
(dataset)
Add timestamp data to an xarray dataset using the time dimension. Adds both a timestamp and a human readable date int to a dataset - int32 format required. modifies the dataset in place.
Add timestamp data to an xarray dataset using the time dimension.
def add_timestamp_data_to_xr(dataset): """Add timestamp data to an xarray dataset using the time dimension. Adds both a timestamp and a human readable date int to a dataset - int32 format required. modifies the dataset in place. """ dims_data_var = list(dataset.data_vars)[0] timestamp_data = n...
[ "def", "add_timestamp_data_to_xr", "(", "dataset", ")", ":", "dims_data_var", "=", "list", "(", "dataset", ".", "data_vars", ")", "[", "0", "]", "timestamp_data", "=", "np", ".", "full", "(", "dataset", "[", "dims_data_var", "]", ".", "values", ".", "shape...
[ 236, 0 ]
[ 261, 38 ]
python
en
['en', 'en', 'en']
True
write_geotiff_from_xr
(tif_path, dataset, bands, no_data=-9999, crs="EPSG:4326")
Write a geotiff from an xarray dataset. Args: tif_path: path for the tif to be written to. dataset: xarray dataset bands: list of strings representing the bands in the order they should be written no_data: nodata value for the dataset crs: requested crs.
Write a geotiff from an xarray dataset.
def write_geotiff_from_xr(tif_path, dataset, bands, no_data=-9999, crs="EPSG:4326"): """Write a geotiff from an xarray dataset. Args: tif_path: path for the tif to be written to. dataset: xarray dataset bands: list of strings representing the bands in the order they should be written ...
[ "def", "write_geotiff_from_xr", "(", "tif_path", ",", "dataset", ",", "bands", ",", "no_data", "=", "-", "9999", ",", "crs", "=", "\"EPSG:4326\"", ")", ":", "assert", "isinstance", "(", "bands", ",", "list", ")", ",", "\"Bands must a list of strings\"", "asser...
[ 264, 0 ]
[ 290, 19 ]
python
en
['en', 'en', 'en']
True
write_png_from_xr
(png_path, dataset, bands, png_filled_path=None, fill_color='red', scale=None, low_res=False, no_data=-9999, crs="EPSG:4326")
Write a rgb png from an xarray dataset. Args: png_path: path for the png to be written to. dataset: dataset to use for the png creation. bands: a list of three strings representing the bands and their order png_filled_path: optional png with no_data values filled fill_color:...
Write a rgb png from an xarray dataset.
def write_png_from_xr(png_path, dataset, bands, png_filled_path=None, fill_color='red', scale=None, low_res=False, no_data=-9999, crs="EPSG:4326"): """Write a rgb png from an xarray dataset. Args: png_path: path for the png to be written to. dataset: dataset to use for the...
[ "def", "write_png_from_xr", "(", "png_path", ",", "dataset", ",", "bands", ",", "png_filled_path", "=", "None", ",", "fill_color", "=", "'red'", ",", "scale", "=", "None", ",", "low_res", "=", "False", ",", "no_data", "=", "-", "9999", ",", "crs", "=", ...
[ 293, 0 ]
[ 330, 23 ]
python
en
['en', 'en', 'en']
True
write_single_band_png_from_xr
(png_path, dataset, band, color_scale=None, fill_color=None, interpolate=True, no_data=-9999, crs="EPSG:4326")
Write a pseudocolor png from an xarray dataset. Args: png_path: path for the png to be written to. dataset: dataset to use for the png creation. band: The band to write to a png png_filled_path: optional png with no_data values filled fill_color: color to use as the no_data ...
Write a pseudocolor png from an xarray dataset.
def write_single_band_png_from_xr(png_path, dataset, band, color_scale=None, fill_color=None, interpolate=True, no_data=-9999, crs="EPSG:4326"): """Write a pseudocolor png from an xarray dataset. Args: png_path: path for the png to be written to. dataset: datas...
[ "def", "write_single_band_png_from_xr", "(", "png_path", ",", "dataset", ",", "band", ",", "color_scale", "=", "None", ",", "fill_color", "=", "None", ",", "interpolate", "=", "True", ",", "no_data", "=", "-", "9999", ",", "crs", "=", "\"EPSG:4326\"", ")", ...
[ 333, 0 ]
[ 365, 23 ]
python
en
['en', 'en', 'en']
True
_get_transform_from_xr
(dataset)
Create a geotransform from an xarray dataset.
Create a geotransform from an xarray dataset.
def _get_transform_from_xr(dataset): """Create a geotransform from an xarray dataset. """ from rasterio.transform import from_bounds geotransform = from_bounds(dataset.longitude[0], dataset.latitude[-1], dataset.longitude[-1], dataset.latitude[0], len(dataset.longitude), ...
[ "def", "_get_transform_from_xr", "(", "dataset", ")", ":", "from", "rasterio", ".", "transform", "import", "from_bounds", "geotransform", "=", "from_bounds", "(", "dataset", ".", "longitude", "[", "0", "]", ",", "dataset", ".", "latitude", "[", "-", "1", "]"...
[ 367, 0 ]
[ 374, 23 ]
python
en
['en', 'lb', 'en']
True
ignore_warnings
(func, *args, **kwargs)
Runs a function while ignoring warnings
Runs a function while ignoring warnings
def ignore_warnings(func, *args, **kwargs): """Runs a function while ignoring warnings""" with warnings.catch_warnings(): warnings.simplefilter("ignore") ret = func(*args, **kwargs) return ret
[ "def", "ignore_warnings", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "ret", "=", "func", "(", "*", "args", ",", ...
[ 382, 0 ]
[ 387, 14 ]
python
en
['en', 'en', 'en']
True