INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Initializes the gcc toolset for the given version. If necessary, command may be used to specify where the compiler is located. The parameter 'options' is a space-delimited list of options, each one specified as <option-name>option-value. Valid option names are: cxxflags, linkflags and li...
def init(version = None, command = None, options = None): """ Initializes the gcc toolset for the given version. If necessary, command may be used to specify where the compiler is located. The parameter 'options' is a space-delimited list of options, each one specified as <option-nam...
Now, the vendor specific flags. The parameter linker can be either gnu, darwin, osf, hpux or sun.
def init_link_flags(toolset, linker, condition): """ Now, the vendor specific flags. The parameter linker can be either gnu, darwin, osf, hpux or sun. """ toolset_link = toolset + '.link' if linker == 'gnu': # Strip the binary when no debugging is needed. We use --strip-all flag ...
Adds a dependency from 'targets' to 'sources' Both 'targets' and 'sources' can be either list of target names, or a single target name.
def add_dependency (self, targets, sources): """Adds a dependency from 'targets' to 'sources' Both 'targets' and 'sources' can be either list of target names, or a single target name. """ if isinstance (targets, str): targets = [targets] if isinstance (source...
Gets the value of `variable` on set on the first target in `targets`. Args: targets (str or list): one or more targets to get the variable from. variable (str): the name of the variable Returns: the value of `variable` set on `targets` (list) Example: ...
def get_target_variable(self, targets, variable): """Gets the value of `variable` on set on the first target in `targets`. Args: targets (str or list): one or more targets to get the variable from. variable (str): the name of the variable Returns: the value...
Sets a target variable. The 'variable' will be available to bjam when it decides where to generate targets, and will also be available to updating rule for that 'taret'.
def set_target_variable (self, targets, variable, value, append=0): """ Sets a target variable. The 'variable' will be available to bjam when it decides where to generate targets, and will also be available to updating rule for that 'taret'. """ if isinstance (targets, s...
Binds a target to the corresponding update action. If target needs to be updated, the action registered with action_name will be used. The 'action_name' must be previously registered by either 'register_action' or 'register_bjam_action' method.
def set_update_action (self, action_name, targets, sources, properties=None): """ Binds a target to the corresponding update action. If target needs to be updated, the action registered with action_name will be used. The 'action_name' must be previously registered by ...
Creates a new build engine action. Creates on bjam side an action named 'action_name', with 'command' as the command to be executed, 'bound_variables' naming the list of variables bound when the command is executed and specified flag. If 'function' is not None, it should be a ca...
def register_action (self, action_name, command='', bound_list = [], flags = [], function = None): """Creates a new build engine action. Creates on bjam side an action named 'action_name', with 'command' as the command to be executed, 'bound_variables' naming th...
Informs self that 'action_name' is declared in bjam. From this point, 'action_name' is a valid argument to the set_update_action method. The action_name should be callable in the global module of bjam.
def register_bjam_action (self, action_name, function=None): """Informs self that 'action_name' is declared in bjam. From this point, 'action_name' is a valid argument to the set_update_action method. The action_name should be callable in the global module of bjam. """ ...
Returns the pixel data stored in the Image object. Returns ------- out : numpy.array The pixel data of the Image object. It returns a multi-dimensional numpy array, where the shape of the array represents the shape of the image (height, weight, channels). ...
def pixel_data(self): """ Returns the pixel data stored in the Image object. Returns ------- out : numpy.array The pixel data of the Image object. It returns a multi-dimensional numpy array, where the shape of the array represents the shape of ...
Displays the image. Requires PIL/Pillow. Alternatively, you can create an :class:`turicreate.SArray` of this image and use py:func:`turicreate.SArray.show()` See Also -------- turicreate.image_analysis.resize Examples -------- >>> img = turicreate.Image...
def show(self): """ Displays the image. Requires PIL/Pillow. Alternatively, you can create an :class:`turicreate.SArray` of this image and use py:func:`turicreate.SArray.show()` See Also -------- turicreate.image_analysis.resize Examples -------...
Return predictions for the model. The kwargs gets passed into the model as a dictionary. Parameters ---------- data : dict[str, value] Dictionary of data to make predictions from where the keys are the names of the input features. useCPUOnly : bool ...
def predict(self, data, useCPUOnly=False, **kwargs): """ Return predictions for the model. The kwargs gets passed into the model as a dictionary. Parameters ---------- data : dict[str, value] Dictionary of data to make predictions from where the keys are ...
Visualize the model. Parameters ---------- port : int if server is to be hosted on specific localhost port input_shape_dict : dict The shapes are calculated assuming the batch and sequence are 1 i.e. (1, 1, C, H, W). If ei...
def visualize_spec(self, port=None, input_shape_dict=None): """ Visualize the model. Parameters ---------- port : int if server is to be hosted on specific localhost port input_shape_dict : dict The shapes are calculat...
Construct composite distance parameters based on selected features and their types.
def _construct_auto_distance(feature_names, column_names, column_types, sample): """ Construct composite distance parameters based on selected features and their types. """ ## Make a dictionary from the column_names and column_types col_type_dict = {k: v for k, v in zip(column_names, column_typ...
Create a nearest neighbor model, which can be searched efficiently and quickly for the nearest neighbors of a query observation. If the `method` argument is specified as `auto`, the type of model is chosen automatically based on the type of data in `dataset`. .. warning:: The 'dot_product' dis...
def create(dataset, label=None, features=None, distance=None, method='auto', verbose=True, **kwargs): """ Create a nearest neighbor model, which can be searched efficiently and quickly for the nearest neighbors of a query observation. If the `method` argument is specified as `auto`, the type ...
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...
List the fields stored in the model, including data, model, and training options. Each field can be queried with the ``get`` method. Returns ------- out : list List of fields queryable with the ``get`` method.
def _list_fields(self): """ List the fields stored in the model, including data, model, and training options. Each field can be queried with the ``get`` method. Returns ------- out : list List of fields queryable with the ``get`` method. """ o...
Return the value of a given field. The list of all queryable fields is detailed below, and can be obtained with the :func:`~turicreate.nearest_neighbors.NearestNeighborsModel._list_fields` method. +-----------------------+----------------------------------------------+ | Fi...
def _get(self, field): """ Return the value of a given field. The list of all queryable fields is detailed below, and can be obtained with the :func:`~turicreate.nearest_neighbors.NearestNeighborsModel._list_fields` method. +-----------------------+----------------------...
Return a dictionary of statistics collected during creation of the model. These statistics are also available with the ``get`` method and are described in more detail in that method's documentation. Returns ------- out : dict Dictionary of statistics compiled during ...
def _training_stats(self): """ Return a dictionary of statistics collected during creation of the model. These statistics are also available with the ``get`` method and are described in more detail in that method's documentation. Returns ------- out : dict ...
For each row of the input 'dataset', retrieve the nearest neighbors from the model's stored data. In general, the query dataset does not need to be the same as the reference data stored in the model, but if it is, the 'include_self_edges' parameter can be set to False to exclude results ...
def query(self, dataset, label=None, k=5, radius=None, verbose=True): """ For each row of the input 'dataset', retrieve the nearest neighbors from the model's stored data. In general, the query dataset does not need to be the same as the reference data stored in the model, but if ...
Construct the similarity graph on the reference dataset, which is already stored in the model. This is conceptually very similar to running `query` with the reference set, but this method is optimized for the purpose, syntactically simpler, and automatically removes self-edges. ...
def similarity_graph(self, k=5, radius=None, include_self_edges=False, output_type='SGraph', verbose=True): """ Construct the similarity graph on the reference dataset, which is already stored in the model. This is conceptually very similar to running `query` wit...
Randomly split an SFrame into two SFrames based on the `session_id` such that one split contains data for a `fraction` of the sessions while the second split contains all data for the rest of the sessions. Parameters ---------- dataset : SFrame Dataset to split. It must contain a column of ...
def random_split_by_session(dataset, session_id, fraction=0.9, seed=None): """ Randomly split an SFrame into two SFrames based on the `session_id` such that one split contains data for a `fraction` of the sessions while the second split contains all data for the rest of the sessions. Parameters ...
Reads the MS Build XML file at the path and returns its contents. Keyword arguments: values -- The map to append the contents to (default {})
def read_msbuild_xml(path, values={}): """Reads the MS Build XML file at the path and returns its contents. Keyword arguments: values -- The map to append the contents to (default {}) """ # Attempt to read the file contents try: document = parse(path) except Exception as e: ...
Reads the MS Build JSON file at the path and returns its contents. Keyword arguments: values -- The list to append the contents to (default [])
def read_msbuild_json(path, values=[]): """Reads the MS Build JSON file at the path and returns its contents. Keyword arguments: values -- The list to append the contents to (default []) """ if not os.path.exists(path): logging.info('Could not find MS Build JSON file at %s', path) r...
Script entrypoint.
def main(): """Script entrypoint.""" # Parse the arguments parser = argparse.ArgumentParser( description='Convert MSBuild XML to JSON format') parser.add_argument( '-t', '--toolchain', help='The name of the toolchain', required=True) parser.add_argument( '-o', '--output', he...
Merges the values between the current and previous run of the script.
def __merge_json_values(current, previous): """Merges the values between the current and previous run of the script.""" for value in current: name = value['name'] # Find the previous value previous_value = __find_and_remove_value(previous, value) if previous_value is not None: ...
Finds the value in the list that corresponds with the value of compare.
def __find_and_remove_value(list, compare): """Finds the value in the list that corresponds with the value of compare.""" # next throws if there are no matches try: found = next(value for value in list if value['name'] == compare['name'] and value['switch'] == ...
Converts the tag type found in the root and converts them using the func and appends them to the values.
def __convert(root, tag, values, func): """Converts the tag type found in the root and converts them using the func and appends them to the values. """ elements = root.getElementsByTagName(tag) for element in elements: converted = func(element) # Append to the list __append...
Converts an EnumProperty node to JSON format.
def __convert_enum(node): """Converts an EnumProperty node to JSON format.""" name = __get_attribute(node, 'Name') logging.debug('Found EnumProperty named %s', name) converted_values = [] for value in node.getElementsByTagName('EnumValue'): converted = __convert_node(value) conver...
Converts an BoolProperty node to JSON format.
def __convert_bool(node): """Converts an BoolProperty node to JSON format.""" converted = __convert_node(node, default_value='true') # Check for a switch for reversing the value reverse_switch = __get_attribute(node, 'ReverseSwitch') if reverse_switch: converted_reverse = copy.deepcopy(con...
Converts a StringListProperty node to JSON format.
def __convert_string_list(node): """Converts a StringListProperty node to JSON format.""" converted = __convert_node(node) # Determine flags for the string list flags = vsflags(VSFlags.UserValue) # Check for a separator to determine if it is semicolon appendable # If not present assume the val...
Converts a StringProperty node to JSON format.
def __convert_string(node): """Converts a StringProperty node to JSON format.""" converted = __convert_node(node, default_flags=vsflags(VSFlags.UserValue)) return __check_for_flag(converted)
Converts a XML node to a JSON equivalent.
def __convert_node(node, default_value='', default_flags=vsflags()): """Converts a XML node to a JSON equivalent.""" name = __get_attribute(node, 'Name') logging.debug('Found %s named %s', node.tagName, name) converted = {} converted['name'] = name converted['switch'] = __get_attribute(node, 'S...
Modifies the flags in value if the node contains an Argument.
def __with_argument(node, value): """Modifies the flags in value if the node contains an Argument.""" arguments = node.getElementsByTagName('Argument') if arguments: logging.debug('Found argument within %s', value['name']) value['flags'] = vsflags(VSFlags.UserValueIgnored, VSFlags.Continue)
Preprocesses occurrences of Argument within the root. Argument XML values reference other values within the document by name. The referenced value does not contain a switch. This function will add the switch associated with the argument.
def __preprocess_arguments(root): """Preprocesses occurrences of Argument within the root. Argument XML values reference other values within the document by name. The referenced value does not contain a switch. This function will add the switch associated with the argument. """ # Set the flags ...
Retrieves the attribute of the given name from the node. If not present then the default_value is used.
def __get_attribute(node, name, default_value=''): """Retrieves the attribute of the given name from the node. If not present then the default_value is used. """ if node.hasAttribute(name): return node.attributes[name].value.strip() else: return default_value
Gets the path to the file.
def __get_path(path): """Gets the path to the file.""" if not os.path.isabs(path): path = os.path.join(os.getcwd(), path) return os.path.normpath(path)
Gets the output path for a file given the toolchain, rule and output_dir
def __output_path(toolchain, rule, output_dir): """Gets the output path for a file given the toolchain, rule and output_dir""" filename = '%s_%s.json' % (toolchain, rule) return os.path.join(output_dir, filename)
Writes a JSON file at the path with the values provided.
def __write_json_file(path, values): """Writes a JSON file at the path with the values provided.""" # Sort the keys to ensure ordering sort_order = ['name', 'switch', 'comment', 'value', 'flags'] sorted_values = [ OrderedDict( sorted( value.items(), key=lambda value: ...
Appends the value to the list.
def __append_list(append_to, value): """Appends the value to the list.""" if value is not None: if isinstance(value, list): append_to.extend(value) else: append_to.append(value)
Decompile a function into ast.FunctionDef node. :param func: python function (can not be a built-in) :return: ast.FunctionDef instance.
def decompile_func(func): ''' Decompile a function into ast.FunctionDef node. :param func: python function (can not be a built-in) :return: ast.FunctionDef instance. ''' code = func.__code__ # For python 3 # defaults = func.func_defaults if sys.version_info.major < 3 else func....
Compile a function from an ast.FunctionDef instance. :param ast_node: ast.FunctionDef instance :param filename: path where function source can be found. :param globals: will be used as func_globals :return: A python function object
def compile_func(ast_node, filename, globals, **defaults): ''' Compile a function from an ast.FunctionDef instance. :param ast_node: ast.FunctionDef instance :param filename: path where function source can be found. :param globals: will be used as func_globals :return: A python functi...
decompile apython pyc or pyo binary file. :param bin_pyc: input file objects :param output: output file objects
def decompile_pyc(bin_pyc, output=sys.stdout): ''' decompile apython pyc or pyo binary file. :param bin_pyc: input file objects :param output: output file objects ''' from turicreate.meta.asttools import python_source bin = bin_pyc.read() code = marshal.loads(bin[8:])...
Consumes input extracting definitions. Args: a_file: The file like stream to parse. Raises: PDDMError if there are any issues.
def ParseInput(self, a_file): """Consumes input extracting definitions. Args: a_file: The file like stream to parse. Raises: PDDMError if there are any issues. """ input_lines = a_file.read().splitlines() self.ParseLines(input_lines)
Parses list of lines. Args: input_lines: A list of strings of input to parse (no newlines on the strings). Raises: PDDMError if there are any issues.
def ParseLines(self, input_lines): """Parses list of lines. Args: input_lines: A list of strings of input to parse (no newlines on the strings). Raises: PDDMError if there are any issues. """ current_macro = None for line in input_lines: if line.startswith(...
Expands the macro reference. Args: macro_ref_str: String of a macro reference (i.e. foo(a, b)). Returns: The text from the expansion. Raises: PDDMError if there are any issues.
def Expand(self, macro_ref_str): """Expands the macro reference. Args: macro_ref_str: String of a macro reference (i.e. foo(a, b)). Returns: The text from the expansion. Raises: PDDMError if there are any issues. """ match = _MACRO_RE.match(macro_ref_str) if match is Non...
Processes the file contents.
def ProcessContent(self, strip_expansion=False): """Processes the file contents.""" self._ParseFile() if strip_expansion: # Without a collection the expansions become blank, removing them. collection = None else: collection = MacroCollection() for section in self._sections: s...
Convert a _imputer model to the protobuf spec. Parameters ---------- model: Imputer A trained Imputer model. input_features: str Name of the input column. output_features: str Name of the output column. Returns ------- model_spec: An object of type Model_pb. ...
def convert(model, input_features, output_features): """Convert a _imputer model to the protobuf spec. Parameters ---------- model: Imputer A trained Imputer model. input_features: str Name of the input column. output_features: str Name of the output column. Retur...
Clear the module state. This is mainly for testing purposes.
def reset (): """ Clear the module state. This is mainly for testing purposes. """ global __all_attributes, __all_features, __implicit_features, __composite_properties global __subfeature_from_value, __all_top_features, __free_features global __all_subfeatures # sets the default value of False ...
Declares a new feature with the given name, values, and attributes. name: the feature name values: a sequence of the allowable values - may be extended later with feature.extend attributes: a sequence of the feature's attributes (e.g. implicit, free, propagated, ...)
def feature (name, values, attributes = []): """ Declares a new feature with the given name, values, and attributes. name: the feature name values: a sequence of the allowable values - may be extended later with feature.extend attributes: a sequence of the feature's attributes (e.g. implicit...
Sets the default value of the given feature, overriding any previous default. feature: the name of the feature value: the default value to assign
def set_default (feature, value): """ Sets the default value of the given feature, overriding any previous default. feature: the name of the feature value: the default value to assign """ f = __all_features[feature] bad_attribute = None if f.free: bad_attribute = "free" ...
Returns the default property values for the given features.
def defaults(features): """ Returns the default property values for the given features. """ assert is_iterable_typed(features, Feature) # FIXME: should merge feature and property modules. from . import property result = [] for f in features: if not f.free and not f.optional and f.de...
Returns true iff all elements of names are valid features.
def valid (names): """ Returns true iff all elements of names are valid features. """ if isinstance(names, str): names = [names] assert is_iterable_typed(names, basestring) return all(name in __all_features for name in names)
Return the values of the given feature.
def values (feature): """ Return the values of the given feature. """ assert isinstance(feature, basestring) validate_feature (feature) return __all_features[feature].values
Returns true iff 'value_string' is a value_string of an implicit feature.
def is_implicit_value (value_string): """ Returns true iff 'value_string' is a value_string of an implicit feature. """ assert isinstance(value_string, basestring) if value_string in __implicit_features: return __implicit_features[value_string] v = value_string.split('-') if v[0] n...
Returns the implicit feature associated with the given implicit value.
def implied_feature (implicit_value): """ Returns the implicit feature associated with the given implicit value. """ assert isinstance(implicit_value, basestring) components = implicit_value.split('-') if components[0] not in __implicit_features: raise InvalidValue ("'%s' is not a value of ...
Checks if all name is a valid feature. Otherwise, raises an exception.
def validate_feature (name): """ Checks if all name is a valid feature. Otherwise, raises an exception. """ assert isinstance(name, basestring) if name not in __all_features: raise InvalidFeature ("'%s' is not a valid feature name" % name) else: return __all_features[name]
Helper for expand_subfeatures. Given a feature and value, or just a value corresponding to an implicit feature, returns a property set consisting of all component subfeatures and their values. For example: expand_subfeatures <toolset>gcc-2.95.2-linux-x86 -> <toolset>gcc ...
def __expand_subfeatures_aux (property_, dont_validate = False): """ Helper for expand_subfeatures. Given a feature and value, or just a value corresponding to an implicit feature, returns a property set consisting of all component subfeatures and their values. For example: expand...
Make all elements of properties corresponding to implicit features explicit, and express all subfeature values as separate properties in their own right. For example, the property gcc-2.95.2-linux-x86 might expand to <toolset>gcc <toolset-version>2.95.2 <toolset-os>linux <toolset-cpu>x86 ...
def expand_subfeatures(properties, dont_validate = False): """ Make all elements of properties corresponding to implicit features explicit, and express all subfeature values as separate properties in their own right. For example, the property gcc-2.95.2-linux-x86 might expand to <too...
Adds the given values to the given feature.
def extend (name, values): """ Adds the given values to the given feature. """ assert isinstance(name, basestring) assert is_iterable_typed(values, basestring) name = add_grist (name) __validate_feature (name) feature = __all_features [name] if feature.implicit: for v in values:...
Checks that value-string is a valid value-string for the given feature.
def validate_value_string (f, value_string): """ Checks that value-string is a valid value-string for the given feature. """ assert isinstance(f, Feature) assert isinstance(value_string, basestring) if f.free or value_string in f.values: return values = [value_string] if f.subfeatu...
Declares a subfeature. feature_name: Root feature that is not a subfeature. value_string: An optional value-string specifying which feature or subfeature values this subfeature is specific to, if any. subfeature: The name of the subfeature ...
def subfeature (feature_name, value_string, subfeature, subvalues, attributes = []): """ Declares a subfeature. feature_name: Root feature that is not a subfeature. value_string: An optional value-string specifying which feature or subfeature values this subfeature is spe...
Sets the components of the given composite property. All parameters are <feature>value strings
def compose (composite_property_s, component_properties_s): """ Sets the components of the given composite property. All parameters are <feature>value strings """ from . import property component_properties_s = to_seq (component_properties_s) composite_property = property.create_from_string(co...
Returns all values of the given feature specified by the given property set.
def get_values (feature, properties): """ Returns all values of the given feature specified by the given property set. """ if feature[0] != '<': feature = '<' + feature + '>' result = [] for p in properties: if get_grist (p) == feature: result.append (replace_grist (p, '')) ...
Expand all composite properties in the set so that all components are explicitly expressed.
def expand_composites (properties): """ Expand all composite properties in the set so that all components are explicitly expressed. """ if __debug__: from .property import Property assert is_iterable_typed(properties, Property) explicit_features = set(p.feature for p in propertie...
Return true iff f is an ordinary subfeature of the parent_property's feature, or if f is a subfeature of the parent_property's feature specific to the parent_property's value.
def is_subfeature_of (parent_property, f): """ Return true iff f is an ordinary subfeature of the parent_property's feature, or if f is a subfeature of the parent_property's feature specific to the parent_property's value. """ if __debug__: from .property import Property asse...
As is_subfeature_of, for subproperties.
def __is_subproperty_of (parent_property, p): """ As is_subfeature_of, for subproperties. """ if __debug__: from .property import Property assert isinstance(parent_property, Property) assert isinstance(p, Property) return is_subfeature_of (parent_property, p.feature)
Given a property set which may consist of composite and implicit properties and combined subfeature values, returns an expanded, normalized property set with all implicit features expressed explicitly, all subfeature values individually expressed, and all components of composite properti...
def expand (properties): """ Given a property set which may consist of composite and implicit properties and combined subfeature values, returns an expanded, normalized property set with all implicit features expressed explicitly, all subfeature values individually expressed, and all ...
Given a set of properties, add default values for features not represented in the set. Note: if there's there's ordinary feature F1 and composite feature F2, which includes some value for F1, and both feature have default values, then the default value of F1 will be added, not the value ...
def add_defaults (properties): """ Given a set of properties, add default values for features not represented in the set. Note: if there's there's ordinary feature F1 and composite feature F2, which includes some value for F1, and both feature have default values, then the default va...
Given an expanded property set, eliminate all redundancy: properties which are elements of other (composite) properties in the set will be eliminated. Non-symmetric properties equal to default values will be eliminated, unless the override a value from some composite property. Implicit p...
def minimize (properties): """ Given an expanded property set, eliminate all redundancy: properties which are elements of other (composite) properties in the set will be eliminated. Non-symmetric properties equal to default values will be eliminated, unless the override a value from some com...
Given a property-set of the form v1/v2/...vN-1/<fN>vN/<fN+1>vN+1/...<fM>vM Returns v1 v2 ... vN-1 <fN>vN <fN+1>vN+1 ... <fM>vM Note that vN...vM may contain slashes. This is resilient to the substitution of backslashes for slashes, since Jam, unbidden, sometimes swaps slash direction o...
def split (properties): """ Given a property-set of the form v1/v2/...vN-1/<fN>vN/<fN+1>vN+1/...<fM>vM Returns v1 v2 ... vN-1 <fN>vN <fN+1>vN+1 ... <fM>vM Note that vN...vM may contain slashes. This is resilient to the substitution of backslashes for slashes, since Jam, unbidden, s...
Combine all subproperties into their parent properties Requires: for every subproperty, there is a parent property. All features are explicitly expressed. This rule probably shouldn't be needed, but build-request.expand-no-defaults is being abused for unintended purposes and i...
def compress_subproperties (properties): """ Combine all subproperties into their parent properties Requires: for every subproperty, there is a parent property. All features are explicitly expressed. This rule probably shouldn't be needed, but build-request.expand-no-defaults is b...
Given a property, return the subset of features consisting of all ordinary subfeatures of the property's feature, and all specific subfeatures of the property's feature which are conditional on the property's value.
def __select_subfeatures (parent_property, features): """ Given a property, return the subset of features consisting of all ordinary subfeatures of the property's feature, and all specific subfeatures of the property's feature which are conditional on the property's value. """ if __d...
Retrieves the interpretation function used.
def _get_interpretation_function(interpretation, dtype): """ Retrieves the interpretation function used. """ type_string = dtype.__name__ name = "%s__%s" % (interpretation, type_string) global _interpretations if not hasattr(_interpretations, name): raise ValueError("No transform ...
Returns the description and output type for a given interpretation.
def _get_interpretation_description_and_output_type(interpretation, dtype): """ Returns the description and output type for a given interpretation. """ type_string = dtype.__name__ name = "%s__%s" % (interpretation, type_string) if not hasattr(_interpretations_class, name): raise Value...
Returns a list of the available interpretations and what they do. If indent is specified, then the entire doc string is indented by that amount.
def _get_embeddable_interpretation_doc(indent = 0): """ Returns a list of the available interpretations and what they do. If indent is specified, then the entire doc string is indented by that amount. """ output_rows = [] # Pull out the doc string and put it in a table. for name in sorted...
A function to load a previously saved SentenceSplitter instance. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writer.
def _load_version(cls, unpickler, version): """ A function to load a previously saved SentenceSplitter instance. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writer...
Fits the transformer using the given data.
def fit(self, data): """ Fits the transformer using the given data. """ _raise_error_if_not_sframe(data, "data") fitted_state = {} feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features) if not feature_columns: raise ...
Transforms the data.
def transform(self, data): """ Transforms the data. """ if not self._get("fitted"): raise RuntimeError("`transform` called before `fit` or `fit_transform`.") data = data.copy() output_column_prefix = self._get("output_column_prefix") if output_colum...
Transforms short text into a dictionary of TFIDF-weighted 3-gram character counts.
def short_text__str(self, column_name, output_column_prefix): """ Transforms short text into a dictionary of TFIDF-weighted 3-gram character counts. """ from ._ngram_counter import NGramCounter from ._tfidf import TFIDF return [NGramCounter(features=[column_name...
Interprets an integer column as a categorical variable.
def categorical__int(self, column_name, output_column_prefix): """ Interprets an integer column as a categorical variable. """ return [_ColumnFunctionTransformation( features = [column_name], output_column_prefix = output_column_prefix, transform_func...
Sets up the content transforms.
def _setup_from_data(self, data): """ Sets up the content transforms. """ fitted_state = {} _raise_error_if_not_of_type(data, [_SFrame]) feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features) if not feature_columns: ...
Fits a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted object) See Also -------- transform, fit_transform
def fit(self, data): """ Fits a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted object) See Also -------- transform, fit_tr...
Fits and transforms the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out: SFrame A transformed SFrame. ...
def fit_transform(self, data): """ Fits and transforms the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out...
Transform the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out: SFrame A transformed SFrame. See Also ...
def transform(self, data): """ Transform the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out: SFrame ...
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...
Save the model as a directory, which can be loaded with the :py:func:`~turicreate.load_model` method. Parameters ---------- pickler : GLPickler An opened GLPickle archive (Do not close the archive). See Also -------- turicreate.load_model Ex...
def _save_impl(self, pickler): """ Save the model as a directory, which can be loaded with the :py:func:`~turicreate.load_model` method. Parameters ---------- pickler : GLPickler An opened GLPickle archive (Do not close the archive). See Also ...
Create a new mock object. Args: # class_to_mock: the class to be mocked class_to_mock: class Returns: MockObject that can be used as the class_to_mock would be.
def CreateMock(self, class_to_mock): """Create a new mock object. Args: # class_to_mock: the class to be mocked class_to_mock: class Returns: MockObject that can be used as the class_to_mock would be. """ new_mock = MockObject(class_to_mock) self._mock_objects.append(new_moc...
Replace a method, attribute, etc. with a Mock. This will replace a class or module with a MockObject, and everything else (method, function, etc) with a MockAnything. This can be overridden to always use a MockAnything by setting use_mock_anything to True. Args: obj: A Python object (class, mod...
def StubOutWithMock(self, obj, attr_name, use_mock_anything=False): """Replace a method, attribute, etc. with a Mock. This will replace a class or module with a MockObject, and everything else (method, function, etc) with a MockAnything. This can be overridden to always use a MockAnything by setting u...
Verify that all of the expected calls have been made. Raises: ExpectedMethodCallsError: if there are still more method calls in the expected queue.
def _Verify(self): """Verify that all of the expected calls have been made. Raises: ExpectedMethodCallsError: if there are still more method calls in the expected queue. """ # If the list of expected calls is not empty, raise an exception if self._expected_calls_queue: # The la...
Verify the called method is expected. This can be an ordered method, or part of an unordered set. Returns: The expected mock method. Raises: UnexpectedMethodCall if the method called was not expected.
def _VerifyMethodCall(self): """Verify the called method is expected. This can be an ordered method, or part of an unordered set. Returns: The expected mock method. Raises: UnexpectedMethodCall if the method called was not expected. """ expected = self._PopNextMethod() # Loo...
Returns a possible group from the end of the call queue or None if no other methods are on the stack.
def GetPossibleGroup(self): """Returns a possible group from the end of the call queue or None if no other methods are on the stack. """ # Remove this method from the tail of the queue so we can add it to a group. this_method = self._call_queue.pop() assert this_method == self # Determine ...
Checks if the last method (a possible group) is an instance of our group_class. Adds the current method to this group or creates a new one. Args: group_name: the name of the group. group_class: the class used to create instance of this new group
def _CheckAndCreateNewGroup(self, group_name, group_class): """Checks if the last method (a possible group) is an instance of our group_class. Adds the current method to this group or creates a new one. Args: group_name: the name of the group. group_class: the class used to create instance of ...
Check to see if the RHS is an instance of class_name. Args: # rhs: the right hand side of the test rhs: object Returns: bool
def equals(self, rhs): """Check to see if the RHS is an instance of class_name. Args: # rhs: the right hand side of the test rhs: object Returns: bool """ try: return isinstance(rhs, self._class_name) except TypeError: # Check raw types if there was a type error....
Check whether the given key/value pair is in the rhs dict. Returns: bool
def equals(self, rhs): """Check whether the given key/value pair is in the rhs dict. Returns: bool """ try: return rhs[self._key] == self._value except Exception: return False
Check to see if RHS is almost equal to float_value Args: rhs: the value to compare to float_value Returns: bool
def equals(self, rhs): """Check to see if RHS is almost equal to float_value Args: rhs: the value to compare to float_value Returns: bool """ try: return round(rhs-self._float_value, self._places) == 0 except TypeError: # This is probably because either float_value or ...
Check to see whether actual_seq has same elements as expected_seq. Args: actual_seq: sequence Returns: bool
def equals(self, actual_seq): """Check to see whether actual_seq has same elements as expected_seq. Args: actual_seq: sequence Returns: bool """ try: expected = dict([(element, None) for element in self._expected_seq]) actual = dict([(element, None) for element in actual_s...
Checks whether any Comparator is equal to rhs. Args: # rhs: can be anything Returns: bool
def equals(self, rhs): """Checks whether any Comparator is equal to rhs. Args: # rhs: can be anything Returns: bool """ for comparator in self._comparators: if comparator.equals(rhs): return True return False
Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raises: UnexpectedMethodCallError if the mo...
def MethodCalled(self, mock_method): """Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raise...
Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raises: UnexpectedMethodCallError if the mo...
def MethodCalled(self, mock_method): """Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raise...
Return True if all methods in this group are called at least once.
def IsSatisfied(self): """Return True if all methods in this group are called at least once.""" # NOTE(psycho): We can't use the simple set difference here because we want # to match different parameters which are considered the same e.g. IsA(str) # and some string. This solution is O(n^2) but n should ...