INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return predictions for dataset. Predictions can be generated as class labels or probabilities.
def predict(self, dataset, output_type='class', verbose=True, batch_size=64): """ Return predictions for ``dataset``. Predictions can be generated as class labels or probabilities. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be cl...
Return top - k predictions for the dataset. Predictions are returned as an SFrame with three columns: id class and probability or rank depending on the output_type parameter.
def predict_topk(self, dataset, output_type='probability', k=3, verbose=True, batch_size=64): """ Return top-k predictions for the ``dataset``. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability` or `rank` depending on the ``output_type`` pa...
Convert data into canonical form.
def _init_data(data, allow_empty, default_name): """Convert data into canonical form.""" assert (data is not None) or allow_empty if data is None: data = [] if isinstance(data, (np.ndarray, NDArray)): data = [data] if isinstance(data, list): if not allow_empty: a...
The name and shape of data provided by this iterator
def provide_data(self): """The name and shape of data provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.data]
The name and shape of label provided by this iterator
def provide_label(self): """The name and shape of label provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]
Clear the module state. This is mainly for testing purposes.
def reset (): """ Clear the module state. This is mainly for testing purposes. """ global __generators, __type_to_generators, __generators_for_toolset, __construct_stack global __overrides, __active_generators global __viable_generators_cache, __viable_source_types_cache global __vstg_cached_gen...
Registers new generator instance g.
def register (g): """ Registers new generator instance 'g'. """ assert isinstance(g, Generator) id = g.id() __generators [id] = g # A generator can produce several targets of the # same type. We want unique occurence of that generator # in .generators.$(t) in that case, otherwise, it w...
Creates new instance of the generator class and registers it. Returns the creates instance. Rationale: the instance is returned so that it s possible to first register a generator and then call run method on that generator bypassing all generator selection.
def register_standard (id, source_types, target_types, requirements = []): """ Creates new instance of the 'generator' class and registers it. Returns the creates instance. Rationale: the instance is returned so that it's possible to first register a generator and then call 'run' method on t...
Make generator overrider - id be preferred to overridee - id. If when searching for generators that could produce a target of certain type both those generators are amoung viable generators the overridden generator is immediately discarded.
def override (overrider_id, overridee_id): """Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The o...
Returns a list of source type which can possibly be converted to target_type by some chain of generator invocation.
def __viable_source_types_real (target_type): """ Returns a list of source type which can possibly be converted to 'target_type' by some chain of generator invocation. More formally, takes all generators for 'target_type' and returns union of source types for those generators and result ...
Helper rule caches the result of __viable_source_types_real.
def viable_source_types (target_type): """ Helper rule, caches the result of '__viable_source_types_real'. """ assert isinstance(target_type, basestring) if target_type not in __viable_source_types_cache: __vst_cached_types.append(target_type) __viable_source_types_cache [target_type] = ...
Returns the list of source types which when passed to run method of generator has some change of being eventually used ( probably after conversion by other generators )
def viable_source_types_for_generator_real (generator): """ Returns the list of source types, which, when passed to 'run' method of 'generator', has some change of being eventually used (probably after conversion by other generators) """ assert isinstance(generator, Generator) source_typ...
Caches the result of viable_source_types_for_generator.
def viable_source_types_for_generator (generator): """ Caches the result of 'viable_source_types_for_generator'. """ assert isinstance(generator, Generator) if generator not in __viable_source_types_cache: __vstg_cached_generators.append(generator) __viable_source_types_cache[generator] ...
Returns usage requirements + list of created targets.
def try_one_generator_really (project, name, generator, target_type, properties, sources): """ Returns usage requirements + list of created targets. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or n...
Checks if generator invocation can be pruned because it s guaranteed to fail. If so quickly returns empty list. Otherwise calls try_one_generator_really.
def try_one_generator (project, name, generator, target_type, properties, sources): """ Checks if generator invocation can be pruned, because it's guaranteed to fail. If so, quickly returns empty list. Otherwise, calls try_one_generator_really. """ if __debug__: from .targets import ...
Ensures all targets have types. If this is not so exists with error.
def __ensure_type (targets): """ Ensures all 'targets' have types. If this is not so, exists with error. """ assert is_iterable_typed(targets, virtual_target.VirtualTarget) for t in targets: if not t.type (): get_manager().errors()("target '%s' has no type" % str (t))
Returns generators which can be used to construct target of specified type with specified properties. Uses the following algorithm: - iterates over requested target_type and all it s bases ( in the order returned bt type. all - bases. - for each type find all generators that generate that type and which requirements ar...
def find_viable_generators_aux (target_type, prop_set): """ Returns generators which can be used to construct target of specified type with specified properties. Uses the following algorithm: - iterates over requested target_type and all it's bases (in the order returned bt type.all-bases....
Attempts to construct target by finding viable generators running them and selecting the dependency graph.
def __construct_really (project, name, target_type, prop_set, sources): """ Attempts to construct target by finding viable generators, running them and selecting the dependency graph. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) ...
Attempts to create target of target - type with properties from sources. The sources are treated as a collection of * possible * ingridients -- i. e. it is not required to consume them all. If multiple is true the rule is allowed to return several targets of target - type.
def construct (project, name, target_type, prop_set, sources, top_level=False): """ Attempts to create target of 'target-type' with 'properties' from 'sources'. The 'sources' are treated as a collection of *possible* ingridients -- i.e. it is not required to consume them all. If 'multiple' i...
Returns another generator which differers from $ ( self ) in - id - value to <toolset > feature in properties
def clone (self, new_id, new_toolset_properties): """ Returns another generator which differers from $(self) in - id - value to <toolset> feature in properties """ assert isinstance(new_id, basestring) assert is_iterable_typed(new_toolset_properties, basestrin...
Creates another generator that is the same as $ ( self ) except that if base is in target types of $ ( self ) type will in target types of the new generator.
def clone_and_change_target_type(self, base, type): """Creates another generator that is the same as $(self), except that if 'base' is in target types of $(self), 'type' will in target types of the new generator.""" assert isinstance(base, basestring) assert isinstance(type, base...
Returns true if the generator can be run with the specified properties.
def match_rank (self, ps): """ Returns true if the generator can be run with the specified properties. """ # See if generator's requirements are satisfied by # 'properties'. Treat a feature name in requirements # (i.e. grist-only element), as matching any value of th...
Tries to invoke this generator on the given sources. Returns a list of generated targets ( instances of virtual - target ).
def run (self, project, name, prop_set, sources): """ Tries to invoke this generator on the given sources. Returns a list of generated targets (instances of 'virtual-target'). project: Project for which the targets are generated. name: Determines the name o...
Constructs the dependency graph that will be returned by this generator. consumed: Already prepared list of consumable targets If generator requires several source files will contain exactly len $ ( self. source_types_ ) targets with matching types Otherwise might contain several targets with the type of self. source_t...
def construct_result (self, consumed, project, name, prop_set): """ Constructs the dependency graph that will be returned by this generator. consumed: Already prepared list of consumable targets If generator requires several source files will c...
Determine the name of the produced target from the names of the sources.
def determine_output_name(self, sources): """Determine the name of the produced target from the names of the sources.""" assert is_iterable_typed(sources, virtual_target.VirtualTarget) # The simple case if when a name # of source has single dot. Then, we take the part before ...
Constructs targets that are created after consuming sources. The result will be the list of virtual - target which the same length as target_types attribute and with corresponding types.
def generated_targets (self, sources, prop_set, project, name): """ Constructs targets that are created after consuming 'sources'. The result will be the list of virtual-target, which the same length as 'target_types' attribute and with corresponding types. When 'name' is em...
Attempts to convert source to the types that this generator can handle. The intention is to produce the set of targets can should be used when generator is run. only_one: convert source to only one of source types if there s more that one possibility report an error.
def convert_to_consumable_types (self, project, name, prop_set, sources, only_one=False): """ Attempts to convert 'source' to the types that this generator can handle. The intention is to produce the set of targets can should be used when generator is run. only_one: convert...
Converts several files to consumable types.
def convert_multiple_sources_to_consumable_types (self, project, prop_set, sources): """ Converts several files to consumable types. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(prop_set, pro...
Returns the sketch summary for the given set of keys. This is only applicable for sketch summary created from SArray of sarray or dict type. For dict SArray the keys are the keys in dict value. For array Sarray the keys are indexes into the array value.
def element_sub_sketch(self, keys = None): """ Returns the sketch summary for the given set of keys. This is only applicable for sketch summary created from SArray of sarray or dict type. For dict SArray, the keys are the keys in dict value. For array Sarray, the keys are indexes...
Convert a Nu - Support Vector Classification ( NuSVC ) model to the protobuf spec. Parameters ---------- model: NuSVC A trained NuSVC encoder model.
def convert(model, feature_names, target): """Convert a Nu-Support Vector Classification (NuSVC) model to the protobuf spec. Parameters ---------- model: NuSVC A trained NuSVC encoder model. feature_names: [str], optional (default=None) Name of the input columns. target: str, o...
Convert a linear regression model to the protobuf spec. Parameters ---------- model: LinearRegression A trained linear regression encoder model.
def convert(model, features, target): """Convert a linear regression model to the protobuf spec. Parameters ---------- model: LinearRegression A trained linear regression encoder model. feature_names: [str] Name of the input columns. target: str Name of the output colu...
Fetches all needed information from the top - level DBAPI module guessing at the module if it wasn t passed as a parameter. Returns a dictionary of all the needed variables. This is put in one place to make sure the error message is clear if the module guess is wrong.
def _get_global_dbapi_info(dbapi_module, conn): """ Fetches all needed information from the top-level DBAPI module, guessing at the module if it wasn't passed as a parameter. Returns a dictionary of all the needed variables. This is put in one place to make sure the error message is clear if the mod...
Constructs an SFrame from a CSV file or a path to multiple CSVs and returns a pair containing the SFrame and optionally ( if store_errors = True ) a dict of filenames to SArrays indicating for each file what are the incorrectly parsed lines encountered.
def _read_csv_impl(cls, url, delimiter=',', header=True, error_bad_lines=False, comment_char='', escape_char='\\', double_quote=True, qu...
Constructs an SFrame from a CSV file or a path to multiple CSVs and returns a pair containing the SFrame and a dict of filenames to SArrays indicating for each file what are the incorrectly parsed lines encountered.
def read_csv_with_errors(cls, url, delimiter=',', header=True, comment_char='', escape_char='\\', double_quote=True, ...
Reads a JSON file representing a table into an SFrame.
def read_json(cls, url, orient='records'): """ Reads a JSON file representing a table into an SFrame. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" p...
Convert the result of a SQL database query to an SFrame.
def from_sql(cls, conn, sql_statement, params=None, type_inference_rows=100, dbapi_module=None, column_type_hints=None, cursor_arraysize=128): """ Convert the result of a SQL database query to an SFrame. Parameters ---------- conn : dbapi2.Connection A DBAPI2 c...
Convert an SFrame to a single table in a SQL database.
def to_sql(self, conn, table_name, dbapi_module=None, use_python_type_specifiers=False, use_exact_column_names=True): """ Convert an SFrame to a single table in a SQL database. This function does not attempt to create the table or check if a table named `table_name` exists i...
Print the first M rows and N columns of the SFrame in human readable format.
def print_rows(self, num_rows=10, num_columns=40, max_column_width=30, max_row_width=80, output_file=None): """ Print the first M rows and N columns of the SFrame in human readable format. Parameters ---------- num_rows : int, optional Numb...
Where other is an SArray of identical length as the current Frame this returns a selection of a subset of rows in the current SFrame where the corresponding row in the selector is non - zero.
def _row_selector(self, other): """ Where other is an SArray of identical length as the current Frame, this returns a selection of a subset of rows in the current SFrame where the corresponding row in the selector is non-zero. """ if type(other) is SArray: if ...
Convert this SFrame to pandas. DataFrame.
def to_dataframe(self): """ Convert this SFrame to pandas.DataFrame. This operation will construct a pandas.DataFrame in memory. Care must be taken when size of the returned object is big. Returns ------- out : pandas.DataFrame The dataframe which co...
Converts this SFrame to a numpy array
def to_numpy(self): """ Converts this SFrame to a numpy array This operation will construct a numpy array in memory. Care must be taken when size of the returned object is big. Returns ------- out : numpy.ndarray A Numpy Array containing all the valu...
Transform each row to an: class: ~turicreate. SArray according to a specified function. Returns a new SArray of dtype where each element in this SArray is transformed by fn ( x ) where x is a single row in the sframe represented as a dictionary. The fn should return exactly one value which can be cast into type dtype. ...
def apply(self, fn, dtype=None, seed=None): """ Transform each row to an :class:`~turicreate.SArray` according to a specified function. Returns a new SArray of ``dtype`` where each element in this SArray is transformed by `fn(x)` where `x` is a single row in the sframe represente...
Map each row of the SFrame to multiple rows in a new SFrame via a function.
def flat_map(self, column_names, fn, column_types='auto', seed=None): """ Map each row of the SFrame to multiple rows in a new SFrame via a function. The output of `fn` must have type List[List[...]]. Each inner list will be a single row in the new output, and the collection of...
Sample a fraction of the current SFrame s rows.
def sample(self, fraction, seed=None, exact=False): """ Sample a fraction of the current SFrame's rows. Parameters ---------- fraction : float Fraction of the rows to fetch. Must be between 0 and 1. if exact is False (default), the number of rows returned...
Randomly split the rows of an SFrame into two SFrames. The first SFrame contains * M * rows sampled uniformly ( without replacement ) from the original SFrame. * M * is approximately the fraction times the original number of rows. The second SFrame contains the remaining rows of the original SFrame. An exact fraction p...
def random_split(self, fraction, seed=None, exact=False): """ Randomly split the rows of an SFrame into two SFrames. The first SFrame contains *M* rows, sampled uniformly (without replacement) from the original SFrame. *M* is approximately the fraction times the original number o...
Get top k rows according to the given column. Result is according to and sorted by column_name in the given order ( default is descending ). When k is small topk is more efficient than sort.
def topk(self, column_name, k=10, reverse=False): """ Get top k rows according to the given column. Result is according to and sorted by `column_name` in the given order (default is descending). When `k` is small, `topk` is more efficient than `sort`. Parameters --------...
Save the SFrame to a file system for later use.
def save(self, filename, format=None): """ Save the SFrame to a file system for later use. Parameters ---------- filename : string The location to save the SFrame. Either a local directory or a remote URL. If the format is 'binary', a directory will be cr...
Writes an SFrame to a CSV file.
def export_csv(self, filename, delimiter=',', line_terminator='\n', header=True, quote_level=csv.QUOTE_NONNUMERIC, double_quote=True, escape_char='\\', quote_char='\"', na_rep='', file_header='', file_footer='', line_prefix='', _no_prefix_on_first_value=False, **kwargs): ...
Writes an SFrame to a JSON file.
def export_json(self, filename, orient='records'): """ Writes an SFrame to a JSON file. Parameters ---------- filename : string The location to save the JSON file. orient : string, optional. Either "records" or "lines"...
Performs an incomplete save of an existing SFrame into a directory. This saved SFrame may reference SFrames in other locations in the same filesystem for certain resources.
def _save_reference(self, filename): """ Performs an incomplete save of an existing SFrame into a directory. This saved SFrame may reference SFrames in other locations in the same filesystem for certain resources. Parameters ---------- filename : string ...
Get a reference to the: class: ~turicreate. SArray that corresponds with the given column_name. Throws an exception if the column_name is something other than a string or if the column name is not found.
def select_column(self, column_name): """ Get a reference to the :class:`~turicreate.SArray` that corresponds with the given column_name. Throws an exception if the column_name is something other than a string or if the column name is not found. Parameters ---------- ...
Selects all columns where the name of the column or the type of column is included in the column_names. An exception is raised if duplicate columns are selected i. e. sf. select_columns ( [ a a ] ) or non - existent columns are selected.
def select_columns(self, column_names): """ Selects all columns where the name of the column or the type of column is included in the column_names. An exception is raised if duplicate columns are selected i.e. sf.select_columns(['a','a']), or non-existent columns are selected. ...
Returns an SFrame with a new column. The number of elements in the data given must match the length of every other column of the SFrame. If no name is given a default name is chosen.
def add_column(self, data, column_name="", inplace=False): """ Returns an SFrame with a new column. The number of elements in the data given must match the length of every other column of the SFrame. If no name is given, a default name is chosen. If inplace == False (default) th...
Returns an SFrame with multiple columns added. The number of elements in all columns must match the length of every other column of the SFrame.
def add_columns(self, data, column_names=None, inplace=False): """ Returns an SFrame with multiple columns added. The number of elements in all columns must match the length of every other column of the SFrame. If inplace == False (default) this operation does not modify the ...
Returns an SFrame with a column removed.
def remove_column(self, column_name, inplace=False): """ Returns an SFrame with a column removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, ret...
Returns an SFrame with one or more columns removed.
def remove_columns(self, column_names, inplace=False): """ Returns an SFrame with one or more columns removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current ...
Returns an SFrame with two column positions swapped.
def swap_columns(self, column_name_1, column_name_2, inplace=False): """ Returns an SFrame with two column positions swapped. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the...
Returns an SFrame with columns renamed. names is expected to be a dict specifying the old and new names. This changes the names of the columns given as the keys and replaces them with the names given as the values.
def rename(self, names, inplace=False): """ Returns an SFrame with columns renamed. ``names`` is expected to be a dict specifying the old and new names. This changes the names of the columns given as the keys and replaces them with the names given as the values. If inpla...
Add the rows of an SFrame to the end of this SFrame.
def append(self, other): """ Add the rows of an SFrame to the end of this SFrame. Both SFrames must have the same set of columns with the same column names and column types. Parameters ---------- other : SFrame Another SFrame whose rows are appended ...
Perform a group on the key_column_names followed by aggregations on the columns listed in operations.
def groupby(self, key_column_names, operations, *args): """ Perform a group on the key_column_names followed by aggregations on the columns listed in operations. The operations parameter is a dictionary that indicates which aggregation operators to use and which columns to use t...
Merge two SFrames. Merges the current ( left ) SFrame with the given ( right ) SFrame using a SQL - style equi - join operation by columns.
def join(self, right, on=None, how='inner'): """ Merge two SFrames. Merges the current (left) SFrame with the given (right) SFrame using a SQL-style equi-join operation by columns. Parameters ---------- right : SFrame The SFrame to join. on : None | ...
Filter an SFrame by values inside an iterable object. Result is an SFrame that only includes ( or excludes ) the rows that have a column with the given column_name which holds one of the values in the given values: class: ~turicreate. SArray. If values is not an SArray we attempt to convert it to one before filtering.
def filter_by(self, values, column_name, exclude=False): """ Filter an SFrame by values inside an iterable object. Result is an SFrame that only includes (or excludes) the rows that have a column with the given ``column_name`` which holds one of the values in the given ``values``...
Explore the SFrame in an interactive GUI. Opens a new app window.
def explore(self, title=None): """ Explore the SFrame in an interactive GUI. Opens a new app window. Parameters ---------- title : str The plot title to show for the resulting visualization. Defaults to None. If the title is None, a default title will be ...
Pack columns of the current SFrame into one single column. The result is a new SFrame with the unaffected columns from the original SFrame plus the newly created column.
def pack_columns(self, column_names=None, column_name_prefix=None, dtype=list, fill_na=None, remove_prefix=True, new_column_name=None): """ Pack columns of the current SFrame into one single column. The result is a new SFrame with the unaffected columns from the original SFr...
Splits a datetime column of SFrame to multiple columns with each value in a separate column. Returns a new SFrame with the expanded column replaced with a list of new columns. The expanded column must be of datetime type.
def split_datetime(self, column_name, column_name_prefix=None, limit=None, timezone=False): """ Splits a datetime column of SFrame to multiple columns, with each value in a separate column. Returns a new SFrame with the expanded column replaced with a list of new columns. The expanded co...
Expand one column of this SFrame to multiple columns with each value in a separate column. Returns a new SFrame with the unpacked column replaced with a list of new columns. The column must be of list/ array/ dict type.
def unpack(self, column_name=None, column_name_prefix=None, column_types=None, na_value=None, limit=None): """ Expand one column of this SFrame to multiple columns with each value in a separate column. Returns a new SFrame with the unpacked column replaced with a list of n...
Convert a wide column of an SFrame to one or two tall columns by stacking all values.
def stack(self, column_name, new_column_name=None, drop_na=False, new_column_type=None): """ Convert a "wide" column of an SFrame to one or two "tall" columns by stacking all values. The stack works only for columns of dict, list, or array type. If the column is dict type, two ...
Concatenate values from one or two columns into one column grouping by all other columns. The resulting column could be of type list array or dictionary. If column_names is a numeric column the result will be of array. array type. If column_names is a non - numeric column the new column will be of list type. If column_...
def unstack(self, column_names, new_column_name=None): """ Concatenate values from one or two columns into one column, grouping by all other columns. The resulting column could be of type list, array or dictionary. If ``column_names`` is a numeric column, the result will be of a...
Sort current SFrame by the given columns using the given sort order. Only columns that are type of str int and float can be sorted.
def sort(self, key_column_names, ascending=True): """ Sort current SFrame by the given columns, using the given sort order. Only columns that are type of str, int and float can be sorted. Parameters ---------- key_column_names : str | list of str | list of (str, bool) pa...
Remove missing values from an SFrame. A missing value is either None or NaN. If how is any a row will be removed if any of the columns in the columns parameter contains at least one missing value. If how is all a row will be removed if all of the columns in the columns parameter are missing values.
def dropna(self, columns=None, how='any'): """ Remove missing values from an SFrame. A missing value is either ``None`` or ``NaN``. If ``how`` is 'any', a row will be removed if any of the columns in the ``columns`` parameter contains at least one missing value. If ``how`` is '...
Split rows with missing values from this SFrame. This function has the same functionality as: py: func: ~turicreate. SFrame. dropna but returns a tuple of two SFrames. The first item is the expected output from: py: func: ~turicreate. SFrame. dropna and the second item contains all the rows filtered out by the dropna a...
def dropna_split(self, columns=None, how='any'): """ Split rows with missing values from this SFrame. This function has the same functionality as :py:func:`~turicreate.SFrame.dropna`, but returns a tuple of two SFrames. The first item is the expected output from :py:func:`~turic...
Fill all missing values with a given value in a given column. If the value is not the same type as the values in column_name this method attempts to convert the value to the original column s type. If this fails an error is raised.
def fillna(self, column_name, value): """ Fill all missing values with a given value in a given column. If the ``value`` is not the same type as the values in ``column_name``, this method attempts to convert the value to the original column's type. If this fails, an error is rais...
Returns an SFrame with a new column that numbers each row sequentially. By default the count starts at 0 but this can be changed to a positive or negative number. The new column will be named with the given column name. An error will be raised if the given column name already exists in the SFrame.
def add_row_number(self, column_name='id', start=0, inplace=False): """ Returns an SFrame with a new column that numbers each row sequentially. By default the count starts at 0, but this can be changed to a positive or negative number. The new column will be named with the given...
Adds the FileDescriptorProto and its types to this pool.
def AddSerializedFile(self, serialized_file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add. """ # pylint: disable=g-import-not-at-top from google.protobuf impor...
Adds a Descriptor to the pool non - recursively.
def AddDescriptor(self, desc): """Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor. """ if...
Adds a ServiceDescriptor to the pool.
def AddServiceDescriptor(self, service_desc): """Adds a ServiceDescriptor to the pool. Args: service_desc: A ServiceDescriptor. """ if not isinstance(service_desc, descriptor.ServiceDescriptor): raise TypeError('Expected instance of descriptor.ServiceDescriptor.') self._service_descri...
Adds a FieldDescriptor describing an extension to the pool.
def AddExtensionDescriptor(self, extension): """Adds a FieldDescriptor describing an extension to the pool. Args: extension: A FieldDescriptor. Raises: AssertionError: when another extension with the same number extends the same message. TypeError: when the specified extension is...
Adds a FileDescriptor to the pool non - recursively.
def AddFileDescriptor(self, file_desc): """Adds a FileDescriptor to the pool, non-recursively. If the FileDescriptor contains messages or enums, the caller must explicitly register them. Args: file_desc: A FileDescriptor. """ self._AddFileDescriptor(file_desc) # TODO(jieluo): This i...
Adds a FileDescriptor to the pool non - recursively.
def _AddFileDescriptor(self, file_desc): """Adds a FileDescriptor to the pool, non-recursively. If the FileDescriptor contains messages or enums, the caller must explicitly register them. Args: file_desc: A FileDescriptor. """ if not isinstance(file_desc, descriptor.FileDescriptor): ...
Gets a FileDescriptor by file name.
def FindFileByName(self, file_name): """Gets a FileDescriptor by file name. Args: file_name: The path to the file to get a descriptor for. Returns: A FileDescriptor for the named file. Raises: KeyError: if the file cannot be found in the pool. """ try: return self._fi...
Gets the FileDescriptor for the file containing the specified symbol.
def FindFileContainingSymbol(self, symbol): """Gets the FileDescriptor for the file containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the...
Loads the named descriptor from the pool.
def FindMessageTypeByName(self, full_name): """Loads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The descriptor for the named type. Raises: KeyError: if the message cannot be found in the pool. """ full_name = _Norm...
Loads the named enum descriptor from the pool.
def FindEnumTypeByName(self, full_name): """Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type. Raises: KeyError: if the enum cannot be found in the pool. """ full_nam...
Loads the named field descriptor from the pool.
def FindFieldByName(self, full_name): """Loads the named field descriptor from the pool. Args: full_name: The full name of the field descriptor to load. Returns: The field descriptor for the named field. Raises: KeyError: if the field cannot be found in the pool. """ full_na...
Loads the named service descriptor from the pool.
def FindServiceByName(self, full_name): """Loads the named service descriptor from the pool. Args: full_name: The full name of the service descriptor to load. Returns: The service descriptor for the named service. Raises: KeyError: if the service cannot be found in the pool. """...
Finds the file in descriptor DB containing the specified symbol.
def _FindFileContainingSymbolInDb(self, symbol): """Finds the file in descriptor DB containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file cannot be found in the...
Creates a FileDescriptor from a proto or returns a cached copy.
def _ConvertFileProtoToFileDescriptor(self, file_proto): """Creates a FileDescriptor from a proto or returns a cached copy. This method also has the side effect of loading all the symbols found in the file into the appropriate dictionaries in the pool. Args: file_proto: The proto to convert. ...
Adds the proto to the pool in the specified package.
def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None, scope=None, syntax=None): """Adds the proto to the pool in the specified package. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: The package the proto shoul...
Sets all the descriptor s fields s types.
def _SetAllFieldTypes(self, package, desc_proto, scope): """Sets all the descriptor's fields's types. This method also sets the containing types on any extensions. Args: package: The current package of desc_proto. desc_proto: The message descriptor to update. scope: Enclosing scope of av...
Sets the field s type cpp_type message_type and enum_type.
def _SetFieldType(self, field_proto, field_desc, package, scope): """Sets the field's type, cpp_type, message_type and enum_type. Args: field_proto: Data about the field in proto format. field_desc: The descriptor to modiy. package: The package the field's container is in. scope: Enclos...
Creates a enum value descriptor object from a enum value proto.
def _MakeEnumValueDescriptor(self, value_proto, index): """Creates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describing the enum value. index: The index of the enum value. Returns: An initialized EnumValueDescriptor object. """ return d...
Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.
def _MakeServiceDescriptor(self, service_proto, service_index, scope, package, file_desc): """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto. Args: service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message. service_index: The index of t...
Creates a method descriptor from a MethodDescriptorProto.
def _MakeMethodDescriptor(self, method_proto, service_name, package, scope, index): """Creates a method descriptor from a MethodDescriptorProto. Args: method_proto: The proto describing the method. service_name: The name of the containing service. package: Optional...
Pulls out all the symbols from descriptor protos.
def _ExtractSymbols(self, descriptors): """Pulls out all the symbols from descriptor protos. Args: descriptors: The messages to extract descriptors from. Yields: A two element tuple of the type name and descriptor object. """ for desc in descriptors: yield (_PrefixWithDot(desc.fu...
Recursively finds dependencies for file protos.
def _GetDeps(self, dependencies): """Recursively finds dependencies for file protos. Args: dependencies: The names of the files being depended on. Yields: Each direct and indirect dependency. """ for dependency in dependencies: dep_desc = self.FindFileByName(dependency) yi...
Finds a given type name in the current scope.
def _GetTypeFromScope(self, package, type_name, scope): """Finds a given type name in the current scope. Args: package: The package the proto should be located in. type_name: The name of the type to be found in the scope. scope: Dict mapping short and full symbols to message and enum types. ...
Returns the maximum number in elements. Uses ordered for comparisons or < is none is provided.
def max_element (elements, ordered = None): """ Returns the maximum number in 'elements'. Uses 'ordered' for comparisons, or '<' is none is provided. """ assert is_iterable(elements) assert callable(ordered) or ordered is None if not ordered: ordered = operator.lt max = elements [0] ...
Returns all of elements for which corresponding element in parallel list rank is equal to the maximum value in rank.
def select_highest_ranked (elements, ranks): """ Returns all of 'elements' for which corresponding element in parallel list 'rank' is equal to the maximum value in 'rank'. """ assert is_iterable(elements) assert is_iterable(ranks) if not elements: return [] max_rank = max_elemen...
Copies the content of the specified message into the current message.
def CopyFrom(self, other_msg): """Copies the content of the specified message into the current message. The method clears the current message and then merges the specified message using MergeFrom. Args: other_msg: Message to copy into the current one. """ if self is other_msg: retu...
Traverse through the tree and append to the tree spec.
def recurse_json(mlkit_tree, xgb_tree_json, tree_id, node_id, feature_map, force_32bit_float): """Traverse through the tree and append to the tree spec. """ relative_hit_rate = None try: relative_hit_rate = xgb_tree_json['cover'] except KeyError: pass # Fill node attri...