Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def convert_multiple_sources_to_consumable_types (self, project, prop_set, sources): if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(prop_set, property_set.Prop...
[ " Converts several files to consumable types.\n " ]
Please provide a description of the function:def element_sub_sketch(self, keys = None): single_val = False if keys is None: keys = [] else: if not isinstance(keys, list): single_val = True keys = [keys] value_types = se...
[ "\n Returns the sketch summary for the given set of keys. This is only\n applicable for sketch summary created from SArray of sarray or dict type.\n For dict SArray, the keys are the keys in dict value.\n For array Sarray, the keys are indexes into the array value.\n\n The keys mu...
Please provide a description of the function:def convert(model, feature_names, target): if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') _sklearn_util.check_expected_type(model, _NuSVC) return _SVC.convert(model, feature_names, targe...
[ "Convert a Nu-Support Vector Classification (NuSVC) model to the protobuf spec.\n Parameters\n ----------\n model: NuSVC\n A trained NuSVC encoder model.\n\n feature_names: [str], optional (default=None)\n Name of the input columns.\n\n target: str, optional (default=None)\n Name...
Please provide a description of the function:def convert(model, features, target): if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') # Check the scikit learn model _sklearn_util.check_expected_type(model, LinearRegression) _sklear...
[ "Convert a linear regression model to the protobuf spec.\n Parameters\n ----------\n model: LinearRegression\n A trained linear regression encoder model.\n\n feature_names: [str]\n Name of the input columns.\n\n target: str\n Name of the output column.\n\n Returns\n -------...
Please provide a description of the function:def _get_global_dbapi_info(dbapi_module, conn): module_given_msg = "The DBAPI2 module given ({0}) is missing the global\n"+\ "variable '{1}'. Please make sure you are supplying a module that\n"+\ "conforms to the DBAPI 2.0 standard (PEP 0249)." module_no...
[ "\n Fetches all needed information from the top-level DBAPI module,\n guessing at the module if it wasn't passed as a parameter. Returns a\n dictionary of all the needed variables. This is put in one place to\n make sure the error message is clear if the module \"guess\" is wrong.\n " ]
Please provide a description of the function:def _read_csv_impl(cls, url, delimiter=',', header=True, error_bad_lines=False, comment_char='', escape_char='\\', ...
[ "\n Constructs an SFrame from a CSV file or a path to multiple CSVs, and\n returns a pair containing the SFrame and optionally\n (if store_errors=True) a dict of filenames to SArrays\n indicating for each file, what are the incorrectly parsed lines\n encountered.\n\n Parame...
Please provide a description of the function:def read_csv_with_errors(cls, url, delimiter=',', header=True, comment_char='', escape_char='\\', dou...
[ "\n Constructs an SFrame from a CSV file or a path to multiple CSVs, and\n returns a pair containing the SFrame and a dict of filenames to SArrays\n indicating for each file, what are the incorrectly parsed lines\n encountered.\n\n Parameters\n ----------\n url : str...
Please provide a description of the function:def read_json(cls, url, orient='records'): if orient == "records": g = SArray.read_json(url) if len(g) == 0: return SFrame() g = SFrame({'X1':g}) return g.unp...
[ "\n Reads a JSON file representing a table into an SFrame.\n\n Parameters\n ----------\n url : string\n Location of the CSV file or directory to load. If URL is a directory\n or a \"glob\" pattern, all matching files will be loaded.\n\n orient : string, optio...
Please provide a description of the function:def from_sql(cls, conn, sql_statement, params=None, type_inference_rows=100, dbapi_module=None, column_type_hints=None, cursor_arraysize=128): # Mapping types is always the trickiest part about reading from a # database, so the main complexit...
[ "\n Convert the result of a SQL database query to an SFrame.\n\n Parameters\n ----------\n conn : dbapi2.Connection\n A DBAPI2 connection object. Any connection object originating from\n the 'connect' method of a DBAPI2-compliant package can be used.\n\n sql_stat...
Please provide a description of the function:def to_sql(self, conn, table_name, dbapi_module=None, use_python_type_specifiers=False, use_exact_column_names=True): mod_info = _get_global_dbapi_info(dbapi_module, conn) c = conn.cursor() col_info = list(zip(self.column_names()...
[ "\n Convert an SFrame to a single table in a SQL database.\n\n This function does not attempt to create the table or check if a table\n named `table_name` exists in the database. It simply assumes that\n `table_name` exists in the database and appends to it.\n\n `to_sql` can be th...
Please provide a description of the function:def print_rows(self, num_rows=10, num_columns=40, max_column_width=30, max_row_width=80, output_file=None): if output_file is None: output_file = sys.stdout max_row_width = max(max_row_width, max_column_width + 1) ...
[ "\n Print the first M rows and N columns of the SFrame in human readable\n format.\n\n Parameters\n ----------\n num_rows : int, optional\n Number of rows to print.\n\n num_columns : int, optional\n Number of columns to print.\n\n max_column_wid...
Please provide a description of the function:def _row_selector(self, other): if type(other) is SArray: if self.__has_size__() and other.__has_size__() and len(other) != len(self): raise IndexError("Cannot perform logical indexing on arrays of different length.") ...
[ "\n Where other is an SArray of identical length as the current Frame,\n this returns a selection of a subset of rows in the current SFrame\n where the corresponding row in the selector is non-zero.\n " ]
Please provide a description of the function:def to_dataframe(self): assert HAS_PANDAS, 'pandas is not installed.' df = pandas.DataFrame() for i in range(self.num_columns()): column_name = self.column_names()[i] df[column_name] = list(self[column_name]) ...
[ "\n Convert this SFrame to pandas.DataFrame.\n\n This operation will construct a pandas.DataFrame in memory. Care must\n be taken when size of the returned object is big.\n\n Returns\n -------\n out : pandas.DataFrame\n The dataframe which contains all rows of SF...
Please provide a description of the function:def to_numpy(self): assert HAS_NUMPY, 'numpy is not installed.' import numpy return numpy.transpose(numpy.asarray([self[x] for x in self.column_names()]))
[ "\n Converts this SFrame to a numpy array\n\n This operation will construct a numpy array in memory. Care must\n be taken when size of the returned object is big.\n\n Returns\n -------\n out : numpy.ndarray\n A Numpy Array containing all the values of the SFrame\...
Please provide a description of the function:def apply(self, fn, dtype=None, seed=None): assert callable(fn), "Input must be callable" test_sf = self[:10] dryrun = [fn(row) for row in test_sf] if dtype is None: dtype = SArray(dryrun).dtype if seed is None: ...
[ "\n Transform each row to an :class:`~turicreate.SArray` according to a\n specified function. Returns a new SArray of ``dtype`` where each element\n in this SArray is transformed by `fn(x)` where `x` is a single row in\n the sframe represented as a dictionary. The ``fn`` should return\n...
Please provide a description of the function:def flat_map(self, column_names, fn, column_types='auto', seed=None): assert callable(fn), "Input must be callable" if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) # determine the column_types if co...
[ "\n Map each row of the SFrame to multiple rows in a new SFrame via a\n function.\n\n The output of `fn` must have type List[List[...]]. Each inner list\n will be a single row in the new output, and the collection of these\n rows within the outer list make up the data for the out...
Please provide a description of the function:def sample(self, fraction, seed=None, exact=False): if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) ...
[ "\n Sample a fraction of the current SFrame's rows.\n\n Parameters\n ----------\n fraction : float\n Fraction of the rows to fetch. Must be between 0 and 1.\n if exact is False (default), the number of rows returned is\n approximately the fraction times t...
Please provide a description of the function:def random_split(self, fraction, seed=None, exact=False): if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) if (self.num_rows() == 0 or self.num_columns() == 0): return (SFrame(), S...
[ "\n Randomly split the rows of an SFrame into two SFrames. The first SFrame\n contains *M* rows, sampled uniformly (without replacement) from the\n original SFrame. *M* is approximately the fraction times the original\n number of rows. The second SFrame contains the remaining rows of the...
Please provide a description of the function:def topk(self, column_name, k=10, reverse=False): if type(column_name) is not str: raise TypeError("column_name must be a string") sf = self[self[column_name].is_topk(k, reverse)] return sf.sort(column_name, ascending=reverse)
[ "\n Get top k rows according to the given column. Result is according to and\n sorted by `column_name` in the given order (default is descending).\n When `k` is small, `topk` is more efficient than `sort`.\n\n Parameters\n ----------\n column_name : string\n The ...
Please provide a description of the function:def save(self, filename, format=None): if format is None: if filename.endswith(('.csv', '.csv.gz')): format = 'csv' elif filename.endswith(('.json')): format = 'json' else: ...
[ "\n Save the SFrame to a file system for later use.\n\n Parameters\n ----------\n filename : string\n The location to save the SFrame. Either a local directory or a\n remote URL. If the format is 'binary', a directory will be created\n at the location whi...
Please provide a description of the function: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='', ...
[ "\n Writes an SFrame to a CSV file.\n\n Parameters\n ----------\n filename : string\n The location to save the CSV.\n\n delimiter : string, optional\n This describes the delimiter used for writing csv files.\n\n line_terminator: string, optional\n ...
Please provide a description of the function:def export_json(self, filename, orient='records'): if orient == "records": self.pack_columns(dtype=dict).export_csv( filename, file_header='[', file_footer=']', heade...
[ "\n Writes an SFrame to a JSON file.\n\n Parameters\n ----------\n filename : string\n The location to save the JSON file.\n\n orient : string, optional. Either \"records\" or \"lines\"\n If orient=\"records\" the file is saved as a single JSON array.\n ...
Please provide a description of the function:def _save_reference(self, filename): ## Save the SFrame url = _make_internal_url(filename) with cython_context(): self.__proxy__.save_reference(url)
[ "\n Performs an incomplete save of an existing SFrame into a directory.\n This saved SFrame may reference SFrames in other locations in the same\n filesystem for certain resources.\n\n Parameters\n ----------\n filename : string\n The location to save the SFrame....
Please provide a description of the function:def select_column(self, column_name): if not isinstance(column_name, str): raise TypeError("Invalid column_nametype: must be str") with cython_context(): return SArray(data=[], _proxy=self.__proxy__.select_column(column_name))
[ "\n Get a reference to the :class:`~turicreate.SArray` that corresponds with\n the given column_name. Throws an exception if the column_name is\n something other than a string or if the column name is not found.\n\n Parameters\n ----------\n column_name: str\n Th...
Please provide a description of the function:def add_column(self, data, column_name="", inplace=False): # Check type for pandas dataframe or SArray? if not isinstance(data, SArray): if isinstance(data, _Iterable): data = SArray(data) else...
[ "\n Returns an SFrame with a new column. The number of elements in the data\n given must match the length of every other column of the SFrame.\n If no name is given, a default name is chosen.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, re...
Please provide a description of the function:def add_columns(self, data, column_names=None, inplace=False): datalist = data if isinstance(data, SFrame): other = data datalist = [other.select_column(name) for name in other.column_names()] column_names = other....
[ "\n Returns an SFrame with multiple columns added. The number of\n elements in all columns must match the length of every other column of\n the SFrame.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, returning a new SFrame.\n\n If inpl...
Please provide a description of the function:def remove_column(self, column_name, inplace=False): column_name = str(column_name) if column_name not in self.column_names(): raise KeyError('Cannot find column %s' % column_name) colid = self.column_names().index(column_name) ...
[ "\n Returns an SFrame with a column removed.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, returning a new SFrame.\n\n If inplace == True, this operation modifies the current\n SFrame, returning self.\n\n Parameters\n --------...
Please provide a description of the function:def remove_columns(self, column_names, inplace=False): column_names = list(column_names) existing_columns = dict((k, i) for i, k in enumerate(self.column_names())) for name in column_names: if name not in existing_columns: ...
[ "\n Returns an SFrame with one or more columns removed.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, returning a new SFrame.\n\n If inplace == True, this operation modifies the current\n SFrame, returning self.\n\n Parameters\n ...
Please provide a description of the function:def swap_columns(self, column_name_1, column_name_2, inplace=False): colnames = self.column_names() colid_1 = colnames.index(column_name_1) colid_2 = colnames.index(column_name_2) if inplace: ret = self else: ...
[ "\n Returns an SFrame with two column positions swapped.\n\n If inplace == False (default) this operation does not modify the\n current SFrame, returning a new SFrame.\n\n If inplace == True, this operation modifies the current\n SFrame, returning self.\n\n Parameters\n ...
Please provide a description of the function:def rename(self, names, inplace=False): if (type(names) is not dict): raise TypeError('names must be a dictionary: oldname -> newname') all_columns = set(self.column_names()) for k in names: if not k in all_columns: ...
[ "\n Returns an SFrame with columns renamed. ``names`` is expected to be a\n dict specifying the old and new names. This changes the names of the\n columns given as the keys and replaces them with the names given as the\n values.\n\n If inplace == False (default) this operation doe...
Please provide a description of the function:def append(self, other): if type(other) is not SFrame: raise RuntimeError("SFrame append can only work with SFrame") left_empty = len(self.column_names()) == 0 right_empty = len(other.column_names()) == 0 if (left_empty ...
[ "\n Add the rows of an SFrame to the end of this SFrame.\n\n Both SFrames must have the same set of columns with the same column\n names and column types.\n\n Parameters\n ----------\n other : SFrame\n Another SFrame whose rows are appended to the current SFrame....
Please provide a description of the function:def groupby(self, key_column_names, operations, *args): # some basic checking first # make sure key_column_names is a list if isinstance(key_column_names, str): key_column_names = [key_column_names] # check that every colu...
[ "\n Perform a group on the key_column_names followed by aggregations on the\n columns listed in operations.\n\n The operations parameter is a dictionary that indicates which\n aggregation operators to use and which columns to use them on. The\n available operators are SUM, MAX, MI...
Please provide a description of the function:def join(self, right, on=None, how='inner'): available_join_types = ['left','right','outer','inner'] if not isinstance(right, SFrame): raise TypeError("Can only join two SFrames") if how not in available_join_types: ...
[ "\n Merge two SFrames. Merges the current (left) SFrame with the given\n (right) SFrame using a SQL-style equi-join operation by columns.\n\n Parameters\n ----------\n right : SFrame\n The SFrame to join.\n\n on : None | str | list | dict, optional\n T...
Please provide a description of the function:def filter_by(self, values, column_name, exclude=False): if type(column_name) is not str: raise TypeError("Must pass a str as column_name") existing_columns = self.column_names() if column_name not in existing_columns: ...
[ "\n Filter an SFrame by values inside an iterable object. Result is an\n SFrame that only includes (or excludes) the rows that have a column\n with the given ``column_name`` which holds one of the values in the\n given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an\n ...
Please provide a description of the function:def explore(self, title=None): import sys import os if sys.platform != 'darwin' and sys.platform != 'linux2' and sys.platform != 'linux': raise NotImplementedError('Visualization is currently supported only on macOS and Linux.')...
[ "\n Explore the SFrame in an interactive GUI. Opens a new app window.\n\n Parameters\n ----------\n title : str\n The plot title to show for the resulting visualization. Defaults to None.\n If the title is None, a default title will be provided.\n\n Returns\n...
Please provide a description of the function:def pack_columns(self, column_names=None, column_name_prefix=None, dtype=list, fill_na=None, remove_prefix=True, new_column_name=None): if column_names is not None and column_name_prefix is not None: raise ValueError("'colum...
[ "\n Pack columns of the current SFrame into one single column. The result\n is a new SFrame with the unaffected columns from the original SFrame\n plus the newly created column.\n\n The list of columns that are packed is chosen through either the\n ``column_names`` or ``column_nam...
Please provide a description of the function:def split_datetime(self, column_name, column_name_prefix=None, limit=None, timezone=False): if column_name not in self.column_names(): raise KeyError("column '" + column_name + "' does not exist in current SFrame") if column_name_prefix ...
[ "\n Splits a datetime column of SFrame to multiple columns, with each value in a\n separate column. Returns a new SFrame with the expanded column replaced with\n a list of new columns. The expanded column must be of datetime type.\n\n For more details regarding name generation and\n ...
Please provide a description of the function:def unpack(self, column_name=None, column_name_prefix=None, column_types=None, na_value=None, limit=None): if column_name is None: if self.num_columns()==0: raise RuntimeError("No column exists in the current SFrame...
[ "\n Expand one column of this SFrame to multiple columns with each value in\n a separate column. Returns a new SFrame with the unpacked column\n replaced with a list of new columns. The column must be of\n list/array/dict type.\n\n For more details regarding name generation, miss...
Please provide a description of the function:def stack(self, column_name, new_column_name=None, drop_na=False, new_column_type=None): # validate column_name column_name = str(column_name) if column_name not in self.column_names(): raise ValueError("Cannot find column '" + st...
[ "\n Convert a \"wide\" column of an SFrame to one or two \"tall\" columns by\n stacking all values.\n\n The stack works only for columns of dict, list, or array type. If the\n column is dict type, two new columns are created as a result of\n stacking: one column holds the key and...
Please provide a description of the function:def unstack(self, column_names, new_column_name=None): if (type(column_names) != str and len(column_names) != 2): raise TypeError("'column_names' parameter has to be either a string or a list of two strings.") with cython_context(): ...
[ "\n Concatenate values from one or two columns into one column, grouping by\n all other columns. The resulting column could be of type list, array or\n dictionary. If ``column_names`` is a numeric column, the result will be of\n array.array type. If ``column_names`` is a non-numeric co...
Please provide a description of the function:def sort(self, key_column_names, ascending=True): sort_column_names = [] sort_column_orders = [] # validate key_column_names if (type(key_column_names) == str): sort_column_names = [key_column_names] elif (type(ke...
[ "\n Sort current SFrame by the given columns, using the given sort order.\n Only columns that are type of str, int and float can be sorted.\n\n Parameters\n ----------\n key_column_names : str | list of str | list of (str, bool) pairs\n Names of columns to be sorted. T...
Please provide a description of the function:def dropna(self, columns=None, how='any'): # If the user gives me an empty list (the indicator to use all columns) # NA values being dropped would not be the expected behavior. This # is a NOOP, so let's not bother the server if type...
[ "\n Remove missing values from an SFrame. A missing value is either ``None``\n or ``NaN``. If ``how`` is 'any', a row will be removed if any of the\n columns in the ``columns`` parameter contains at least one missing\n value. If ``how`` is 'all', a row will be removed if all of the col...
Please provide a description of the function:def dropna_split(self, columns=None, how='any'): # If the user gives me an empty list (the indicator to use all columns) # NA values being dropped would not be the expected behavior. This # is a NOOP, so let's not bother the server i...
[ "\n Split rows with missing values from this SFrame. This function has the\n same functionality as :py:func:`~turicreate.SFrame.dropna`, but returns a\n tuple of two SFrames. The first item is the expected output from\n :py:func:`~turicreate.SFrame.dropna`, and the second item contains ...
Please provide a description of the function:def fillna(self, column_name, value): # Normal error checking if type(column_name) is not str: raise TypeError("column_name must be a str") ret = self[self.column_names()] ret[column_name] = ret[column_name].fillna(value) ...
[ "\n Fill all missing values with a given value in a given column. If the\n ``value`` is not the same type as the values in ``column_name``, this method\n attempts to convert the value to the original column's type. If this\n fails, an error is raised.\n\n Parameters\n -----...
Please provide a description of the function:def add_row_number(self, column_name='id', start=0, inplace=False): if type(column_name) is not str: raise TypeError("Must give column_name as strs") if type(start) is not int: raise TypeError("Must give start as int") ...
[ "\n Returns an SFrame with a new column that numbers each row\n sequentially. By default the count starts at 0, but this can be changed\n to a positive or negative number. The new column will be named with\n the given column name. An error will be raised if the given column\n na...
Please provide a description of the function:def AddSerializedFile(self, serialized_file_desc_proto): # pylint: disable=g-import-not-at-top from google.protobuf import descriptor_pb2 file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( serialized_file_desc_proto) self.Add(file_...
[ "Adds the FileDescriptorProto and its types to this pool.\n\n Args:\n serialized_file_desc_proto: A bytes string, serialization of the\n FileDescriptorProto to add.\n " ]
Please provide a description of the function:def AddDescriptor(self, desc): if not isinstance(desc, descriptor.Descriptor): raise TypeError('Expected instance of descriptor.Descriptor.') self._descriptors[desc.full_name] = desc self._AddFileDescriptor(desc.file)
[ "Adds a Descriptor to the pool, non-recursively.\n\n If the Descriptor contains nested messages or enums, the caller must\n explicitly register them. This method also registers the FileDescriptor\n associated with the message.\n\n Args:\n desc: A Descriptor.\n " ]
Please provide a description of the function:def AddServiceDescriptor(self, service_desc): if not isinstance(service_desc, descriptor.ServiceDescriptor): raise TypeError('Expected instance of descriptor.ServiceDescriptor.') self._service_descriptors[service_desc.full_name] = service_desc
[ "Adds a ServiceDescriptor to the pool.\n\n Args:\n service_desc: A ServiceDescriptor.\n " ]
Please provide a description of the function:def AddExtensionDescriptor(self, extension): if not (isinstance(extension, descriptor.FieldDescriptor) and extension.is_extension): raise TypeError('Expected an extension descriptor.') if extension.extension_scope is None: self._toplevel...
[ "Adds a FieldDescriptor describing an extension to the pool.\n\n Args:\n extension: A FieldDescriptor.\n\n Raises:\n AssertionError: when another extension with the same number extends the\n same message.\n TypeError: when the specified extension is not a\n descriptor.FieldDescrip...
Please provide a description of the function:def AddFileDescriptor(self, file_desc): self._AddFileDescriptor(file_desc) # TODO(jieluo): This is a temporary solution for FieldDescriptor.file. # Remove it when FieldDescriptor.file is added in code gen. for extension in file_desc.extensions_by_name.v...
[ "Adds a FileDescriptor to the pool, non-recursively.\n\n If the FileDescriptor contains messages or enums, the caller must explicitly\n register them.\n\n Args:\n file_desc: A FileDescriptor.\n " ]
Please provide a description of the function:def _AddFileDescriptor(self, file_desc): if not isinstance(file_desc, descriptor.FileDescriptor): raise TypeError('Expected instance of descriptor.FileDescriptor.') self._file_descriptors[file_desc.name] = file_desc
[ "Adds a FileDescriptor to the pool, non-recursively.\n\n If the FileDescriptor contains messages or enums, the caller must explicitly\n register them.\n\n Args:\n file_desc: A FileDescriptor.\n " ]
Please provide a description of the function:def FindFileByName(self, file_name): try: return self._file_descriptors[file_name] except KeyError: pass try: file_proto = self._internal_db.FindFileByName(file_name) except KeyError as error: if self._descriptor_db: fil...
[ "Gets a FileDescriptor by file name.\n\n Args:\n file_name: The path to the file to get a descriptor for.\n\n Returns:\n A FileDescriptor for the named file.\n\n Raises:\n KeyError: if the file cannot be found in the pool.\n " ]
Please provide a description of the function:def FindFileContainingSymbol(self, symbol): symbol = _NormalizeFullyQualifiedName(symbol) try: return self._descriptors[symbol].file except KeyError: pass try: return self._enum_descriptors[symbol].file except KeyError: pass...
[ "Gets the FileDescriptor for the file containing the specified symbol.\n\n Args:\n symbol: The name of the symbol to search for.\n\n Returns:\n A FileDescriptor that contains the specified symbol.\n\n Raises:\n KeyError: if the file cannot be found in the pool.\n " ]
Please provide a description of the function:def FindMessageTypeByName(self, full_name): full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._descriptors: self._FindFileContainingSymbolInDb(full_name) return self._descriptors[full_name]
[ "Loads the named descriptor from the pool.\n\n Args:\n full_name: The full name of the descriptor to load.\n\n Returns:\n The descriptor for the named type.\n\n Raises:\n KeyError: if the message cannot be found in the pool.\n " ]
Please provide a description of the function:def FindEnumTypeByName(self, full_name): full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._enum_descriptors: self._FindFileContainingSymbolInDb(full_name) return self._enum_descriptors[full_name]
[ "Loads the named enum descriptor from the pool.\n\n Args:\n full_name: The full name of the enum descriptor to load.\n\n Returns:\n The enum descriptor for the named type.\n\n Raises:\n KeyError: if the enum cannot be found in the pool.\n " ]
Please provide a description of the function:def FindFieldByName(self, full_name): full_name = _NormalizeFullyQualifiedName(full_name) message_name, _, field_name = full_name.rpartition('.') message_descriptor = self.FindMessageTypeByName(message_name) return message_descriptor.fields_by_name[field...
[ "Loads the named field descriptor from the pool.\n\n Args:\n full_name: The full name of the field descriptor to load.\n\n Returns:\n The field descriptor for the named field.\n\n Raises:\n KeyError: if the field cannot be found in the pool.\n " ]
Please provide a description of the function:def FindServiceByName(self, full_name): full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._service_descriptors: self._FindFileContainingSymbolInDb(full_name) return self._service_descriptors[full_name]
[ "Loads the named service descriptor from the pool.\n\n Args:\n full_name: The full name of the service descriptor to load.\n\n Returns:\n The service descriptor for the named service.\n\n Raises:\n KeyError: if the service cannot be found in the pool.\n " ]
Please provide a description of the function:def _FindFileContainingSymbolInDb(self, symbol): try: file_proto = self._internal_db.FindFileContainingSymbol(symbol) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileContainingSymbol(symbol) el...
[ "Finds the file in descriptor DB containing the specified symbol.\n\n Args:\n symbol: The name of the symbol to search for.\n\n Returns:\n A FileDescriptor that contains the specified symbol.\n\n Raises:\n KeyError: if the file cannot be found in the descriptor database.\n " ]
Please provide a description of the function:def _ConvertFileProtoToFileDescriptor(self, file_proto): if file_proto.name not in self._file_descriptors: built_deps = list(self._GetDeps(file_proto.dependency)) direct_deps = [self.FindFileByName(n) for n in file_proto.dependency] public_deps = ...
[ "Creates a FileDescriptor from a proto or returns a cached copy.\n\n This method also has the side effect of loading all the symbols found in\n the file into the appropriate dictionaries in the pool.\n\n Args:\n file_proto: The proto to convert.\n\n Returns:\n A FileDescriptor matching the pas...
Please provide a description of the function:def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None, scope=None, syntax=None): if package: desc_name = '.'.join((package, desc_proto.name)) else: desc_name = desc_proto.name if file_desc ...
[ "Adds the proto to the pool in the specified package.\n\n Args:\n desc_proto: The descriptor_pb2.DescriptorProto protobuf message.\n package: The package the proto should be located in.\n file_desc: The file containing this message.\n scope: Dict mapping short and full symbols to message and ...
Please provide a description of the function:def _SetAllFieldTypes(self, package, desc_proto, scope): package = _PrefixWithDot(package) main_desc = self._GetTypeFromScope(package, desc_proto.name, scope) if package == '.': nested_package = _PrefixWithDot(desc_proto.name) else: nested...
[ "Sets all the descriptor's fields's types.\n\n This method also sets the containing types on any extensions.\n\n Args:\n package: The current package of desc_proto.\n desc_proto: The message descriptor to update.\n scope: Enclosing scope of available types.\n " ]
Please provide a description of the function:def _SetFieldType(self, field_proto, field_desc, package, scope): if field_proto.type_name: desc = self._GetTypeFromScope(package, field_proto.type_name, scope) else: desc = None if not field_proto.HasField('type'): if isinstance(desc, des...
[ "Sets the field's type, cpp_type, message_type and enum_type.\n\n Args:\n field_proto: Data about the field in proto format.\n field_desc: The descriptor to modiy.\n package: The package the field's container is in.\n scope: Enclosing scope of available types.\n " ]
Please provide a description of the function:def _MakeEnumValueDescriptor(self, value_proto, index): return descriptor.EnumValueDescriptor( name=value_proto.name, index=index, number=value_proto.number, options=_OptionsOrNone(value_proto), type=None)
[ "Creates a enum value descriptor object from a enum value proto.\n\n Args:\n value_proto: The proto describing the enum value.\n index: The index of the enum value.\n\n Returns:\n An initialized EnumValueDescriptor object.\n " ]
Please provide a description of the function:def _MakeServiceDescriptor(self, service_proto, service_index, scope, package, file_desc): if package: service_name = '.'.join((package, service_proto.name)) else: service_name = service_proto.name methods = [self._...
[ "Make a protobuf ServiceDescriptor given a ServiceDescriptorProto.\n\n Args:\n service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message.\n service_index: The index of the service in the File.\n scope: Dict mapping short and full symbols to message and enum types.\n package: O...
Please provide a description of the function:def _MakeMethodDescriptor(self, method_proto, service_name, package, scope, index): full_name = '.'.join((service_name, method_proto.name)) input_type = self._GetTypeFromScope( package, method_proto.input_type, scope) outp...
[ "Creates a method descriptor from a MethodDescriptorProto.\n\n Args:\n method_proto: The proto describing the method.\n service_name: The name of the containing service.\n package: Optional package name to look up for types.\n scope: Scope containing available types.\n index: Index of th...
Please provide a description of the function:def _ExtractSymbols(self, descriptors): for desc in descriptors: yield (_PrefixWithDot(desc.full_name), desc) for symbol in self._ExtractSymbols(desc.nested_types): yield symbol for enum in desc.enum_types: yield (_PrefixWithDot(en...
[ "Pulls out all the symbols from descriptor protos.\n\n Args:\n descriptors: The messages to extract descriptors from.\n Yields:\n A two element tuple of the type name and descriptor object.\n " ]
Please provide a description of the function:def _GetDeps(self, dependencies): for dependency in dependencies: dep_desc = self.FindFileByName(dependency) yield dep_desc for parent_dep in dep_desc.dependencies: yield parent_dep
[ "Recursively finds dependencies for file protos.\n\n Args:\n dependencies: The names of the files being depended on.\n\n Yields:\n Each direct and indirect dependency.\n " ]
Please provide a description of the function:def _GetTypeFromScope(self, package, type_name, scope): if type_name not in scope: components = _PrefixWithDot(package).split('.') while components: possible_match = '.'.join(components + [type_name]) if possible_match in scope: ...
[ "Finds a given type name in the current scope.\n\n Args:\n package: The package the proto should be located in.\n type_name: The name of the type to be found in the scope.\n scope: Dict mapping short and full symbols to message and enum types.\n\n Returns:\n The descriptor for the requeste...
Please provide a description of the function:def max_element (elements, ordered = None): assert is_iterable(elements) assert callable(ordered) or ordered is None if not ordered: ordered = operator.lt max = elements [0] for e in elements [1:]: if ordered (max, e): max = e ...
[ " Returns the maximum number in 'elements'. Uses 'ordered' for comparisons,\n or '<' is none is provided.\n " ]
Please provide a description of the function:def select_highest_ranked (elements, ranks): assert is_iterable(elements) assert is_iterable(ranks) if not elements: return [] max_rank = max_element (ranks) result = [] while elements: if ranks [0] == max_rank: resu...
[ " Returns all of 'elements' for which corresponding element in parallel\n list 'rank' is equal to the maximum value in 'rank'.\n " ]
Please provide a description of the function:def CopyFrom(self, other_msg): if self is other_msg: return self.Clear() self.MergeFrom(other_msg)
[ "Copies the content of the specified message into the current message.\n\n The method clears the current message and then merges the specified\n message using MergeFrom.\n\n Args:\n other_msg: Message to copy into the current one.\n " ]
Please provide a description of the function:def recurse_json(mlkit_tree, xgb_tree_json, tree_id, node_id, feature_map, force_32bit_float): relative_hit_rate = None try: relative_hit_rate = xgb_tree_json['cover'] except KeyError: pass # Fill node attributes if 'leaf' ...
[ "Traverse through the tree and append to the tree spec.\n " ]
Please provide a description of the function:def convert_tree_ensemble(model, feature_names, target, force_32bit_float): if not(_HAS_XGBOOST): raise RuntimeError('xgboost not found. xgboost conversion API is disabled.') import json import os feature_map = None if isinstance(model, (_x...
[ "Convert a generic tree model to the protobuf spec.\n\n This currently supports:\n * Decision tree regression\n\n Parameters\n ----------\n model: str | Booster\n Path on disk where the XGboost JSON representation of the model is or\n a handle to the XGboost model.\n\n feature_name...
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.') # Make sure the model is fitted. _sklearn_util.check_expected_type(model, OneHotEncoder...
[ "Convert a one-hot-encoder model to the protobuf spec.\n\n Parameters\n ----------\n model: OneHotEncoder\n A trained one-hot encoder model.\n\n input_features: str, optional\n Name of the input column.\n\n output_features: str, optional\n Name of the output column.\n\n Return...
Please provide a description of the function:def update_dimension(model, input_dimension): if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'active_features_')) _sklearn_util.chec...
[ "\n Given a model that takes an array of dimension input_dimension, returns\n the output dimension.\n " ]
Please provide a description of the function:def convert_reshape(net, node, module, builder): input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) target_shape = literal_eval(param['shape']) if target_shape == (0, -1): convert_flatten(n...
[ "Converts a reshape layer from mxnet to coreml.\n\n This doesn't currently handle the deprecated parameters for the reshape layer.\n\n Parameters\n ----------\n net: network\n An mxnet network object.\n\n node: layer\n Node to convert.\n\n module: module\n A module for MXNet\n...
Please provide a description of the function:def convert_elementwise_mul_scalar(net, node, module, builder): import numpy input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) mult = literal_eval(param['scalar']) builder.add_scale(name=name...
[ "Convert a scalar multiplication from mxnet to coreml.\n\n Parameters\n ----------\n net: network\n A mxnet network object.\n\n node: layer\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n...
Please provide a description of the function:def convert_dense(net, node, module, builder): input_name, output_name = _get_input_output_name(net, node) has_bias = True name = node['name'] inputs = node['inputs'] args, _ = module.get_params() W = args[_get_node_name(net, inputs[1][0])].asnu...
[ "Convert a dense layer from mxnet to coreml.\n\n Parameters\n ----------\n net: network\n A mxnet network object.\n\n node: layer\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_padding(net, node, module, builder): input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) pad = literal_eval(param['pad_width']) pad_left = pad[4] pad_top = pad[5] pad_right = ...
[ "Convert a padding layer from mxnet to coreml.\n\n Parameters\n ----------\n net: network\n A mxnet network object.\n\n node: layer\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_upsample(net, node, module, builder): input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) inputs = node['inputs'] args, _ = module.get_params() scale = literal_eval(param['scale']) ...
[ "Convert a UpSampling layer from mxnet to coreml.\n\n Parameters\n ----------\n net: network\n A mxnet network object.\n\n node: layer\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "...
Please provide a description of the function:def convert_softmax(net, node, module, builder): input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) if param is not None and 'axis' in param: axis = literal_eval(param['axis']) assert ...
[ "Convert a softmax layer from mxnet to coreml.\n\n Parameters\n ----------\n net: network\n A mxnet network object.\n\n node: layer\n Node to convert.\n\n module: module\n An module for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_custom(net, node, module, builder): input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) if param['op_type'] == 'special-darknet-maxpool': _add_pooling.add_pooling_with_padding_types(...
[ "Convert highly specific ops" ]
Please provide a description of the function:def convert_embedding(net, node, model, builder): input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] outputs = node['outputs'] arg_params, aux_params = model.get_params() W = arg_params[_get_no...
[ "Convert an embedding layer from mxnet to coreml.\n\n Parameters\n ----------\n net: network\n A mxnet network object.\n\n node: layer\n Node to convert.\n\n model: model\n An model for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_scalar_add(net, node, model, builder): import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) mode = 'ADD' alpha = _np.array([float(param['scalar'])]) builder.ad...
[ "Convert a scalar add layer from mxnet to coreml.\n\n Parameters\n ----------\n net: network\n A mxnet network object.\n\n node: layer\n Node to convert.\n\n model: model\n An model for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n " ]
Please provide a description of the function:def convert_scalar_multiply(net, node, model, builder): import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] param = _get_attr(node) alpha = _np.array([float(param['scalar'])]) builder.add_scale(name...
[ "Convert a scalar multiply layer from mxnet to coreml.\n\n Parameters\n ----------\n net: network\n A mxnet network object.\n\n node: layer\n Node to convert.\n\n model: model\n An model for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n ...
Please provide a description of the function:def convert_instancenorm(net, node, model, builder): import numpy as _np input_name, output_name = _get_input_output_name(net, node) name = node['name'] inputs = node['inputs'] outputs = node['outputs'] data_blob_name = _get_node_name(net, inp...
[ "Convert an instance norm layer from mxnet to coreml.\n\n Parameters\n ----------\n net: network\n A mxnet network object.\n\n node: layer\n Node to convert.\n\n model: model\n An model for MXNet\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n ...
Please provide a description of the function:def _get_aws_credentials(): if (not 'AWS_ACCESS_KEY_ID' in _os.environ): raise KeyError('No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.') if (not 'AWS_SECRET_ACCESS_KEY' in _os.environ): raise KeyError('No secret key...
[ "\n Returns the values stored in the AWS credential environment variables.\n Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and\n the value stored in the AWS_SECRET_ACCESS_KEY environment variable.\n\n Returns\n -------\n out : tuple [string]\n The first string of th...
Please provide a description of the function:def _try_inject_s3_credentials(url): assert url.startswith('s3://') path = url[5:] # Check if the path already contains credentials tokens = path.split(':') # If there are two ':', its possible that we have already injected credentials if len(tok...
[ "\n Inject aws credentials into s3 url as s3://[aws_id]:[aws_key]:[bucket/][objectkey]\n\n If s3 url already contains secret key/id pairs, just return as is.\n " ]
Please provide a description of the function:def _make_internal_url(url): if not url: raise ValueError('Invalid url: %s' % url) from .. import _sys_util from . import _file_util # Convert Windows paths to Unix-style slashes url = _convert_slashes(url) # Try to split the url into ...
[ "\n Process user input url string with proper normalization\n For all urls:\n Expands ~ to $HOME\n For S3 urls:\n Returns the s3 URL with credentials filled in using turicreate.aws.get_aws_credential().\n For example: \"s3://mybucket/foo\" -> \"s3://$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY:...
Please provide a description of the function:def is_directory_archive(path): if path is None: return False if not _os.path.isdir(path): return False ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini']) if not _os.path.exists(ini_path): return False if _os...
[ "\n Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it.\n\n SFrames are written to disk as a directory archive, this function identifies if a given directory is an archive\n for an SFrame.\n\n Parameters\n ----------\n path : string\n D...
Please provide a description of the function:def get_archive_type(path): if not is_directory_archive(path): raise TypeError('Unable to determine the type of archive at path: %s' % path) try: ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini']) parser = _ConfigParser.Saf...
[ "\n Returns the contents type for the provided archive path.\n\n Parameters\n ----------\n path : string\n Directory to evaluate.\n\n Returns\n -------\n Returns a string of: sframe, sgraph, raises TypeError for anything else\n " ]
Please provide a description of the function:def crossproduct(d): from .. import SArray d = [list(zip(list(d.keys()), x)) for x in _itertools.product(*list(d.values()))] sa = [{k:v for (k,v) in x} for x in d] return SArray(sa).unpack(column_name_prefix='')
[ "\n Create an SFrame containing the crossproduct of all provided options.\n\n Parameters\n ----------\n d : dict\n Each key is the name of an option, and each value is a list\n of the possible values for that option.\n\n Returns\n -------\n out : SFrame\n There will be a co...
Please provide a description of the function:def get_turicreate_object_type(url): ''' Given url where a Turi Create object is persisted, return the Turi Create object type: 'model', 'graph', 'sframe', or 'sarray' ''' from .._connect import main as _glconnect ret = _glconnect.get_unity().get_turi...
[]
Please provide a description of the function:def _assert_sframe_equal(sf1, sf2, check_column_names=True, check_column_order=True, check_row_order=True, float_column_delta=None): from .. ...
[ "\n Assert the two SFrames are equal.\n\n The default behavior of this function uses the strictest possible\n definition of equality, where all columns must be in the same order, with\n the same names and have the same data in the same order. Each of these\n stipulations can be relaxed individually ...
Please provide a description of the function:def _get_temp_file_location(): ''' Returns user specified temporary file location. The temporary location is specified through: >>> turicreate.config.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...) ''' from .._connect import main as _glconnect ...
[]
Please provide a description of the function:def _make_temp_directory(prefix): ''' Generate a temporary directory that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the directory is no longer needed. But the directory will be cleaned as ...
[]
Please provide a description of the function:def _make_temp_filename(prefix): ''' Generate a temporary file that would not live beyond the lifetime of unity_server. Caller is expected to clean up the temp file as soon as the file is no longer needed. But temp files created using this method will be...
[]
Please provide a description of the function:def _pickle_to_temp_location_or_memory(obj): ''' If obj can be serialized directly into memory (via cloudpickle) this will return the serialized bytes. Otherwise, gl_pickle is attempted and it will then generates a temporary directory ...
[]
Please provide a description of the function:def _get_cuda_gpus(): import subprocess try: output = subprocess.check_output(['nvidia-smi', '--query-gpu=index,gpu_name,memory.free,memory.total', '--format=csv,noheader...
[ "\n Returns a list of dictionaries, with the following keys:\n - index (integer, device index of the GPU)\n - name (str, GPU name)\n - memory_free (float, free memory in MiB)\n - memory_total (float, total memory in MiB)\n " ]
Please provide a description of the function:def _ParameterDecorator(naming_type, testcases): def _Apply(obj): if isinstance(obj, type): _ModifyClass( obj, list(testcases) if not isinstance(testcases, collections.Sequence) else testcases, naming_type) return ...
[ "Implementation of the parameterization decorators.\n\n Args:\n naming_type: The naming type.\n testcases: Testcase parameters.\n\n Returns:\n A function for modifying the decorated object.\n " ]