Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def set_target_variable (self, targets, variable, value, append=0):
if isinstance (targets, str):
targets = [targets]
if isinstance(value, str):
value = [value]
assert is_iterable(targets)
assert isinstance(va... | [
" Sets a target variable.\n\n The 'variable' will be available to bjam when it decides\n where to generate targets, and will also be available to\n updating rule for that 'taret'.\n "
] |
Please provide a description of the function:def set_update_action (self, action_name, targets, sources, properties=None):
if isinstance(targets, str):
targets = [targets]
if isinstance(sources, str):
sources = [sources]
if properties is None:
propert... | [
" Binds a target to the corresponding update action.\n If target needs to be updated, the action registered\n with action_name will be used.\n The 'action_name' must be previously registered by\n either 'register_action' or 'register_bjam_action'\n method.\n ... |
Please provide a description of the function:def register_action (self, action_name, command='', bound_list = [], flags = [],
function = None):
assert isinstance(action_name, basestring)
assert isinstance(command, basestring)
assert is_iterable(bound_list)
... | [
"Creates a new build engine action.\n\n Creates on bjam side an action named 'action_name', with\n 'command' as the command to be executed, 'bound_variables'\n naming the list of variables bound when the command is executed\n and specified flag.\n If 'function' is not None, it sho... |
Please provide a description of the function:def register_bjam_action (self, action_name, function=None):
# We allow duplicate calls to this rule for the same
# action name. This way, jamfile rules that take action names
# can just register them without specially checking if
#... | [
"Informs self that 'action_name' is declared in bjam.\n\n From this point, 'action_name' is a valid argument to the\n set_update_action method. The action_name should be callable\n in the global module of bjam.\n "
] |
Please provide a description of the function:def pixel_data(self):
from .. import extensions as _extensions
data = _np.zeros((self.height, self.width, self.channels), dtype=_np.uint8)
_extensions.image_load_to_numpy(self, data.ctypes.data, data.strides)
if self.channels == 1:
... | [
"\n Returns the pixel data stored in the Image object.\n\n Returns\n -------\n out : numpy.array\n The pixel data of the Image object. It returns a multi-dimensional\n numpy array, where the shape of the array represents the shape of\n the image (height, ... |
Please provide a description of the function:def show(self):
from ..visualization._plot import _target
try:
img = self._to_pil_image()
try:
# output into jupyter notebook if possible
if _target == 'auto' and \
get_ipyth... | [
"\n Displays the image. Requires PIL/Pillow.\n\n Alternatively, you can create an :class:`turicreate.SArray` of this image\n and use py:func:`turicreate.SArray.show()`\n\n See Also\n --------\n turicreate.image_analysis.resize\n\n Examples\n --------\n ... |
Please provide a description of the function:def predict(self, data, useCPUOnly=False, **kwargs):
if self.__proxy__:
return self.__proxy__.predict(data,useCPUOnly)
else:
if _macos_version() < (10, 13):
raise Exception('Model prediction is only supported ... | [
"\n Return predictions for the model. The kwargs gets passed into the\n model as a dictionary.\n\n Parameters\n ----------\n data : dict[str, value]\n Dictionary of data to make predictions from where the keys are\n the names of the input features.\n\n ... |
Please provide a description of the function:def visualize_spec(self, port=None, input_shape_dict=None):
spec = self._spec
model_type = spec.WhichOneof('Type')
model_description = spec.description
input_spec = model_description.input
output_spec = model_description.outp... | [
"\n Visualize the model.\n\n Parameters\n ----------\n port : int\n if server is to be hosted on specific localhost port\n\n input_shape_dict : dict\n The shapes are calculated assuming the batch and sequence\n are 1... |
Please provide a description of the function:def _construct_auto_distance(feature_names, column_names, column_types, sample):
## Make a dictionary from the column_names and column_types
col_type_dict = {k: v for k, v in zip(column_names, column_types)}
## Loop through feature names, appending a dista... | [
"\n Construct composite distance parameters based on selected features and their\n types.\n "
] |
Please provide a description of the function:def create(dataset, label=None, features=None, distance=None, method='auto',
verbose=True, **kwargs):
## Validate the 'dataset' input
_tkutl._raise_error_if_not_sframe(dataset, "dataset")
_tkutl._raise_error_if_sframe_empty(dataset, "dataset")
... | [
"\n Create a nearest neighbor model, which can be searched efficiently and\n quickly for the nearest neighbors of a query observation. If the `method`\n argument is specified as `auto`, the type of model is chosen automatically\n based on the type of data in `dataset`.\n\n .. warning::\n\n The... |
Please provide a description of the function:def _get_summary_struct(self):
model_fields = [
("Method", 'method'),
("Number of distance components", 'num_distance_components'),
("Number of examples", 'num_examples'),
("Number of feature columns", 'num_fe... | [
"\n Returns a structured description of the model, including (where\n relevant) the schema of the training data, description of the training\n data, training statistics, and model hyperparameters.\n\n Returns\n -------\n sections : list (of list of tuples)\n A li... |
Please provide a description of the function:def _list_fields(self):
opts = {'model': self.__proxy__, 'model_name': self.__name__}
response = _turicreate.extensions._nearest_neighbors.list_fields(opts)
return sorted(response.keys()) | [
"\n List the fields stored in the model, including data, model, and\n training options. Each field can be queried with the ``get`` method.\n\n Returns\n -------\n out : list\n List of fields queryable with the ``get`` method.\n "
] |
Please provide a description of the function:def _get(self, field):
opts = {'model': self.__proxy__,
'model_name': self.__name__,
'field': field}
response = _turicreate.extensions._nearest_neighbors.get_value(opts)
return response['value'] | [
"\n Return the value of a given field. The list of all queryable fields is\n detailed below, and can be obtained with the\n :func:`~turicreate.nearest_neighbors.NearestNeighborsModel._list_fields`\n method.\n\n +-----------------------+---------------------------------------------... |
Please provide a description of the function:def _training_stats(self):
opts = {'model': self.__proxy__, 'model_name': self.__name__}
return _turicreate.extensions._nearest_neighbors.training_stats(opts) | [
"\n Return a dictionary of statistics collected during creation of the\n model. These statistics are also available with the ``get`` method and\n are described in more detail in that method's documentation.\n\n Returns\n -------\n out : dict\n Dictionary of stati... |
Please provide a description of the function:def query(self, dataset, label=None, k=5, radius=None, verbose=True):
## Validate the 'dataset' input
_tkutl._raise_error_if_not_sframe(dataset, "dataset")
_tkutl._raise_error_if_sframe_empty(dataset, "dataset")
## Get model feature... | [
"\n For each row of the input 'dataset', retrieve the nearest neighbors\n from the model's stored data. In general, the query dataset does not\n need to be the same as the reference data stored in the model, but if\n it is, the 'include_self_edges' parameter can be set to False to\n ... |
Please provide a description of the function:def similarity_graph(self, k=5, radius=None, include_self_edges=False,
output_type='SGraph', verbose=True):
## Validate inputs.
if k is not None:
if not isinstance(k, int):
raise ValueError("Input ... | [
"\n Construct the similarity graph on the reference dataset, which is\n already stored in the model. This is conceptually very similar to\n running `query` with the reference set, but this method is optimized\n for the purpose, syntactically simpler, and automatically removes\n se... |
Please provide a description of the function:def random_split_by_session(dataset, session_id, fraction=0.9, seed=None):
from random import Random
_raise_error_if_not_of_type(dataset, _SFrame, 'dataset')
_raise_error_if_not_of_type(session_id, str, 'session_id')
_raise_error_if_not_of_type(fraction... | [
"\n Randomly split an SFrame into two SFrames based on the `session_id` such\n that one split contains data for a `fraction` of the sessions while the\n second split contains all data for the rest of the sessions.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset to split. It must co... |
Please provide a description of the function:def read_msbuild_xml(path, values={}):
# Attempt to read the file contents
try:
document = parse(path)
except Exception as e:
logging.exception('Could not read MS Build XML file at %s', path)
return values
# Convert the XML to J... | [
"Reads the MS Build XML file at the path and returns its contents.\n\n Keyword arguments:\n values -- The map to append the contents to (default {})\n "
] |
Please provide a description of the function:def read_msbuild_json(path, values=[]):
if not os.path.exists(path):
logging.info('Could not find MS Build JSON file at %s', path)
return values
try:
values.extend(__read_json_file(path))
except Exception as e:
logging.except... | [
"Reads the MS Build JSON file at the path and returns its contents.\n\n Keyword arguments:\n values -- The list to append the contents to (default [])\n "
] |
Please provide a description of the function:def main():
# 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(
... | [
"Script entrypoint."
] |
Please provide a description of the function:def __merge_json_values(current, previous):
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:
flags = value['fla... | [
"Merges the values between the current and previous run of the script."
] |
Please provide a description of the function:def __find_and_remove_value(list, compare):
# next throws if there are no matches
try:
found = next(value for value in list
if value['name'] == compare['name'] and value['switch'] ==
compare['switch'])
except... | [
"Finds the value in the list that corresponds with the value of compare."
] |
Please provide a description of the function:def __convert(root, tag, values, func):
elements = root.getElementsByTagName(tag)
for element in elements:
converted = func(element)
# Append to the list
__append_list(values, converted) | [
"Converts the tag type found in the root and converts them using the func\n and appends them to the values.\n "
] |
Please provide a description of the function:def __convert_enum(node):
name = __get_attribute(node, 'Name')
logging.debug('Found EnumProperty named %s', name)
converted_values = []
for value in node.getElementsByTagName('EnumValue'):
converted = __convert_node(value)
converted['v... | [
"Converts an EnumProperty node to JSON format."
] |
Please provide a description of the function:def __convert_bool(node):
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(converted... | [
"Converts an BoolProperty node to JSON format."
] |
Please provide a description of the function:def __convert_string_list(node):
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 value should b... | [
"Converts a StringListProperty node to JSON format."
] |
Please provide a description of the function:def __convert_string(node):
converted = __convert_node(node, default_flags=vsflags(VSFlags.UserValue))
return __check_for_flag(converted) | [
"Converts a StringProperty node to JSON format."
] |
Please provide a description of the function:def __convert_node(node, default_value='', default_flags=vsflags()):
name = __get_attribute(node, 'Name')
logging.debug('Found %s named %s', node.tagName, name)
converted = {}
converted['name'] = name
converted['switch'] = __get_attribute(node, 'Swi... | [
"Converts a XML node to a JSON equivalent."
] |
Please provide a description of the function:def __with_argument(node, value):
arguments = node.getElementsByTagName('Argument')
if arguments:
logging.debug('Found argument within %s', value['name'])
value['flags'] = vsflags(VSFlags.UserValueIgnored, VSFlags.Continue) | [
"Modifies the flags in value if the node contains an Argument."
] |
Please provide a description of the function:def __preprocess_arguments(root):
# Set the flags to require a value
flags = ','.join(vsflags(VSFlags.UserValueRequired))
# Search through the arguments
arguments = root.getElementsByTagName('Argument')
for argument in arguments:
reference ... | [
"Preprocesses occurrences of Argument within the root.\n\n Argument XML values reference other values within the document by name. The\n referenced value does not contain a switch. This function will add the\n switch associated with the argument.\n "
] |
Please provide a description of the function:def __get_attribute(node, name, default_value=''):
if node.hasAttribute(name):
return node.attributes[name].value.strip()
else:
return default_value | [
"Retrieves the attribute of the given name from the node.\n\n If not present then the default_value is used.\n "
] |
Please provide a description of the function:def __get_path(path):
if not os.path.isabs(path):
path = os.path.join(os.getcwd(), path)
return os.path.normpath(path) | [
"Gets the path to the file."
] |
Please provide a description of the function:def __output_path(toolchain, rule, output_dir):
filename = '%s_%s.json' % (toolchain, rule)
return os.path.join(output_dir, filename) | [
"Gets the output path for a file given the toolchain, rule and output_dir"
] |
Please provide a description of the function:def __write_json_file(path, values):
# Sort the keys to ensure ordering
sort_order = ['name', 'switch', 'comment', 'value', 'flags']
sorted_values = [
OrderedDict(
sorted(
value.items(), key=lambda value: sort_order.index(... | [
"Writes a JSON file at the path with the values provided."
] |
Please provide a description of the function:def __append_list(append_to, value):
if value is not None:
if isinstance(value, list):
append_to.extend(value)
else:
append_to.append(value) | [
"Appends the value to the list."
] |
Please provide a description of the function: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_defa... | [] |
Please provide a description of the function: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 f... | [] |
Please provide a description of the function: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.... | [] |
Please provide a description of the function:def ParseInput(self, a_file):
input_lines = a_file.read().splitlines()
self.ParseLines(input_lines) | [
"Consumes input extracting definitions.\n\n Args:\n a_file: The file like stream to parse.\n\n Raises:\n PDDMError if there are any issues.\n "
] |
Please provide a description of the function:def ParseLines(self, input_lines):
current_macro = None
for line in input_lines:
if line.startswith('PDDM-'):
directive = line.split(' ', 1)[0]
if directive == 'PDDM-DEFINE':
name, args = self._ParseDefineLine(line)
if s... | [
"Parses list of lines.\n\n Args:\n input_lines: A list of strings of input to parse (no newlines on the\n strings).\n\n Raises:\n PDDMError if there are any issues.\n "
] |
Please provide a description of the function:def Expand(self, macro_ref_str):
match = _MACRO_RE.match(macro_ref_str)
if match is None or match.group(0) != macro_ref_str:
raise PDDMError('Failed to parse macro reference: "%s"' % macro_ref_str)
if match.group('name') not in self._macros:
rais... | [
"Expands the macro reference.\n\n Args:\n macro_ref_str: String of a macro reference (i.e. foo(a, b)).\n\n Returns:\n The text from the expansion.\n\n Raises:\n PDDMError if there are any issues.\n "
] |
Please provide a description of the function:def ProcessContent(self, strip_expansion=False):
self._ParseFile()
if strip_expansion:
# Without a collection the expansions become blank, removing them.
collection = None
else:
collection = MacroCollection()
for section in self._sectio... | [
"Processes the file contents."
] |
Please provide a description of the function:def convert(model, input_features, output_features):
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Test the scikit-learn model
_sklearn_util.check_expected_type(model, StandardScaler)
... | [
"Convert a _imputer model to the protobuf spec.\n\n Parameters\n ----------\n model: Imputer\n A trained Imputer model.\n\n input_features: str\n Name of the input column.\n\n output_features: str\n Name of the output column.\n\n Returns\n -------\n model_spec: An object... |
Please provide a description of the function:def reset ():
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 for each valid attribute
... | [
" Clear the module state. This is mainly for testing purposes.\n "
] |
Please provide a description of the function:def feature (name, values, attributes = []):
__validate_feature_attributes (name, attributes)
feature = Feature(name, [], attributes)
__all_features[name] = feature
# Temporary measure while we have not fully moved from 'gristed strings'
__all_featu... | [
" Declares a new feature with the given name, values, and attributes.\n name: the feature name\n values: a sequence of the allowable values - may be extended later with feature.extend\n attributes: a sequence of the feature's attributes (e.g. implicit, free, propagated, ...)\n "
] |
Please provide a description of the function:def set_default (feature, value):
f = __all_features[feature]
bad_attribute = None
if f.free:
bad_attribute = "free"
elif f.optional:
bad_attribute = "optional"
if bad_attribute:
raise InvalidValue ("%s property %s cannot ha... | [
" Sets the default value of the given feature, overriding any previous default.\n feature: the name of the feature\n value: the default value to assign\n "
] |
Please provide a description of the function:def defaults(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.default:
result.... | [
" Returns the default property values for the given features.\n "
] |
Please provide a description of the function:def valid (names):
if isinstance(names, str):
names = [names]
assert is_iterable_typed(names, basestring)
return all(name in __all_features for name in names) | [
" Returns true iff all elements of names are valid features.\n "
] |
Please provide a description of the function:def values (feature):
assert isinstance(feature, basestring)
validate_feature (feature)
return __all_features[feature].values | [
" Return the values of the given feature.\n "
] |
Please provide a description of the function:def is_implicit_value (value_string):
assert isinstance(value_string, basestring)
if value_string in __implicit_features:
return __implicit_features[value_string]
v = value_string.split('-')
if v[0] not in __implicit_features:
return Fa... | [
" Returns true iff 'value_string' is a value_string\n of an implicit feature.\n "
] |
Please provide a description of the function:def implied_feature (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 an implicit feature" % implicit_value... | [
" Returns the implicit feature associated with the given implicit value.\n "
] |
Please provide a description of the function:def validate_feature (name):
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] | [
" Checks if all name is a valid feature. Otherwise, raises an exception.\n "
] |
Please provide a description of the function:def __expand_subfeatures_aux (property_, dont_validate = False):
from . import property # no __debug__ since Property is used elsewhere
assert isinstance(property_, property.Property)
assert isinstance(dont_validate, int) # matches bools
f = property_... | [
" Helper for expand_subfeatures.\n Given a feature and value, or just a value corresponding to an\n implicit feature, returns a property set consisting of all component\n subfeatures and their values. For example:\n\n expand_subfeatures <toolset>gcc-2.95.2-linux-x86\n -> <... |
Please provide a description of the function:def expand_subfeatures(properties, dont_validate = False):
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
assert isinstance(dont_validate, int) # matches bools
result = []
for p in propert... | [
"\n Make all elements of properties corresponding to implicit features\n explicit, and express all subfeature values as separate properties\n in their own right. For example, the property\n\n gcc-2.95.2-linux-x86\n\n might expand to\n\n <toolset>gcc <toolset-version>2.95.2 <toolset-os>linux <... |
Please provide a description of the function:def extend (name, values):
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:
... | [
" Adds the given values to the given feature.\n "
] |
Please provide a description of the function:def validate_value_string (f, value_string):
assert isinstance(f, Feature)
assert isinstance(value_string, basestring)
if f.free or value_string in f.values:
return
values = [value_string]
if f.subfeatures:
if not value_string in f.... | [
" Checks that value-string is a valid value-string for the given feature.\n "
] |
Please provide a description of the function:def subfeature (feature_name, value_string, subfeature, subvalues, attributes = []):
parent_feature = validate_feature (feature_name)
# Add grist to the subfeature name if a value-string was supplied
subfeature_name = __get_subfeature_name (subfeature, valu... | [
" Declares a subfeature.\n feature_name: Root feature that is not a subfeature.\n value_string: An optional value-string specifying which feature or\n subfeature values this subfeature is specific to,\n if any.\n subfeature: The name of the ... |
Please provide a description of the function:def compose (composite_property_s, component_properties_s):
from . import property
component_properties_s = to_seq (component_properties_s)
composite_property = property.create_from_string(composite_property_s)
f = composite_property.feature
if len... | [
" Sets the components of the given composite property.\n\n All parameters are <feature>value strings\n "
] |
Please provide a description of the function:def get_values (feature, properties):
if feature[0] != '<':
feature = '<' + feature + '>'
result = []
for p in properties:
if get_grist (p) == feature:
result.append (replace_grist (p, ''))
return result | [
" Returns all values of the given feature specified by the given property set.\n "
] |
Please provide a description of the function:def expand_composites (properties):
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
explicit_features = set(p.feature for p in properties)
result = []
# now expand composite features
for p... | [
" Expand all composite properties in the set so that all components\n are explicitly expressed.\n "
] |
Please provide a description of the function:def is_subfeature_of (parent_property, f):
if __debug__:
from .property import Property
assert isinstance(parent_property, Property)
assert isinstance(f, Feature)
if not f.subfeature:
return False
p = f.parent
if not p:
... | [
" Return true iff f is an ordinary subfeature of the parent_property's\n feature, or if f is a subfeature of the parent_property's feature\n specific to the parent_property's value.\n "
] |
Please provide a description of the function:def __is_subproperty_of (parent_property, p):
if __debug__:
from .property import Property
assert isinstance(parent_property, Property)
assert isinstance(p, Property)
return is_subfeature_of (parent_property, p.feature) | [
" As is_subfeature_of, for subproperties.\n "
] |
Please provide a description of the function:def expand (properties):
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
expanded = expand_subfeatures(properties)
return expand_composites (expanded) | [
" Given a property set which may consist of composite and implicit\n properties and combined subfeature values, returns an expanded,\n normalized property set with all implicit features expressed\n explicitly, all subfeature values individually expressed, and all\n components of composit... |
Please provide a description of the function:def add_defaults (properties):
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
# create a copy since properties will be modified
result = list(properties)
# We don't add default for conditional... | [
" Given a set of properties, add default values for features not\n represented in the set.\n Note: if there's there's ordinary feature F1 and composite feature\n F2, which includes some value for F1, and both feature have default values,\n then the default value of F1 will be added, not ... |
Please provide a description of the function:def minimize (properties):
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
# remove properties implied by composite features
components = []
component_features = set()
for property in proper... | [
" Given an expanded property set, eliminate all redundancy: properties\n which are elements of other (composite) properties in the set will\n be eliminated. Non-symmetric properties equal to default values will be\n eliminated, unless the override a value from some composite property.\n ... |
Please provide a description of the function:def split (properties):
assert isinstance(properties, basestring)
def split_one (properties):
pieces = re.split (__re_slash_or_backslash, properties)
result = []
for x in pieces:
if not get_grist (x) and len (result) > 0 and ... | [
" Given a property-set of the form\n v1/v2/...vN-1/<fN>vN/<fN+1>vN+1/...<fM>vM\n\n Returns\n v1 v2 ... vN-1 <fN>vN <fN+1>vN+1 ... <fM>vM\n\n Note that vN...vM may contain slashes. This is resilient to the\n substitution of backslashes for slashes, since Jam, unbidden,\n sometimes swaps sla... |
Please provide a description of the function:def compress_subproperties (properties):
from .property import Property
assert is_iterable_typed(properties, Property)
result = []
matched_subs = set()
all_subs = set()
for p in properties:
f = p.feature
if not f.subfeature:
... | [
" Combine all subproperties into their parent properties\n\n Requires: for every subproperty, there is a parent property. All\n features are explicitly expressed.\n\n This rule probably shouldn't be needed, but\n build-request.expand-no-defaults is being abused for unintended\n p... |
Please provide a description of the function:def __select_subfeatures (parent_property, features):
if __debug__:
from .property import Property
assert isinstance(parent_property, Property)
assert is_iterable_typed(features, Feature)
return [f for f in features if is_subfeature_of (p... | [
" Given a property, return the subset of features consisting of all\n ordinary subfeatures of the property's feature, and all specific\n subfeatures of the property's feature which are conditional on the\n property's value.\n "
] |
Please provide a description of the function:def _get_interpretation_function(interpretation, dtype):
type_string = dtype.__name__
name = "%s__%s" % (interpretation, type_string)
global _interpretations
if not hasattr(_interpretations, name):
raise ValueError("No transform available for ... | [
"\n Retrieves the interpretation function used.\n "
] |
Please provide a description of the function:def _get_interpretation_description_and_output_type(interpretation, dtype):
type_string = dtype.__name__
name = "%s__%s" % (interpretation, type_string)
if not hasattr(_interpretations_class, name):
raise ValueError("No transform available for type... | [
"\n Returns the description and output type for a given interpretation.\n "
] |
Please provide a description of the function:def _get_embeddable_interpretation_doc(indent = 0):
output_rows = []
# Pull out the doc string and put it in a table.
for name in sorted(dir(_interpretations)):
if name.startswith("_") or "__" not in name:
continue
interpretati... | [
"\n Returns a list of the available interpretations and what they do.\n\n If indent is specified, then the entire doc string is indented by that amount.\n "
] |
Please provide a description of the function:def _load_version(cls, unpickler, version):
state, _exclude, _features = unpickler.load()
features = state['features']
excluded_features = state['excluded_features']
model = cls.__new__(cls)
model._setup()
model.__pr... | [
"\n A function to load a previously saved SentenceSplitter instance.\n\n Parameters\n ----------\n unpickler : GLUnpickler\n A GLUnpickler file handler.\n\n version : int\n Version number maintained by the class writer.\n "
] |
Please provide a description of the function:def fit(self, 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 RuntimeError("No vali... | [
"\n Fits the transformer using the given data.\n "
] |
Please provide a description of the function:def transform(self, 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_colu... | [
"\n Transforms the data.\n "
] |
Please provide a description of the function:def short_text__str(self, column_name, output_column_prefix):
from ._ngram_counter import NGramCounter
from ._tfidf import TFIDF
return [NGramCounter(features=[column_name],
n = 3,
m... | [
"\n Transforms short text into a dictionary of TFIDF-weighted 3-gram\n character counts.\n "
] |
Please provide a description of the function:def categorical__int(self, column_name, output_column_prefix):
return [_ColumnFunctionTransformation(
features = [column_name],
output_column_prefix = output_column_prefix,
transform_function = lambda col: col.astype(str)... | [
"\n Interprets an integer column as a categorical variable.\n "
] |
Please provide a description of the function:def _setup_from_data(self, data):
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:
raise Run... | [
"\n Sets up the content transforms.\n "
] |
Please provide a description of the function:def fit(self, data):
self._setup_from_data(data)
self.transform_chain.fit(data)
self.__proxy__.update({"fitted" : True})
return self | [
"\n Fits a transformer using the SFrame `data`.\n\n Parameters\n ----------\n data : SFrame\n The data used to fit the transformer.\n\n Returns\n -------\n self (A fitted object)\n\n See Also\n --------\n transform, fit_transform\n ... |
Please provide a description of the function:def fit_transform(self, data):
self._setup_from_data(data)
ret = self.transform_chain.fit_transform(data)
self.__proxy__.update({"fitted" : True})
return ret | [
"\n Fits and transforms the SFrame `data` using a fitted model.\n\n Parameters\n ----------\n data : SFrame\n The data to be transformed.\n\n Returns\n -------\n A transformed SFrame.\n\n Returns\n -------\n out: SFrame\n A... |
Please provide a description of the function:def transform(self, data):
if self.transform_chain is None:
raise RuntimeError("`transform()` method called before `fit` or `fit_transform`.")
return self.transform_chain.transform(data) | [
"\n Transform the SFrame `data` using a fitted model.\n\n Parameters\n ----------\n data : SFrame\n The data to be transformed.\n\n Returns\n -------\n A transformed SFrame.\n\n Returns\n -------\n out: SFrame\n A transform... |
Please provide a description of the function:def _get_summary_struct(self):
sections = []
fields = []
_features = _precomputed_field(_internal_utils.pretty_print_list(self.features))
_exclude = _precomputed_field(_internal_utils.pretty_print_list(self.excluded_features))
... | [
"\n Returns a structured description of the model, including (where relevant)\n the schema of the training data, description of the training data,\n training statistics, and model hyperparameters.\n\n Returns\n -------\n sections : list (of list of tuples)\n A li... |
Please provide a description of the function:def _save_impl(self, pickler):
pickler.dump( (self.__proxy__.state, self._exclude, self._features) ) | [
"\n Save the model as a directory, which can be loaded with the\n :py:func:`~turicreate.load_model` method.\n\n Parameters\n ----------\n pickler : GLPickler\n An opened GLPickle archive (Do not close the archive).\n\n See Also\n --------\n turicrea... |
Please provide a description of the function:def CreateMock(self, class_to_mock):
new_mock = MockObject(class_to_mock)
self._mock_objects.append(new_mock)
return new_mock | [
"Create a new mock object.\n\n Args:\n # class_to_mock: the class to be mocked\n class_to_mock: class\n\n Returns:\n MockObject that can be used as the class_to_mock would be.\n "
] |
Please provide a description of the function:def StubOutWithMock(self, obj, attr_name, use_mock_anything=False):
attr_to_replace = getattr(obj, attr_name)
if type(attr_to_replace) in self._USE_MOCK_OBJECT and not use_mock_anything:
stub = self.CreateMock(attr_to_replace)
else:
stub = self.... | [
"Replace a method, attribute, etc. with a Mock.\n\n This will replace a class or module with a MockObject, and everything else\n (method, function, etc) with a MockAnything. This can be overridden to\n always use a MockAnything by setting use_mock_anything to True.\n\n Args:\n obj: A Python object... |
Please provide a description of the function:def _Verify(self):
# If the list of expected calls is not empty, raise an exception
if self._expected_calls_queue:
# The last MultipleTimesGroup is not popped from the queue.
if (len(self._expected_calls_queue) == 1 and
isinstance(self._ex... | [
"Verify that all of the expected calls have been made.\n\n Raises:\n ExpectedMethodCallsError: if there are still more method calls in the\n expected queue.\n "
] |
Please provide a description of the function:def _VerifyMethodCall(self):
expected = self._PopNextMethod()
# Loop here, because we might have a MethodGroup followed by another
# group.
while isinstance(expected, MethodGroup):
expected, method = expected.MethodCalled(self)
if method is... | [
"Verify the called method is expected.\n\n This can be an ordered method, or part of an unordered set.\n\n Returns:\n The expected mock method.\n\n Raises:\n UnexpectedMethodCall if the method called was not expected.\n "
] |
Please provide a description of the function:def GetPossibleGroup(self):
# 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 if the tail of the queue is a group, or just a regular ordered
# mo... | [
"Returns a possible group from the end of the call queue or None if no\n other methods are on the stack.\n "
] |
Please provide a description of the function:def _CheckAndCreateNewGroup(self, group_name, group_class):
group = self.GetPossibleGroup()
# If this is a group, and it is the correct group, add the method.
if isinstance(group, group_class) and group.group_name() == group_name:
group.AddMethod(self... | [
"Checks if the last method (a possible group) is an instance of our\n group_class. Adds the current method to this group or creates a new one.\n\n Args:\n\n group_name: the name of the group.\n group_class: the class used to create instance of this new group\n "
] |
Please provide a description of the function:def equals(self, rhs):
try:
return isinstance(rhs, self._class_name)
except TypeError:
# Check raw types if there was a type error. This is helpful for
# things like cStringIO.StringIO.
return type(rhs) == type(self._class_name) | [
"Check to see if the RHS is an instance of class_name.\n\n Args:\n # rhs: the right hand side of the test\n rhs: object\n\n Returns:\n bool\n "
] |
Please provide a description of the function:def equals(self, rhs):
try:
return round(rhs-self._float_value, self._places) == 0
except TypeError:
# This is probably because either float_value or rhs is not a number.
return False | [
"Check to see if RHS is almost equal to float_value\n\n Args:\n rhs: the value to compare to float_value\n\n Returns:\n bool\n "
] |
Please provide a description of the function:def equals(self, rhs):
try:
return rhs[self._key] == self._value
except Exception:
return False | [
"Check whether the given key/value pair is in the rhs dict.\n\n Returns:\n bool\n "
] |
Please provide a description of the function:def equals(self, actual_seq):
try:
expected = dict([(element, None) for element in self._expected_seq])
actual = dict([(element, None) for element in actual_seq])
except TypeError:
# Fall back to slower list-compare if any of the objects are u... | [
"Check to see whether actual_seq has same elements as expected_seq.\n\n Args:\n actual_seq: sequence\n\n Returns:\n bool\n "
] |
Please provide a description of the function:def equals(self, rhs):
for comparator in self._comparators:
if comparator.equals(rhs):
return True
return False | [
"Checks whether any Comparator is equal to rhs.\n\n Args:\n # rhs: can be anything\n\n Returns:\n bool\n "
] |
Please provide a description of the function:def MethodCalled(self, mock_method):
# Check to see if this method exists, and if so, remove it from the set
# and return it.
for method in self._methods:
if method == mock_method:
# Remove the called mock_method instead of the method in the g... | [
"Remove a method call from the group.\n\n If the method is not in the set, an UnexpectedMethodCallError will be\n raised.\n\n Args:\n mock_method: a mock method that should be equal to a method in the group.\n\n Returns:\n The mock method from the group\n\n Raises:\n UnexpectedMethodCa... |
Please provide a description of the function:def MethodCalled(self, mock_method):
# Check to see if this method exists, and if so add it to the set of
# called methods.
for method in self._methods:
if method == mock_method:
self._methods_called.add(mock_method)
# Always put this... | [
"Remove a method call from the group.\n\n If the method is not in the set, an UnexpectedMethodCallError will be\n raised.\n\n Args:\n mock_method: a mock method that should be equal to a method in the group.\n\n Returns:\n The mock method from the group\n\n Raises:\n UnexpectedMethodCa... |
Please provide a description of the function:def IsSatisfied(self):
# 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 be small.
tmp = self._m... | [
"Return True if all methods in this group are called at least once."
] |
Please provide a description of the function:def convert(model, input_features, output_features):
_INTERMEDIATE_FEATURE_NAME = "__sparse_vector_features__"
n_dimensions = len(model.feature_names_)
input_features = process_or_validate_features(input_features)
# Ensure that the output_features are... | [
"Convert a _imputer model to the protobuf spec.\n\n Parameters\n ----------\n model: Imputer\n A trained Imputer model.\n\n input_features: str\n Name of the input column.\n\n output_features: str\n Name of the output column.\n\n Returns\n -------\n model_spec: An object... |
Please provide a description of the function:def set_classifier_interface_params(spec, features, class_labels,
model_accessor_for_class_labels, output_features = None):
# Normalize the features list.
features = _fm.process_or_validate_features(features)
if class_labels is None:
raise V... | [
"\n Common utilities to set the regression interface params.\n "
] |
Please provide a description of the function:def set_regressor_interface_params(spec, features, output_features):
if output_features is None:
output_features = [("predicted_class", datatypes.Double())]
else:
output_features = _fm.process_or_validate_features(output_features, 1)
if len(... | [
" Common utilities to set the regressor interface params.\n "
] |
Please provide a description of the function:def set_transform_interface_params(spec, input_features, output_features, are_optional = False):
input_features = _fm.process_or_validate_features(input_features)
output_features = _fm.process_or_validate_features(output_features)
# Add input and output fea... | [
" Common utilities to set transform interface params.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.