INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Evaluate the XPath Location Path in the given context.
def xpathEval(self, str): """Evaluate the XPath Location Path in the given context. """ ret = libxml2mod.xmlXPathEval(str, self._o) if ret is None:raise xpathError('xmlXPathEval() failed') return xpathObjectRet(ret)
Evaluate the XPath expression in the given context.
def xpathEvalExpression(self, str): """Evaluate the XPath expression in the given context. """ ret = libxml2mod.xmlXPathEvalExpression(str, self._o) if ret is None:raise xpathError('xmlXPathEvalExpression() failed') return xpathObjectRet(ret)
Create a new xmlXPathParserContext
def xpathNewParserContext(self, str): """Create a new xmlXPathParserContext """ ret = libxml2mod.xmlXPathNewParserContext(str, self._o) if ret is None:raise xpathError('xmlXPathNewParserContext() failed') __tmp = xpathParserContext(_obj=ret) return __tmp
Search in the namespace declaration array of the context for the given namespace name associated to the given prefix
def xpathNsLookup(self, prefix): """Search in the namespace declaration array of the context for the given namespace name associated to the given prefix """ ret = libxml2mod.xmlXPathNsLookup(self._o, prefix) return ret
Register a new namespace. If @ns_uri is None it unregisters the namespace
def xpathRegisterNs(self, prefix, ns_uri): """Register a new namespace. If @ns_uri is None it unregisters the namespace """ ret = libxml2mod.xmlXPathRegisterNs(self._o, prefix, ns_uri) return ret
Search in the Variable array of the context for the given variable value.
def xpathVariableLookup(self, name): """Search in the Variable array of the context for the given variable value. """ ret = libxml2mod.xmlXPathVariableLookup(self._o, name) if ret is None:raise xpathError('xmlXPathVariableLookup() failed') return xpathObjectRet(ret)
Search in the Variable array of the context for the given variable value.
def xpathVariableLookupNS(self, name, ns_uri): """Search in the Variable array of the context for the given variable value. """ ret = libxml2mod.xmlXPathVariableLookupNS(self._o, name, ns_uri) if ret is None:raise xpathError('xmlXPathVariableLookupNS() failed') return xpathObj...
Evaluate the XPath Location Path in the given context.
def xpointerEval(self, str): """Evaluate the XPath Location Path in the given context. """ ret = libxml2mod.xmlXPtrEval(str, self._o) if ret is None:raise treeError('xmlXPtrEval() failed') return xpathObjectRet(ret)
Get the xpathContext from an xpathParserContext
def context(self): """Get the xpathContext from an xpathParserContext """ ret = libxml2mod.xmlXPathParserGetContext(self._o) if ret is None:raise xpathError('xmlXPathParserGetContext() failed') __tmp = xpathContext(_obj=ret) return __tmp
Implement the compare operation on XPath objects: @arg1 < @arg2 (1, 1, ... @arg1 <= @arg2 (1, 0, ... @arg1 > @arg2 (0, 1, ... @arg1 >= @arg2 (0, 0, ... When neither object to be compared is a node-set and the operator is <=, <, >=, >, then the objects are compared by ...
def xpathCompareValues(self, inf, strict): """Implement the compare operation on XPath objects: @arg1 < @arg2 (1, 1, ... @arg1 <= @arg2 (1, 0, ... @arg1 > @arg2 (0, 1, ... @arg1 >= @arg2 (0, 0, ... When neither object to be compared is a node-set and the operat...
Traversal function for the "ancestor" direction the ancestor axis contains the ancestors of the context node; the ancestors of the context node consist of the parent of context node and the parent's parent and so on; the nodes are ordered in reverse document order; thus the paren...
def xpathNextAncestor(self, cur): """Traversal function for the "ancestor" direction the ancestor axis contains the ancestors of the context node; the ancestors of the context node consist of the parent of context node and the parent's parent and so on; the nodes are orde...
Traversal function for the "ancestor-or-self" direction he ancestor-or-self axis contains the context node and ancestors of the context node in reverse document order; thus the context node is the first node on the axis, and the context node's parent the second; parent here is ...
def xpathNextAncestorOrSelf(self, cur): """Traversal function for the "ancestor-or-self" direction he ancestor-or-self axis contains the context node and ancestors of the context node in reverse document order; thus the context node is the first node on the axis, and the ...
Traversal function for the "attribute" direction TODO: support DTD inherited default attributes
def xpathNextAttribute(self, cur): """Traversal function for the "attribute" direction TODO: support DTD inherited default attributes """ if cur is None: cur__o = None else: cur__o = cur._o ret = libxml2mod.xmlXPathNextAttribute(self._o, cur__o) if ret is None:raise xp...
Traversal function for the "child" direction The child axis contains the children of the context node in document order.
def xpathNextChild(self, cur): """Traversal function for the "child" direction The child axis contains the children of the context node in document order. """ if cur is None: cur__o = None else: cur__o = cur._o ret = libxml2mod.xmlXPathNextChild(self._o, cur__o) if ret ...
Traversal function for the "descendant" direction the descendant axis contains the descendants of the context node in document order; a descendant is a child or a child of a child and so on.
def xpathNextDescendant(self, cur): """Traversal function for the "descendant" direction the descendant axis contains the descendants of the context node in document order; a descendant is a child or a child of a child and so on. """ if cur is None: cur__o = None e...
Traversal function for the "descendant-or-self" direction the descendant-or-self axis contains the context node and the descendants of the context node in document order; thus the context node is the first node on the axis, and the first child of the context node is the second no...
def xpathNextDescendantOrSelf(self, cur): """Traversal function for the "descendant-or-self" direction the descendant-or-self axis contains the context node and the descendants of the context node in document order; thus the context node is the first node on the axis, and the ...
Traversal function for the "following" direction The following axis contains all nodes in the same document as the context node that are after the context node in document order, excluding any descendants and excluding attribute nodes and namespace nodes; the nodes are ordered ...
def xpathNextFollowing(self, cur): """Traversal function for the "following" direction The following axis contains all nodes in the same document as the context node that are after the context node in document order, excluding any descendants and excluding attribute nodes...
Traversal function for the "following-sibling" direction The following-sibling axis contains the following siblings of the context node in document order.
def xpathNextFollowingSibling(self, cur): """Traversal function for the "following-sibling" direction The following-sibling axis contains the following siblings of the context node in document order. """ if cur is None: cur__o = None else: cur__o = cur._o ret = libxm...
Traversal function for the "namespace" direction the namespace axis contains the namespace nodes of the context node; the order of nodes on this axis is implementation-defined; the axis will be empty unless the context node is an element We keep the XML namespace node ...
def xpathNextNamespace(self, cur): """Traversal function for the "namespace" direction the namespace axis contains the namespace nodes of the context node; the order of nodes on this axis is implementation-defined; the axis will be empty unless the context node is an elem...
Traversal function for the "parent" direction The parent axis contains the parent of the context node, if there is one.
def xpathNextParent(self, cur): """Traversal function for the "parent" direction The parent axis contains the parent of the context node, if there is one. """ if cur is None: cur__o = None else: cur__o = cur._o ret = libxml2mod.xmlXPathNextParent(self._o, cur__o) ...
Traversal function for the "preceding" direction the preceding axis contains all nodes in the same document as the context node that are before the context node in document order, excluding any ancestors and excluding attribute nodes and namespace nodes; the nodes are ordered ...
def xpathNextPreceding(self, cur): """Traversal function for the "preceding" direction the preceding axis contains all nodes in the same document as the context node that are before the context node in document order, excluding any ancestors and excluding attribute nodes ...
Traversal function for the "preceding-sibling" direction The preceding-sibling axis contains the preceding siblings of the context node in reverse document order; the first preceding sibling is first on the axis; the sibling preceding that node is the second on the axis and so o...
def xpathNextPrecedingSibling(self, cur): """Traversal function for the "preceding-sibling" direction The preceding-sibling axis contains the preceding siblings of the context node in reverse document order; the first preceding sibling is first on the axis; the sibling p...
Traversal function for the "self" direction The self axis contains just the context node itself
def xpathNextSelf(self, cur): """Traversal function for the "self" direction The self axis contains just the context node itself """ if cur is None: cur__o = None else: cur__o = cur._o ret = libxml2mod.xmlXPathNextSelf(self._o, cur__o) if ret is None:raise xpathError('...
Formats an error message.
def xpatherror(self, file, line, no): """Formats an error message. """ libxml2mod.xmlXPatherror(self._o, file, line, no)
Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of list of tuples) A list of summary sections...
def _get_summary_struct(self): """ Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of lis...
Return a classification, for each example in the ``dataset``, using the trained logistic regression model. The output SFrame contains predictions as both class labels (0 or 1) as well as probabilities that the predicted value is the associated label. Parameters ---------- ...
def classify(self, dataset, missing_value_action='auto'): """ Return a classification, for each example in the ``dataset``, using the trained logistic regression model. The output SFrame contains predictions as both class labels (0 or 1) as well as probabilities that the predicted ...
Appends the suffix appropriate to 'type/property-set' combination to the specified name and returns the result.
def add_prefix_and_suffix(specified_name, type, property_set): """Appends the suffix appropriate to 'type/property-set' combination to the specified name and returns the result.""" property_set = b2.util.jam_to_value_maybe(property_set) suffix = "" if type: suffix = b2.build.type.generated...
Traverses the dependency graph of 'target' and return all targets that will be created before this one is created. If root of some dependency graph is found during traversal, it's either included or not, dependencing of the value of 'include_roots'. In either case, sources of root are not traver...
def traverse (target, include_roots = False, include_sources = False): """ Traverses the dependency graph of 'target' and return all targets that will be created before this one is created. If root of some dependency graph is found during traversal, it's either included or not, dependencing of the ...
Takes an 'action' instances and creates new instance of it and all produced target. The rule-name and properties are set to 'new-rule-name' and 'new-properties', if those are specified. Returns the cloned action.
def clone_action (action, new_project, new_action_name, new_properties): """Takes an 'action' instances and creates new instance of it and all produced target. The rule-name and properties are set to 'new-rule-name' and 'new-properties', if those are specified. Returns the cloned action.""" if __deb...
Registers a new virtual target. Checks if there's already registered target, with the same name, type, project and subvariant properties, and also with the same sources and equal action. If such target is found it is retured and 'target' is not registered. Otherwise, 'target' is regi...
def register (self, target): """ Registers a new virtual target. Checks if there's already registered target, with the same name, type, project and subvariant properties, and also with the same sources and equal action. If such target is found it is retured and 'target' is not registered...
Creates a virtual target with appropriate name and type from 'file'. If a target with that name in that project was already created, returns that already created target. TODO: more correct way would be to compute path to the file, based on name and source location for the...
def from_file (self, file, file_location, project): """ Creates a virtual target with appropriate name and type from 'file'. If a target with that name in that project was already created, returns that already created target. TODO: more correct way would be to compute path to...
Appends the suffix appropriate to 'type/property_set' combination to the specified name and returns the result.
def add_suffix (self, specified_name, file_type, prop_set): """ Appends the suffix appropriate to 'type/property_set' combination to the specified name and returns the result. """ assert isinstance(specified_name, basestring) assert isinstance(file_type, basestring) a...
Adds additional instances of 'VirtualTarget' that this one depends on.
def depends (self, d): """ Adds additional instances of 'VirtualTarget' that this one depends on. """ self.dependencies_ = unique (self.dependencies_ + d).sort ()
Generates all the actual targets and sets up build actions for this target. If 'scanner' is specified, creates an additional target with the same location as actual target, which will depend on the actual target and be associated with 'scanner'. That additional ...
def actualize (self, scanner = None): """ Generates all the actual targets and sets up build actions for this target. If 'scanner' is specified, creates an additional target with the same location as actual target, which will depend on the actual target and be as...
Sets the path. When generating target name, it will override any path computation from properties.
def set_path (self, path): """ Sets the path. When generating target name, it will override any path computation from properties. """ assert isinstance(path, basestring) self.path_ = os.path.normpath(path)
Sets/gets the 'root' flag. Target is root is it directly correspods to some variant of a main target.
def root (self, set = None): """ Sets/gets the 'root' flag. Target is root is it directly correspods to some variant of a main target. """ assert isinstance(set, (int, bool, type(None))) if set: self.root_ = True return self.root_
Gets or sets the subvariant which created this target. Subvariant is set when target is brought into existance, and is never changed after that. In particual, if target is shared by subvariant, only the first is stored. s: If specified, specified the value to set, which ...
def creating_subvariant (self, s = None): """ Gets or sets the subvariant which created this target. Subvariant is set when target is brought into existance, and is never changed after that. In particual, if target is shared by subvariant, only the first is stored. s: If specifi...
Helper to 'actual_name', above. Compute unique prefix used to distinguish this target from other targets with the same name which create different file.
def grist (self): """Helper to 'actual_name', above. Compute unique prefix used to distinguish this target from other targets with the same name which create different file. """ # Depending on target, there may be different approaches to generating # unique prefix...
Given the target name specified in constructor, returns the name which should be really used, by looking at the <tag> properties. The tag properties come in two flavour: - <tag>value, - <tag>@rule-name In the first case, value is just added to name In the second case,...
def __adjust_name(self, specified_name): """Given the target name specified in constructor, returns the name which should be really used, by looking at the <tag> properties. The tag properties come in two flavour: - <tag>value, - <tag>@rule-name In the first case, val...
Returns the directory for this target.
def path (self): """ Returns the directory for this target. """ if not self.path_: if self.action_: p = self.action_.properties () (target_path, relative_to_build_dir) = p.target_path () if relative_to_build_dir: # ...
Generates actual build instructions.
def actualize (self): """ Generates actual build instructions. """ if self.actualized_: return self.actualized_ = True ps = self.properties () properties = self.adjust_properties (ps) actual_targets = [] for i in self.targets (): ...
Helper for 'actualize_sources'. For each passed source, actualizes it with the appropriate scanner. Returns the actualized virtual targets.
def actualize_source_type (self, sources, prop_set): """ Helper for 'actualize_sources'. For each passed source, actualizes it with the appropriate scanner. Returns the actualized virtual targets. """ assert is_iterable_typed(sources, VirtualTarget) assert isinsta...
Creates actual jam targets for sources. Initializes two member variables: 'self.actual_sources_' -- sources which are passed to updating action 'self.dependency_only_sources_' -- sources which are made dependencies, but are not used otherwise. New values will...
def actualize_sources (self, sources, prop_set): """ Creates actual jam targets for sources. Initializes two member variables: 'self.actual_sources_' -- sources which are passed to updating action 'self.dependency_only_sources_' -- sources which are made dependencies, but ...
Returns all targets referenced by this subvariant, either directly or indirectly, and either as sources, or as dependency properties. Targets referred with dependency property are returned a properties, not targets.
def all_referenced_targets(self, result): """Returns all targets referenced by this subvariant, either directly or indirectly, and either as sources, or as dependency properties. Targets referred with dependency property are returned a properties, not targets.""" if __debug__: ...
Returns the properties which specify implicit include paths to generated headers. This traverses all targets in this subvariant, and subvariants referred by <implcit-dependecy>properties. For all targets which are of type 'target-type' (or for all targets, if 'target_type...
def implicit_includes (self, feature, target_type): """ Returns the properties which specify implicit include paths to generated headers. This traverses all targets in this subvariant, and subvariants referred by <implcit-dependecy>properties. For all targets which are of typ...
Compare if two nodes are equal.
def cmp_ast(node1, node2): ''' Compare if two nodes are equal. ''' if type(node1) != type(node2): return False if isinstance(node1, (list, tuple)): if len(node1) != len(node2): return False for left, right in zip(node1, node2): if not cmp_ast(left, ...
Creates additional files for the individual MPL-containers.
def create_more_container_files(sourceDir, suffix, maxElements, containers, containers2): """Creates additional files for the individual MPL-containers.""" # Create files for each MPL-container with 20 to 'maxElements' elements # which will be used during generation. for container in containers: ...
Creates additional source- and header-files for the numbered sequence MPL-containers.
def create_input_for_numbered_sequences(headerDir, sourceDir, containers, maxElements): """Creates additional source- and header-files for the numbered sequence MPL-containers.""" # Create additional container-list without "map". containersWithoutMap = containers[:] try: containersWithoutMap.rem...
Adjusts the limits of variadic sequence MPL-containers.
def adjust_container_limits_for_variadic_sequences(headerDir, containers, maxElements): """Adjusts the limits of variadic sequence MPL-containers.""" for container in containers: headerFile = os.path.join( headerDir, "limits", container + ".hpp" ) regexMatch = r'(define\s+BOOST_MPL_LIMIT_' + c...
Returns the (relative) path to the Boost source-directory this file is located in (if any).
def current_boost_dir(): """Returns the (relative) path to the Boost source-directory this file is located in (if any).""" # Path to directory containing this script. path = os.path.dirname( os.path.realpath(__file__) ) # Making sure it is located in "${boost-dir}/libs/mpl/preprocessed". for directo...
Converts a string into its encoded positive integer (greater zero) or throws an exception.
def to_positive_multiple_of_10(string): """Converts a string into its encoded positive integer (greater zero) or throws an exception.""" try: value = int(string) except ValueError: msg = '"%r" is not a positive multiple of 10 (greater zero).' % string raise argparse.ArgumentTypeError...
The main function.
def main(): """The main function.""" # Find the current Boost source-directory in which this script is located. sourceDir = current_boost_dir() if sourceDir == None: sourceDir = "" # Prepare and run cmdline-parser. cmdlineParser = argparse.ArgumentParser(description="A generato...
Add an inner product layer to the model. Parameters ---------- name: str The name of this layer W: numpy.array or bytes() Weight matrix of shape (output_channels, input_channels) If W is of type bytes(), i.e. quantized, other quantization related argu...
def add_inner_product(self, name, W, b, input_channels, output_channels, has_bias, input_name, output_name, **kwargs): """ Add an inner product layer to the model. Parameters ---------- name: str The name of this layer W: numpy.array...
Add a convolution layer to the network. Please see the ConvolutionLayerParams in Core ML neural network protobuf message for more information about input and output blob dimensions. Parameters ---------- name: str The name of this layer. kernel_channels: int...
def add_convolution(self, name, kernel_channels, output_channels, height, width, stride_height, stride_width, border_mode, groups, W, b, has_bias, is_deconv = False, output_shape = None, input_name = 'data', output_name = 'out', dilation_factors = [1,1], paddi...
Add resize bilinear layer to the model. A layer that resizes the input to a given spatial size using bilinear interpolation. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str ...
def add_resize_bilinear(self, name, input_name, output_name, target_height=1, target_width=1, mode='ALIGN_ENDPOINTS_MODE'): """ Add resize bilinear layer to the model. A layer that resizes the input to a given spatial size using bilinear interpolation. Parameters ...
Add crop resize layer to the model. A layer that extracts cropped spatial patches or RoIs (regions of interest) from the input and resizes them to a pre-specified size using bilinear interpolation. Note that RoI Align layer can be implemented with this layer followed by a pooling layer. Kindly r...
def add_crop_resize(self, name, input_names, output_name, target_height=1, target_width=1, mode='STRICT_ALIGN_ENDPOINTS_MODE', normalized_roi=False, box_indices_mode='CORNERS_HEIGHT_FIRST', spatial_scale=1.0)...
Format a doc-string on the fly. @arg format_dict: A dictionary to format the doc-strings Example: @add_docstring({'context': __doc_string_context}) def predict(x): ''' {context} >> model.predict(data) ''' return x
def _add_docstring(format_dict): """ Format a doc-string on the fly. @arg format_dict: A dictionary to format the doc-strings Example: @add_docstring({'context': __doc_string_context}) def predict(x): ''' {context} >> model.predict(data) '...
Serialize model summary into a dict with ordered lists of sections and section titles Parameters ---------- model : Model object sections : Ordered list of lists (sections) of tuples (field,value) [ [(field1, value1), (field2, value2)], [(field3, value3), (field4, value4)], ...
def _toolkit_serialize_summary_struct(model, sections, section_titles): """ Serialize model summary into a dict with ordered lists of sections and section titles Parameters ---------- model : Model object sections : Ordered list of lists (sections) of tuples (field,value) [ [(fi...
Finds the only column in `SFrame` with a type specified by `target_type`. If there are zero or more than one such columns, an exception will be raised. The name and type of the target column should be provided as strings for the purpose of error feedback.
def _find_only_column_of_type(sframe, target_type, type_name, col_name): """ Finds the only column in `SFrame` with a type specified by `target_type`. If there are zero or more than one such columns, an exception will be raised. The name and type of the target column should be provided as strings fo...
Finds the only column in `sframe` with a type of turicreate.Image. If there are zero or more than one image columns, an exception will be raised.
def _find_only_image_column(sframe): """ Finds the only column in `sframe` with a type of turicreate.Image. If there are zero or more than one image columns, an exception will be raised. """ from turicreate import Image return _find_only_column_of_type(sframe, target_type=Image, ...
Finds the only column that can be interpreted as a drawing feature column. A drawing column can be a stroke-based drawing column (with dtype list) or a bitmap-based drawing column (with dtype turicreate.Image) If there are zero or more than one drawing columns, an exception will be raised.
def _find_only_drawing_column(sframe): """ Finds the only column that can be interpreted as a drawing feature column. A drawing column can be a stroke-based drawing column (with dtype list) or a bitmap-based drawing column (with dtype turicreate.Image) If there are zero or more than one drawing...
Convert the Json Tree to SGraph
def _SGraphFromJsonTree(json_str): """ Convert the Json Tree to SGraph """ g = json.loads(json_str) vertices = [_Vertex(x['id'], dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id'])) for x in g['vertices']] edges = [...
Return a tuple of sections and section titles. Sections are pretty print of model coefficients Parameters ---------- top_coefs : SFrame of top k coefficients bottom_coefs : SFrame of bottom k coefficients Returns ------- (sections, section_titles) : tuple sections : list ...
def _summarize_coefficients(top_coefs, bottom_coefs): """ Return a tuple of sections and section titles. Sections are pretty print of model coefficients Parameters ---------- top_coefs : SFrame of top k coefficients bottom_coefs : SFrame of bottom k coefficients Returns ------- ...
Returns a tuple of the top k values from the positive and negative values in a SArray Parameters ---------- values : SFrame of model coefficients k: Maximum number of largest positive and k lowest negative numbers to return Returns ------- (topk_positive, bottomk_positive) : tuple ...
def _toolkit_get_topk_bottomk(values, k=5): """ Returns a tuple of the top k values from the positive and negative values in a SArray Parameters ---------- values : SFrame of model coefficients k: Maximum number of largest positive and k lowest negative numbers to return Returns -...
Extract a model summary field value
def __extract_model_summary_value(model, value): """ Extract a model summary field value """ field_value = None if isinstance(value, _precomputed_field): field_value = value.field else: field_value = model._get(value) if isinstance(field_value, float): try: ...
Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table.
def _make_repr_table_from_sframe(X): """ Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table. """ assert isinstance(X, _SFrame) column_names = X.column_names() out_data = [ [None]*len(column_names) for i in range(X.num_rows())] column_sizes = [le...
Display a toolkit repr according to some simple rules. Parameters ---------- model : Turi Create model fields: List of lists of tuples Each tuple should be (display_name, field_name), where field_name can be a string or a _precomputed_field object. section_titles: List of section...
def _toolkit_repr_print(model, fields, section_titles, width = None): """ Display a toolkit repr according to some simple rules. Parameters ---------- model : Turi Create model fields: List of lists of tuples Each tuple should be (display_name, field_name), where field_name can ...
Map returning value, if it is unity SFrame, SArray, map it
def _map_unity_proxy_to_object(value): """ Map returning value, if it is unity SFrame, SArray, map it """ vtype = type(value) if vtype in _proxy_map: return _proxy_map[vtype](value) elif vtype == list: return [_map_unity_proxy_to_object(v) for v in value] elif vtype == dict: ...
Same as select columns but redirect runtime error to ToolkitError.
def _toolkits_select_columns(dataset, columns): """ Same as select columns but redirect runtime error to ToolkitError. """ try: return dataset.select_columns(columns) except RuntimeError: missing_features = list(set(columns).difference(set(dataset.column_names()))) raise Tool...
Check if a column exists in an SFrame with error message.
def _raise_error_if_column_exists(dataset, column_name = 'dataset', dataset_variable_name = 'dataset', column_name_error_message_name = 'column_name'): """ Check if a column exists in an SFrame with error message. """ err_msg = 'The SFrame {0} must...
Check whether or not the requested option is one of the allowed values.
def _check_categorical_option_type(option_name, option_value, possible_values): """ Check whether or not the requested option is one of the allowed values. """ err_msg = '{0} is not a valid option for {1}. '.format(option_value, option_name) err_msg += ' Expected one of: '.format(possible_values) ...
Check if the input is an SArray. Provide a proper error message otherwise.
def _raise_error_if_not_sarray(dataset, variable_name="SArray"): """ Check if the input is an SArray. Provide a proper error message otherwise. """ err_msg = "Input %s is not an SArray." if not isinstance(dataset, _SArray): raise ToolkitError(err_msg % variable_name)
Check if the input is an SFrame. Provide a proper error message otherwise.
def _raise_error_if_not_sframe(dataset, variable_name="SFrame"): """ Check if the input is an SFrame. Provide a proper error message otherwise. """ err_msg = "Input %s is not an SFrame. If it is a Pandas DataFrame," err_msg += " you may use the to_sframe() function to convert it to an SFrame." ...
Check if the input is empty.
def _raise_error_if_sframe_empty(dataset, variable_name="SFrame"): """ Check if the input is empty. """ err_msg = "Input %s either has no rows or no columns. A non-empty SFrame " err_msg += "is required." if dataset.num_rows() == 0 or dataset.num_columns() == 0: raise ToolkitError(err_m...
Check if the input is an SFrame. Provide a proper error message otherwise.
def _raise_error_evaluation_metric_is_valid(metric, allowed_metrics): """ Check if the input is an SFrame. Provide a proper error message otherwise. """ err_msg = "Evaluation metric '%s' not recognized. The supported evaluation" err_msg += " metrics are (%s)." if metric not in allowed_metr...
Checks if numeric parameter is within given range
def _numeric_param_check_range(variable_name, variable_value, range_bottom, range_top): """ Checks if numeric parameter is within given range """ err_msg = "%s must be between %i and %i" if variable_value < range_bottom or variable_value > range_top: raise ToolkitError(err_msg % (variable_n...
Validate and canonicalize training and validation data. Parameters ---------- dataset : SFrame Dataset for training the model. target : string Name of the column containing the target variable. features : list[string], optional List of feature names used. validation_s...
def _validate_data(dataset, target, features=None, validation_set='auto'): """ Validate and canonicalize training and validation data. Parameters ---------- dataset : SFrame Dataset for training the model. target : string Name of the column containing the target variable. ...
Validate a row label column. If the row label is not specified, a column is created with row numbers, named with the string in the `default_label` parameter. Parameters ---------- dataset : SFrame Input dataset. label : str, optional Name of the column containing row labels. ...
def _validate_row_label(dataset, label=None, default_label='__id'): """ Validate a row label column. If the row label is not specified, a column is created with row numbers, named with the string in the `default_label` parameter. Parameters ---------- dataset : SFrame Input dataset....
Returns Mac version as a tuple of integers, making it easy to do proper version comparisons. On non-Macs, it returns an empty tuple.
def _mac_ver(): """ Returns Mac version as a tuple of integers, making it easy to do proper version comparisons. On non-Macs, it returns an empty tuple. """ import platform import sys if sys.platform == 'darwin': ver_str = platform.mac_ver()[0] return tuple([int(v) for v in v...
Print a message making it clear to the user what compute resource is used in neural network training.
def _print_neural_compute_device(cuda_gpus, use_mps, cuda_mem_req=None, has_mps_impl=True): """ Print a message making it clear to the user what compute resource is used in neural network training. """ num_cuda_gpus = len(cuda_gpus) if num_cuda_gpus >= 1: gpu_names = ', '.join(gpu['name'...
Get a proto class from the MessageFactory by name. Args: factory: a MessageFactory instance. full_name: str, the fully qualified name of the proto type. Returns: A class, for the type identified by full_name. Raises: KeyError, if the proto is not found in the factory's descriptor pool.
def _GetMessageFromFactory(factory, full_name): """Get a proto class from the MessageFactory by name. Args: factory: a MessageFactory instance. full_name: str, the fully qualified name of the proto type. Returns: A class, for the type identified by full_name. Raises: KeyError, if the proto is n...
Create a Protobuf class whose fields are basic types. Note: this doesn't validate field names! Args: fields: dict of {name: field_type} mappings for each field in the proto. If this is an OrderedDict the order will be maintained, otherwise the fields will be sorted by name. full_name: opti...
def MakeSimpleProtoClass(fields, full_name=None, pool=None): """Create a Protobuf class whose fields are basic types. Note: this doesn't validate field names! Args: fields: dict of {name: field_type} mappings for each field in the proto. If this is an OrderedDict the order will be maintained, otherw...
Populate FileDescriptorProto for MessageFactory's DescriptorPool.
def _MakeFileDescriptorProto(proto_file_name, full_name, field_items): """Populate FileDescriptorProto for MessageFactory's DescriptorPool.""" package, name = full_name.rsplit('.', 1) file_proto = descriptor_pb2.FileDescriptorProto() file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name) f...
Convert a decision tree model to protobuf format. Parameters ---------- decision_tree : DecisionTreeClassifier A trained scikit-learn tree model. input_name: str Name of the input columns. output_name: str Name of the output columns. Returns ------- model_spec...
def convert(model, input_name, output_features): """Convert a decision tree model to protobuf format. Parameters ---------- decision_tree : DecisionTreeClassifier A trained scikit-learn tree model. input_name: str Name of the input columns. output_name: str Name of the...
Returns user-defined metadata, making sure information all models should have is also available, as a dictionary
def _get_model_metadata(model_class, metadata, version=None): """ Returns user-defined metadata, making sure information all models should have is also available, as a dictionary """ from turicreate import __version__ info = { 'turicreate_version': __version__, 'type': model_cla...
Sets user-defined metadata, making sure information all models should have is also available
def _set_model_metadata(mlmodel, model_class, metadata, version=None): """ Sets user-defined metadata, making sure information all models should have is also available """ info = _get_model_metadata(model_class, metadata, version) mlmodel.user_defined_metadata.update(info)
Converts name to camel-case and returns it.
def _ToCamelCase(name): """Converts name to camel-case and returns it.""" capitalize_next = False result = [] for c in name: if c == '_': if result: capitalize_next = True elif capitalize_next: result.append(c.upper()) capitalize_next = False else: result += c # L...
Converts name to Json name and returns it.
def _ToJsonName(name): """Converts name to Json name and returns it.""" capitalize_next = False result = [] for c in name: if c == '_': capitalize_next = True elif capitalize_next: result.append(c.upper()) capitalize_next = False else: result += c return ''.join(result)
Sets the descriptor's options This function is used in generated proto2 files to update descriptor options. It must not be used outside proto2.
def _SetOptions(self, options, options_class_name): """Sets the descriptor's options This function is used in generated proto2 files to update descriptor options. It must not be used outside proto2. """ self._options = options self._options_class_name = options_class_name # Does this descr...
Retrieves descriptor options. This method returns the options set or creates the default options for the descriptor.
def GetOptions(self): """Retrieves descriptor options. This method returns the options set or creates the default options for the descriptor. """ if self._options: return self._options from google.protobuf import descriptor_pb2 try: options_class = getattr(descriptor_pb2, self._...
Copies this to the matching proto in descriptor_pb2. Args: proto: An empty proto instance from descriptor_pb2. Raises: Error: If self couldnt be serialized, due to to few constructor arguments.
def CopyToProto(self, proto): """Copies this to the matching proto in descriptor_pb2. Args: proto: An empty proto instance from descriptor_pb2. Raises: Error: If self couldnt be serialized, due to to few constructor arguments. """ if (self.file is not None and self._serialized_...
Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn't exist or the va...
def EnumValueName(self, enum, value): """Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyErr...
Given a target_reference, made in context of 'project', returns the AbstractTarget instance that is referred to, as well as properties explicitly specified for this reference.
def resolve_reference(target_reference, project): """ Given a target_reference, made in context of 'project', returns the AbstractTarget instance that is referred to, as well as properties explicitly specified for this reference. """ # Separate target name from properties override assert isinsta...
Attempts to generate the target given by target reference, which can refer both to a main target or to a file. Returns a list consisting of - usage requirements - generated virtual targets, if any target_reference: Target reference project: Project where the reference is made prop...
def generate_from_reference(target_reference, project, property_set_): """ Attempts to generate the target given by target reference, which can refer both to a main target or to a file. Returns a list consisting of - usage requirements - generated virtual targets, if any target_reference: Targe...
Registers the specified target as a main target alternatives. Returns 'target'.
def main_target_alternative (self, target): """ Registers the specified target as a main target alternatives. Returns 'target'. """ assert isinstance(target, AbstractTarget) target.project ().add_alternative (target) return target
Return the list of sources to use, if main target rule is invoked with 'sources'. If there are any objects in 'sources', they are treated as main target instances, and the name of such targets are adjusted to be '<name_of_this_target>__<name_of_source_target>'. Such renaming is disabled ...
def main_target_sources (self, sources, main_target_name, no_renaming=0): """Return the list of sources to use, if main target rule is invoked with 'sources'. If there are any objects in 'sources', they are treated as main target instances, and the name of such targets are adjusted to be...
Returns the requirement to use when declaring a main target, which are obtained by - translating all specified property paths, and - refining project requirements with the one specified for the target 'specification' are the properties xplicitly specified for a main target...
def main_target_requirements(self, specification, project): """Returns the requirement to use when declaring a main target, which are obtained by - translating all specified property paths, and - refining project requirements with the one specified for the target 'specificat...
Returns the use requirement to use when declaraing a main target, which are obtained by - translating all specified property paths, and - adding project's usage requirements specification: Use-properties explicitly specified for a main target project: ...
def main_target_usage_requirements (self, specification, project): """ Returns the use requirement to use when declaraing a main target, which are obtained by - translating all specified property paths, and - adding project's usage requirements specification: Use...
Return the default build value to use when declaring a main target, which is obtained by using specified value if not empty and parent's default build attribute otherwise. specification: Default build explicitly specified for a main target project: Project where t...
def main_target_default_build (self, specification, project): """ Return the default build value to use when declaring a main target, which is obtained by using specified value if not empty and parent's default build attribute otherwise. specification: Default build explicit...
Helper rules to detect cycles in main target references.
def start_building (self, main_target_instance): """ Helper rules to detect cycles in main target references. """ assert isinstance(main_target_instance, MainTarget) if id(main_target_instance) in self.targets_being_built_: names = [] for t in self.targets_being_b...